food_scanning/helpers.py
2025-02-28 12:36:45 +05:30

26 lines
881 B
Python

import base64
import json
import re
def jpeg_to_base64(file_path):
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string.decode('utf-8')
def extract_json_to_dict(input_string):
# Use regex to extract JSON content
json_pattern = re.compile(r"\{.*\}", re.DOTALL) # DOTALL allows matching across multiple lines
match = json_pattern.search(input_string)
if match:
json_content = match.group(0) # Extract the matched JSON content
try:
# Convert the JSON string to a dictionary
json_dict = json.loads(json_content)
return json_dict
except json.JSONDecodeError:
print("Error: Extracted content is not valid JSON.")
return None
else:
print("No JSON content found.")
return None