benedictpepper commited on
Commit
a160fef
ยท
verified ยท
1 Parent(s): 955006e

๐Ÿš€ Automated deployment backend API by VS Code AI

Browse files
database/data/tcm_500_ingredients.json ADDED
The diff for this file is too large to render. See raw diff
 
database/generate_500.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+
5
+ sys.path.insert(0, 'backend')
6
+ from database.seed_100_tcm import POPULAR_TCM
7
+
8
+ meridian_id_map = {
9
+ 'lung': 'Paru-paru',
10
+ 'liver': 'Hati',
11
+ 'kidney': 'Ginjal',
12
+ 'heart': 'Jantung',
13
+ 'spleen': 'Limpa / Pencernaan',
14
+ 'stomach': 'Lambung',
15
+ 'large intestine': 'Usus Besar',
16
+ 'small intestine': 'Usus Halus',
17
+ 'bladder': 'Kandung Kemih',
18
+ 'gallbladder': 'Kantung Empedu',
19
+ 'pericardium': 'Perikardium',
20
+ 'triple energizer': 'San Jiao',
21
+ }
22
+
23
+ def translate_meridians(mer_eng):
24
+ if not mer_eng:
25
+ return 'Umum'
26
+ parts = [str(p).strip().lower() for p in str(mer_eng).split(',')]
27
+ res = []
28
+ for p in parts:
29
+ if p in meridian_id_map:
30
+ res.append(meridian_id_map[p])
31
+ elif p:
32
+ res.append(p.capitalize())
33
+ return ', '.join(dict.fromkeys(res)) if res else 'Umum'
34
+
35
+ def get_desc(cls_eng, prop_eng, name_eng):
36
+ c = str(cls_eng or '').lower()
37
+ p = str(prop_eng or '').lower()
38
+ if 'antitussive' in c or 'asthma' in c:
39
+ return 'Pereda batuk, peluruh dahak, dan kesehatan saluran pernapasan'
40
+ if 'heat-clearing' in c:
41
+ return 'Pereda panas dalam, anti-radang, dan detoksifikasi racun panas'
42
+ if 'hemostatic' in c:
43
+ return 'Penghenti pendarahan dan pemulihan luka jaringan'
44
+ if 'tonif' in c or 'replenish' in c:
45
+ return 'Herbal tonik peningkat stamina, daya tahan tubuh, dan energi vital'
46
+ if 'blood' in c:
47
+ return 'Memperlancar sirkulasi darah dan meredakan nyeri akibat penyumbatan'
48
+ if 'exterior' in c:
49
+ return 'Meredakan gejala awal flu, demam, masuk angin, dan sakit kepala'
50
+ if 'damp' in c or 'diuretic' in c:
51
+ return 'Mengeluarkan kelembaban tubuh berlebih dan melancarkan buang air'
52
+ if 'digest' in c or 'stomachic' in c:
53
+ return 'Memperbaiki fungsi lambung dan mengoptimalkan pencernaan'
54
+ if 'calm' in c or 'sedat' in c:
55
+ return 'Menenangkan pikiran, meredakan kecemasan, dan mengatasi insomnia'
56
+ if 'interior-warm' in c or 'cold-dispell' in c:
57
+ return 'Menghangatkan tubuh bagian dalam dan mengusir dingin'
58
+ if 'purgative' in c:
59
+ return 'Pencahar alami untuk melancarkan buang air besar'
60
+ if 'toxic' in p:
61
+ return 'Herbal berkandungan toksik keras, diawasi ketat dan dilarang penggunaan mandiri'
62
+ return 'Bahan herbal alami terdaftar untuk terapi kesehatan holistik'
63
+
64
+ items = []
65
+ seen = set()
66
+
67
+ def add_entry(mandarin, pinyin, indo, eng, lat, is_toxic, lvl, organ, desc, src):
68
+ key = (mandarin or '').strip().lower()
69
+ if not key:
70
+ key = (pinyin or '').strip().lower()
71
+ if not key:
72
+ key = (indo or '').strip().lower()
73
+ if key in seen:
74
+ return False
75
+ seen.add(key)
76
+ items.append({
77
+ 'mandarin_name': (mandarin or '').strip(),
78
+ 'pinyin_name': (pinyin or '').strip(),
79
+ 'indonesian_name': (indo or '').strip(),
80
+ 'english_name': (eng or '').strip(),
81
+ 'latin_name': (lat or '').strip(),
82
+ 'is_toxic': bool(is_toxic),
83
+ 'toxicity_level': lvl or ('high' if is_toxic else 'none'),
84
+ 'toxicity_class': 'toxic' if is_toxic else 'safe',
85
+ 'target_organ': organ or 'Umum',
86
+ 'description': desc or '',
87
+ 'source_reference': src or 'BPOM-TI',
88
+ 'validated_by': 'fitmate_verified'
89
+ })
90
+ return True
91
+
92
+ # 1. Add all 101 POPULAR_TCM
93
+ for m, p, i, e, tox, lvl, org, d, src in POPULAR_TCM:
94
+ lat = i if (' ' in i and '/' not in i) else ''
95
+ add_entry(m, p, i, e, lat, tox, lvl, org, d, src)
96
+
97
+ print('Stage 1 (POPULAR_TCM):', len(items))
98
+
99
+ # 2. Add BPOM OTSKK herbs
100
+ try:
101
+ with open('data/scraper/output/bpom_ingredients.json', 'r', encoding='utf-8') as f:
102
+ bpom_raw = json.load(f)
103
+ for b in bpom_raw:
104
+ indo_name = str(b.get('indonesian_name') or '').strip()
105
+ lat_name = str(b.get('latin_name') or '').strip()
106
+ if not indo_name:
107
+ continue
108
+ exists = any(indo_name.lower() == it['indonesian_name'].lower() for it in items)
109
+ if not exists:
110
+ add_entry(
111
+ b.get('mandarin_name', ''),
112
+ b.get('pinyin_name', ''),
113
+ indo_name,
114
+ indo_name,
115
+ lat_name,
116
+ False,
117
+ 'none',
118
+ 'Pencernaan / Hati',
119
+ 'Tanaman obat terdaftar BPOM OTSKK untuk sediaan herbal Indonesia',
120
+ b.get('bpom_reference', 'BPOM-OTSKK')
121
+ )
122
+ except Exception as err:
123
+ print('BPOM load warning:', err)
124
+
125
+ print('Stage 2 (+BPOM):', len(items))
126
+
127
+ # 3. Add SymMap toxic herbs
128
+ with open('data/scraper/output/symmap_herbs_raw.json', 'r', encoding='utf-8') as f:
129
+ symmap = json.load(f)
130
+
131
+ def is_sym_toxic(s):
132
+ p = str(s.get('Properties_English') or '').lower()
133
+ c = str(s.get('Class_English') or '').lower()
134
+ return 'toxic' in p or 'toxic' in c
135
+
136
+ sym_toxic = [s for s in symmap if is_sym_toxic(s)]
137
+ sym_safe = [s for s in symmap if not is_sym_toxic(s)]
138
+
139
+ for s in sym_toxic:
140
+ if len(items) >= 500:
141
+ break
142
+ m = s.get('Chinese_name') or ''
143
+ p = s.get('Pinyin_name') or ''
144
+ e = s.get('English_name') or ''
145
+ lat = str(s.get('Latin_name') or '').split(',')[0].strip()
146
+ props = str(s.get('Properties_English') or '')
147
+ meridians = translate_meridians(s.get('Meridians_English'))
148
+
149
+ props_lower = props.lower()
150
+ lvl = 'high' if ('extremely toxic' in props_lower or 'great toxic' in props_lower) else 'moderate' if 'toxic' in props_lower else 'low'
151
+ desc = f'Herbal berkandungan toksik ({props}). Diawasi ketat dan dilarang penggunaan mandiri tanpa pengawasan apoteker.'
152
+ indo = p or e or lat
153
+ add_entry(m, p, indo, e or p, lat, True, lvl, meridians, desc, 'SymMap-Toxic')
154
+
155
+ print('Stage 3 (+SymMap Toxic):', len(items))
156
+
157
+ # 4. Add SymMap safe herbs until exactly 500
158
+ for s in sym_safe:
159
+ if len(items) >= 500:
160
+ break
161
+ m = s.get('Chinese_name') or ''
162
+ p = s.get('Pinyin_name') or ''
163
+ e = s.get('English_name') or ''
164
+ lat = str(s.get('Latin_name') or '').split(',')[0].strip()
165
+ cls_e = s.get('Class_English') or ''
166
+ props = s.get('Properties_English') or ''
167
+ meridians = translate_meridians(s.get('Meridians_English'))
168
+
169
+ desc = get_desc(cls_e, props, e)
170
+ indo = p or e or lat
171
+ add_entry(m, p, indo, e or p, lat, False, 'none', meridians, desc, 'SymMap')
172
+
173
+ print('Final total items:', len(items))
174
+
175
+ toxic_count = sum(1 for it in items if it['is_toxic'])
176
+ safe_count = sum(1 for it in items if not it['is_toxic'])
177
+ print(f'Breakdown: {toxic_count} toxic / restricted, {safe_count} safe herbs')
178
+
179
+ # Save both to backend and frontend
180
+ os.makedirs('backend/database/data', exist_ok=True)
181
+ with open('backend/database/data/tcm_500_ingredients.json', 'w', encoding='utf-8') as f:
182
+ json.dump(items, f, ensure_ascii=False, indent=2)
183
+
184
+ with open('frontend/src/data/tcmIngredients.json', 'w', encoding='utf-8') as f:
185
+ json.dump(items, f, ensure_ascii=False, indent=2)
186
+
187
+ print('Saved successfully to backend and frontend!')
database/mongo.py CHANGED
@@ -170,26 +170,37 @@ class FallbackDatabase:
170
  def __init__(self):
171
  tcm_data = []
172
  try:
173
- from database.seed_100_tcm import POPULAR_TCM
174
- for idx, item in enumerate(POPULAR_TCM, 1):
175
- mandarin, pinyin, indo, eng, is_toxic, tox_class, organ, desc, source = item
176
- tcm_data.append({
177
- "_id": str(idx),
178
- "mandarin_name": mandarin,
179
- "pinyin_name": pinyin,
180
- "indonesian_name": indo,
181
- "english_name": eng,
182
- "latin_name": indo if " " in indo else None,
183
- "is_toxic": is_toxic,
184
- "toxicity_level": tox_class,
185
- "toxicity_class": "toxic" if is_toxic else tox_class,
186
- "target_organ": organ,
187
- "description": desc,
188
- "source_reference": source,
189
- "validated_by": "fitmate_verified"
190
- })
 
 
 
 
 
 
 
 
 
 
 
191
  except Exception as e:
192
- logger.warning(f"Could not load POPULAR_TCM into fallback: {e}")
193
 
194
  self._collections = {
195
  "tcm_ingredients": FallbackCollection("tcm_ingredients", tcm_data),
 
170
  def __init__(self):
171
  tcm_data = []
172
  try:
173
+ import json
174
+ from pathlib import Path
175
+ json_path = Path(__file__).parent / "data" / "tcm_500_ingredients.json"
176
+ if json_path.exists():
177
+ with open(json_path, "r", encoding="utf-8") as f:
178
+ raw_items = json.load(f)
179
+ for idx, it in enumerate(raw_items, 1):
180
+ doc = dict(it)
181
+ doc["_id"] = str(idx)
182
+ tcm_data.append(doc)
183
+ else:
184
+ from database.seed_100_tcm import POPULAR_TCM
185
+ for idx, item in enumerate(POPULAR_TCM, 1):
186
+ mandarin, pinyin, indo, eng, is_toxic, tox_class, organ, desc, source = item
187
+ tcm_data.append({
188
+ "_id": str(idx),
189
+ "mandarin_name": mandarin,
190
+ "pinyin_name": pinyin,
191
+ "indonesian_name": indo,
192
+ "english_name": eng,
193
+ "latin_name": indo if " " in indo else None,
194
+ "is_toxic": is_toxic,
195
+ "toxicity_level": tox_class,
196
+ "toxicity_class": "toxic" if is_toxic else tox_class,
197
+ "target_organ": organ,
198
+ "description": desc,
199
+ "source_reference": source,
200
+ "validated_by": "fitmate_verified"
201
+ })
202
  except Exception as e:
203
+ logger.warning(f"Could not load TCM ingredients into fallback: {e}")
204
 
205
  self._collections = {
206
  "tcm_ingredients": FallbackCollection("tcm_ingredients", tcm_data),
routers/bridge.py CHANGED
@@ -97,7 +97,11 @@ async def upload_for_session(
97
 
98
  session["status"] = "completed"
99
  session["results"] = payload
100
- return {"status": "success", "message": "Hasil analisis berhasil dikirim ke desktop"}
 
 
 
 
101
  except Exception as e:
102
  session["status"] = "error"
103
  session["error"] = str(e)
 
97
 
98
  session["status"] = "completed"
99
  session["results"] = payload
100
+ return {
101
+ "status": "success",
102
+ "message": "Hasil analisis berhasil diproses",
103
+ **payload
104
+ }
105
  except Exception as e:
106
  session["status"] = "error"
107
  session["error"] = str(e)
services/safety.py CHANGED
@@ -42,28 +42,53 @@ async def match_ingredients(detected_texts: list[str], db) -> dict:
42
  matched_texts.add(raw_text)
43
  continue
44
 
45
- # 2. Substring matching (both directions)
46
  matched_item = None
47
  matched_score = 0
48
  for name_key, item in lookup_keys.items():
49
- if len(name_key) >= 2 and (name_key in lower_text or (len(lower_text) >= 3 and lower_text in name_key)):
50
- matched_item = item
51
- matched_score = 95
52
- break
 
 
 
53
 
54
  if matched_item:
55
  _categorize_item(matched_item, raw_text, results, matched_score)
56
  matched_texts.add(raw_text)
57
  continue
58
 
59
- # 3. Fuzzy ratio matching against all known names
60
- best_match = process.extractOne(lower_text, list(lookup_keys.keys()), scorer=fuzz.partial_ratio)
61
- if best_match and best_match[1] >= 82:
62
- matched_item = lookup_keys[best_match[0]]
63
- _categorize_item(matched_item, raw_text, results, best_match[1])
64
- matched_texts.add(raw_text)
65
- else:
66
- results["unknown"].append({"detected_text": raw_text, "match_score": 0})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  return results
69
 
 
42
  matched_texts.add(raw_text)
43
  continue
44
 
45
+ # 2. Strict word boundary check (Requires full word match, not loose partial letters)
46
  matched_item = None
47
  matched_score = 0
48
  for name_key, item in lookup_keys.items():
49
+ if len(name_key) >= 3 or re.search(r'[\u4e00-\u9fff]', name_key):
50
+ p1 = r'(?:\b|^)' + re.escape(name_key) + r'(?:\b|$)'
51
+ p2 = r'(?:\b|^)' + re.escape(lower_text) + r'(?:\b|$)'
52
+ if re.search(p1, lower_text) or (len(lower_text) >= 4 and re.search(p2, name_key)):
53
+ matched_item = item
54
+ matched_score = 95
55
+ break
56
 
57
  if matched_item:
58
  _categorize_item(matched_item, raw_text, results, matched_score)
59
  matched_texts.add(raw_text)
60
  continue
61
 
62
+ # 3. Fuzzy token ratio matching (only for shorter text snippets)
63
+ if len(lower_text) <= 35:
64
+ best_match = process.extractOne(lower_text, list(lookup_keys.keys()), scorer=fuzz.token_sort_ratio)
65
+ if best_match and best_match[1] >= 88:
66
+ matched_item = lookup_keys[best_match[0]]
67
+ _categorize_item(matched_item, raw_text, results, best_match[1])
68
+ matched_texts.add(raw_text)
69
+ continue
70
+
71
+ results["unknown"].append({
72
+ "detected_text": raw_text,
73
+ "match_score": 0,
74
+ "is_toxic": False,
75
+ "is_herbal": False,
76
+ "status_label": "Bukan Komposisi Herbal / Teks Kemasan Umum"
77
+ })
78
+
79
+ total_toxic = len(results["toxic"]) + len(results["contraindicated"])
80
+ total_safe = len(results["safe"])
81
+ total_unknown = len(results["unknown"])
82
+ is_herbal = (total_toxic + total_safe) > 0
83
+
84
+ results["meta"] = {
85
+ "total_detected": len(detected_texts),
86
+ "total_toxic": total_toxic,
87
+ "total_safe": total_safe,
88
+ "total_unknown": total_unknown,
89
+ "is_herbal_product": is_herbal,
90
+ "classification": "toxic" if total_toxic > 0 else ("safe" if total_safe > 0 else "non_herbal")
91
+ }
92
 
93
  return results
94
 
tests/test_integration.py CHANGED
@@ -8,9 +8,9 @@ async def run_all_tests():
8
  print("--- 1. Testing Database & Fallback ---")
9
  db = get_db()
10
  col = db["tcm_ingredients"]
11
- doc_count = await col.count_documents({})
12
- print(f"Database ingredient count: {doc_count}")
13
- assert doc_count >= 100, f"Expected >= 100 ingredients, got {doc_count}"
14
 
15
  print("--- 2. Testing Multilingual Safety Matching ---")
16
  test_queries = [
@@ -33,6 +33,15 @@ async def run_all_tests():
33
  item = matched["safe"][0]
34
  print(f"Query: {raw_name:<15} -> Matched SAFE: {item.get('english_name') or item.get('indonesian_name')}")
35
 
 
 
 
 
 
 
 
 
 
36
  print("--- 3. Testing API Endpoints via ASGI ---")
37
  transport = httpx.ASGITransport(app=app)
38
  async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
 
8
  print("--- 1. Testing Database & Fallback ---")
9
  db = get_db()
10
  col = db["tcm_ingredients"]
11
+ count = await col.count_documents({})
12
+ assert count >= 100
13
+ print(f"Database ingredient count: {count}")
14
 
15
  print("--- 2. Testing Multilingual Safety Matching ---")
16
  test_queries = [
 
33
  item = matched["safe"][0]
34
  print(f"Query: {raw_name:<15} -> Matched SAFE: {item.get('english_name') or item.get('indonesian_name')}")
35
 
36
+ # Test non-herbal food snack text
37
+ snack_res = await match_ingredients(["Naraya Rice Crackers", "Krekers Beras Rasa Asin"], db)
38
+ assert snack_res["meta"]["is_herbal_product"] == False
39
+ assert snack_res["meta"]["classification"] == "non_herbal"
40
+ assert len(snack_res["toxic"]) == 0
41
+ assert len(snack_res["safe"]) == 0
42
+ assert len(snack_res["unknown"]) == 2
43
+ print("Non-herbal food snack test: PASS (Correctly flagged non_herbal)")
44
+
45
  print("--- 3. Testing API Endpoints via ASGI ---")
46
  transport = httpx.ASGITransport(app=app)
47
  async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: