Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def _row_to_payload(row: dict) -> dict:
"confidence": round((row.get("confidence_score") or 0) * 100, 1),
"classification": "FRESH" if is_fresh else "SPOILED",
"is_fresh": is_fresh,
"uncertain_flag": False,
"uncertain_flag": (row.get("confidence_score") or 1.0) < 0.70,
"species": {
"common_name": "Rohu Carp",
"scientific_name": "Labeo rohita",
Expand Down Expand Up @@ -528,12 +528,59 @@ async def process_scan(
async def scan_auto(
request: Request,
image: UploadFile = File(...),
freshness_label: Optional[str] = Form(None),
fused_score: Optional[float] = Form(None),
source: Optional[str] = Form(None),
confidence_score: Optional[float] = Form(None),
species_detected: Optional[str] = Form(None),
current_user=Depends(get_current_user),
):
image_bytes = await image.read()
scan_id = str(uuid.uuid4())
display_id = _generate_display_id()

# If edge_onnx path is used, save directly and bypass server inference
if source == "edge_onnx" and fused_score is not None:
freshness = int(fused_score * 100)
conf = confidence_score or 0.85
edge_fusion = {
"final_score_percent": freshness,
"final_grade": _to_db_grade(freshness_label or "C"),
"confidence_score": conf,
"uncertain_prediction_flag": conf < 0.70,
"regional_breakdown": {
"gill_freshness_score": fused_score,
"eye_freshness_score": fused_score,
"body_freshness_score": fused_score,
},
}
photo_url = await _upload_image(image_bytes, str(current_user.id), scan_id)
payload = _build_scan_payload(edge_fusion, scan_id, display_id, photo_url)
if species_detected:
payload["species"]["common_name"] = species_detected

try:
_db().table("scans").insert(
{
"id": scan_id,
"user_id": str(current_user.id),
"final_grade": _to_db_grade(payload["grade"]),
"confidence_score": conf,
"image_type": "BODY",
"freshness_index": payload["freshness_index"],
"scan_display_id": display_id,
"species_detected": species_detected or "Rohu Carp",
"biomarker_json": payload["biomarkers"],
"storage_hours": payload["recommendations"]["consume_within_hours"],
"alert_flags": payload["recommendations"]["alert_flags"],
"photo_urls": [photo_url] if photo_url else [],
}
).execute()
except Exception as exc:
print(f"DB write failed (edge_onnx): {exc}")

return {"success": True, "scan": payload}

# ── Demo mode: models not loaded (PyTorch not installed) ─────────────────
if not _models_loaded:
gill = random.randint(68, 96)
Expand Down
58 changes: 58 additions & 0 deletions merge_i18n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Merge a FreshScanAi PR's rejected i18n "analytics" hunk (added by the PR's
shared base diff) into upstream's existing analytics i18n object.

Usage: merge_i18n.py <patch_file> [en bn hi]
Reads the analytics key block the PR tries to ADD for each locale from the
patch, and appends those keys (minus the wrapping "analytics": { } since
upstream already has that object) into the existing analytics object, right
after the "allTime" key.
"""
import re, json, sys

def extract_analytics_keys(patch, lang):
sec = re.search(r'diff --git a/src/i18n/locales/%s\.json.*?(?=\ndiff --git|\Z)' % lang, patch, re.S)
if not sec:
return None
body = sec.group()
lines = body.split('\n')
cap = False
added = []
for l in lines:
if l.startswith('+') and '"analytics"' in l:
cap = True
continue
if cap:
if l.startswith('+'):
content = l[1:].rstrip('\n')
if content.strip() == '}':
break
added.append(content.strip())
elif l.startswith('-') or (not l.startswith('+') and not l.startswith(' ') and not l.startswith('@@')):
break
return added

def merge_lang(lang, patch):
f = f'src/i18n/locales/{lang}.json'
s = open(f).read()
keys = extract_analytics_keys(patch, lang)
if not keys:
print(f'{lang}: no analytics keys in patch'); return
if keys[-1].endswith(','):
keys[-1] = keys[-1][:-1]
pattern = re.compile(r'("allTime"\s*:\s*"[^"]*")(\n \}\n\})')
if not pattern.search(s):
print(f'{lang}: allTime anchor not found'); return
insertion = ',\n' + '\n'.join(' ' + k for k in keys)
s2 = pattern.sub(lambda mm: mm.group(1) + insertion + '\n' + mm.group(2), s)
open(f, 'w').write(s2)
try:
json.load(open(f)); print(f'{lang}: merged OK ({len(keys)} keys)')
except Exception as e:
print(f'{lang}: INVALID {e}')

patch_file = sys.argv[1]
langs = sys.argv[2:] if len(sys.argv) > 2 else ['en', 'bn', 'hi']
patch = open(patch_file).read()
for lang in langs:
merge_lang(lang, patch)
Loading
Loading