Spaces:
Sleeping
Sleeping
Update app/utils.py
Browse files- app/utils.py +22 -26
app/utils.py
CHANGED
@@ -137,28 +137,23 @@ class AllergyAnalyzer:
|
|
137 |
tokens = nltk.word_tokenize(text)
|
138 |
return [w.lower() for w in tokens if w.isalpha()]
|
139 |
|
140 |
-
def
|
141 |
-
"""
|
142 |
results = []
|
143 |
-
for allergy in
|
144 |
-
if
|
145 |
results.append(allergy)
|
146 |
return results
|
147 |
|
148 |
-
def check_allergy_risk(self, ingredient,
|
149 |
"""الاستعلام من Claude API عن الحساسيات"""
|
150 |
prompt = f"""
|
151 |
-
You are a professional food safety expert specializing in allergen classification
|
|
|
|
|
152 |
|
153 |
-
|
154 |
-
|
155 |
-
⚠️ *Important Guidelines:*
|
156 |
-
- Base your answer strictly on scientific classification and allergen presence.
|
157 |
-
- Do NOT rely solely on word similarity—consider actual ingredient composition.
|
158 |
-
- If '{ingredient}' contains {allergy_type} proteins or poses a high cross-allergy risk, answer *'Yes'*.
|
159 |
-
- If it is completely unrelated and safe for individuals with {allergy_type} allergies, answer *'No'*.
|
160 |
-
|
161 |
-
🚨 *Final Answer:* Only respond with *'Yes'* or *'No'*. Do NOT provide explanations.
|
162 |
"""
|
163 |
url = "https://api.anthropic.com/v1/messages"
|
164 |
headers = {
|
@@ -178,14 +173,15 @@ Please analyze the ingredient '{ingredient}' and determine whether it contains o
|
|
178 |
json_response = response.json()
|
179 |
|
180 |
if "content" in json_response and isinstance(json_response["content"], list):
|
181 |
-
|
182 |
-
|
|
|
183 |
|
184 |
except Exception as e:
|
185 |
logger.error(f"Error querying Claude API: {str(e)}")
|
186 |
-
return
|
187 |
|
188 |
-
def analyze_image(self, image,
|
189 |
"""تحليل الصورة مباشرة للكشف عن الحساسيات"""
|
190 |
try:
|
191 |
# استخراج النص من الصورة
|
@@ -200,7 +196,7 @@ Please analyze the ingredient '{ingredient}' and determine whether it contains o
|
|
200 |
|
201 |
# التحقق من كل token في قاعدة البيانات
|
202 |
for token in tokens:
|
203 |
-
db_results = self.
|
204 |
|
205 |
if db_results:
|
206 |
for allergy in db_results:
|
@@ -210,12 +206,12 @@ Please analyze the ingredient '{ingredient}' and determine whether it contains o
|
|
210 |
database_matches[allergy].append(token)
|
211 |
elif claude_api_key:
|
212 |
# إذا لم توجد في قاعدة البيانات، نستخدم Claude API
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
|
220 |
return {
|
221 |
"extracted_text": extracted_text,
|
|
|
137 |
tokens = nltk.word_tokenize(text)
|
138 |
return [w.lower() for w in tokens if w.isalpha()]
|
139 |
|
140 |
+
def find_allergy_for_token(self, token):
|
141 |
+
"""البحث عن الحساسية المقابلة للتوكن في ملف الإكسل"""
|
142 |
results = []
|
143 |
+
for allergy, ingredients in self.allergy_dict.items():
|
144 |
+
if token in ingredients:
|
145 |
results.append(allergy)
|
146 |
return results
|
147 |
|
148 |
+
def check_allergy_risk(self, ingredient, api_key):
|
149 |
"""الاستعلام من Claude API عن الحساسيات"""
|
150 |
prompt = f"""
|
151 |
+
You are a professional food safety expert specializing in allergen classification.
|
152 |
+
Please analyze the ingredient '{ingredient}' and determine which of the following major allergen categories it belongs to:
|
153 |
+
dairy, eggs, peanuts, soy, tree nuts, wheat, fish, shellfish, sesame.
|
154 |
|
155 |
+
Return only the allergen category name if found, or 'None' if not found.
|
156 |
+
Example responses: 'dairy', 'eggs', 'None', etc.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
"""
|
158 |
url = "https://api.anthropic.com/v1/messages"
|
159 |
headers = {
|
|
|
173 |
json_response = response.json()
|
174 |
|
175 |
if "content" in json_response and isinstance(json_response["content"], list):
|
176 |
+
result = json_response["content"][0]["text"].strip().lower()
|
177 |
+
return result if result in self.allergy_dict else None
|
178 |
+
return None
|
179 |
|
180 |
except Exception as e:
|
181 |
logger.error(f"Error querying Claude API: {str(e)}")
|
182 |
+
return None
|
183 |
|
184 |
+
def analyze_image(self, image, claude_api_key=None):
|
185 |
"""تحليل الصورة مباشرة للكشف عن الحساسيات"""
|
186 |
try:
|
187 |
# استخراج النص من الصورة
|
|
|
196 |
|
197 |
# التحقق من كل token في قاعدة البيانات
|
198 |
for token in tokens:
|
199 |
+
db_results = self.find_allergy_for_token(token)
|
200 |
|
201 |
if db_results:
|
202 |
for allergy in db_results:
|
|
|
206 |
database_matches[allergy].append(token)
|
207 |
elif claude_api_key:
|
208 |
# إذا لم توجد في قاعدة البيانات، نستخدم Claude API
|
209 |
+
api_result = self.check_allergy_risk(token, claude_api_key)
|
210 |
+
if api_result:
|
211 |
+
detected_allergens.add(api_result)
|
212 |
+
if api_result not in claude_matches:
|
213 |
+
claude_matches[api_result] = []
|
214 |
+
claude_matches[api_result].append(token)
|
215 |
|
216 |
return {
|
217 |
"extracted_text": extracted_text,
|