Spaces:
Sleeping
Sleeping
Vineela Gampa
commited on
fixes for front end
Browse files- .gitignore +4 -1
- Dockerfile +10 -1
- backend.py +9 -11
- bert.py +6 -6
- data/app.db +0 -0
- past_reports.py +202 -0
- web/analyzer.html +13 -30
- web/past_data.html +26 -6
- web/script.js +99 -0
.gitignore
CHANGED
|
@@ -1,4 +1,7 @@
|
|
| 1 |
.venv
|
| 2 |
/api_key.py
|
| 3 |
api_key.py
|
| 4 |
-
.DS_Store
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
.venv
|
| 2 |
/api_key.py
|
| 3 |
api_key.py
|
| 4 |
+
.DS_Store
|
| 5 |
+
firebase_key.json
|
| 6 |
+
.env
|
| 7 |
+
.vscode
|
Dockerfile
CHANGED
|
@@ -57,12 +57,21 @@ COPY . .
|
|
| 57 |
# Writable caches
|
| 58 |
RUN mkdir -p /cache/hf /tmp && chmod -R 777 /cache /tmp
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
#ENV PORT=8000
|
| 61 |
EXPOSE 7860
|
| 62 |
|
| 63 |
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
|
| 64 |
CMD curl -fsS "http://127.0.0.1:${PORT:-7860}/api/health/" || exit 1
|
| 65 |
|
| 66 |
-
#
|
| 67 |
CMD ["sh","-c","uvicorn backend:app --host 0.0.0.0 --port ${PORT:-7860} --proxy-headers --forwarded-allow-ips='*'"]
|
| 68 |
|
|
|
|
| 57 |
# Writable caches
|
| 58 |
RUN mkdir -p /cache/hf /tmp && chmod -R 777 /cache /tmp
|
| 59 |
|
| 60 |
+
|
| 61 |
+
# If you have a starter DB in the repo, uncomment the next line to seed it:
|
| 62 |
+
RUN mkdir -p /data && chmod -R 777 /data
|
| 63 |
+
#COPY app.db /data/app.db
|
| 64 |
+
ENV DB_DIR=/data
|
| 65 |
+
ENV DB_PATH=/data/app.db
|
| 66 |
+
# (optional) expose as a volume so you can mount from host if you want persistence
|
| 67 |
+
VOLUME ["/data"]
|
| 68 |
+
|
| 69 |
#ENV PORT=8000
|
| 70 |
EXPOSE 7860
|
| 71 |
|
| 72 |
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
|
| 73 |
CMD curl -fsS "http://127.0.0.1:${PORT:-7860}/api/health/" || exit 1
|
| 74 |
|
| 75 |
+
# bind to $PORT provided by HF; include proxy headers
|
| 76 |
CMD ["sh","-c","uvicorn backend:app --host 0.0.0.0 --port ${PORT:-7860} --proxy-headers --forwarded-allow-ips='*'"]
|
| 77 |
|
backend.py
CHANGED
|
@@ -24,6 +24,7 @@ from bert import analyze_with_clinicalBert, classify_disease_and_severity, extra
|
|
| 24 |
from disease_links import diseases as disease_links
|
| 25 |
from disease_steps import disease_next_steps
|
| 26 |
from disease_support import disease_doctor_specialty, disease_home_care
|
|
|
|
| 27 |
|
| 28 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 29 |
df = pd.read_csv("measurement.csv")
|
|
@@ -55,6 +56,7 @@ app.include_router(api)
|
|
| 55 |
|
| 56 |
|
| 57 |
app.mount("/app", StaticFiles(directory="web", html=True), name="web")
|
|
|
|
| 58 |
|
| 59 |
app.add_middleware(
|
| 60 |
CORSMiddleware,
|
|
@@ -204,6 +206,7 @@ async def analyze(
|
|
| 204 |
filename = file.filename.lower()
|
| 205 |
detected_diseases = set()
|
| 206 |
ocr_full = ""
|
|
|
|
| 207 |
if filename.endswith(".pdf"):
|
| 208 |
pdf_bytes = await file.read()
|
| 209 |
image_bytes_list = extract_images_from_pdf_bytes(pdf_bytes)
|
|
@@ -224,22 +227,19 @@ async def analyze(
|
|
| 224 |
return {"message": "Gemini model not available; please use BERT model."}
|
| 225 |
|
| 226 |
found_diseases = extract_non_negated_keywords(ocr_full)
|
| 227 |
-
print(f"CALLING FOUND DISEASES: {found_diseases}")
|
| 228 |
past = detect_past_diseases(ocr_full)
|
| 229 |
-
print(f"CALLING PAST DISEASES: {past}")
|
| 230 |
|
| 231 |
for disease in found_diseases:
|
| 232 |
if disease in past:
|
| 233 |
severity = classify_disease_and_severity(disease)
|
| 234 |
detected_diseases.add(((f"{disease}(detected as historical condition, but still under risk.)"), severity))
|
| 235 |
-
print(f"DETECTED DISEASES(PAST): {detected_diseases}")
|
| 236 |
else:
|
| 237 |
severity = classify_disease_and_severity(disease)
|
| 238 |
detected_diseases.add((disease, severity))
|
| 239 |
-
|
| 240 |
|
| 241 |
-
|
| 242 |
-
print("Detected diseases:",
|
| 243 |
ranges = analyze_measurements(ocr_full, df)
|
| 244 |
|
| 245 |
|
|
@@ -273,7 +273,6 @@ async def analyze(
|
|
| 273 |
next_steps_range = disease_next_steps.get(condition.lower(), ['Consult a doctor'])
|
| 274 |
specialist_range = disease_doctor_specialty.get(condition.lower(), "General Practitioner")
|
| 275 |
home_care_range = disease_home_care.get(condition.lower(), [])
|
| 276 |
-
print(f"HELLO!: {measurement}")
|
| 277 |
|
| 278 |
condition_version = condition.upper()
|
| 279 |
severity_version = severity.upper()
|
|
@@ -287,12 +286,11 @@ async def analyze(
|
|
| 287 |
"info_link": link_range
|
| 288 |
})
|
| 289 |
|
| 290 |
-
|
| 291 |
ranges = analyze_measurements(ocr_full, df)
|
| 292 |
print(analyze_measurements(ocr_full, df))
|
| 293 |
# print ("Ranges is being printed", ranges)
|
| 294 |
historical_med_data = detect_past_diseases(ocr_full)
|
| 295 |
-
print("***End of Code***")
|
| 296 |
|
| 297 |
return {
|
| 298 |
"ocr_text": ocr_full.strip(),
|
|
@@ -323,10 +321,10 @@ def analyze_text(text):
|
|
| 323 |
def health():
|
| 324 |
return {"response": "ok"}
|
| 325 |
|
| 326 |
-
@app.route("/save_report/")
|
| 327 |
async def save_report(request: Request):
|
| 328 |
data = await request.json()
|
| 329 |
-
print("Report recieved from frontend:", data)
|
| 330 |
|
| 331 |
@app.on_event("startup")
|
| 332 |
def _log_routes():
|
|
|
|
| 24 |
from disease_links import diseases as disease_links
|
| 25 |
from disease_steps import disease_next_steps
|
| 26 |
from disease_support import disease_doctor_specialty, disease_home_care
|
| 27 |
+
from past_reports import router as reports_router
|
| 28 |
|
| 29 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 30 |
df = pd.read_csv("measurement.csv")
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
app.mount("/app", StaticFiles(directory="web", html=True), name="web")
|
| 59 |
+
app.include_router(reports_router)
|
| 60 |
|
| 61 |
app.add_middleware(
|
| 62 |
CORSMiddleware,
|
|
|
|
| 206 |
filename = file.filename.lower()
|
| 207 |
detected_diseases = set()
|
| 208 |
ocr_full = ""
|
| 209 |
+
print("Received request for file:", filename)
|
| 210 |
if filename.endswith(".pdf"):
|
| 211 |
pdf_bytes = await file.read()
|
| 212 |
image_bytes_list = extract_images_from_pdf_bytes(pdf_bytes)
|
|
|
|
| 227 |
return {"message": "Gemini model not available; please use BERT model."}
|
| 228 |
|
| 229 |
found_diseases = extract_non_negated_keywords(ocr_full)
|
|
|
|
| 230 |
past = detect_past_diseases(ocr_full)
|
|
|
|
| 231 |
|
| 232 |
for disease in found_diseases:
|
| 233 |
if disease in past:
|
| 234 |
severity = classify_disease_and_severity(disease)
|
| 235 |
detected_diseases.add(((f"{disease}(detected as historical condition, but still under risk.)"), severity))
|
|
|
|
| 236 |
else:
|
| 237 |
severity = classify_disease_and_severity(disease)
|
| 238 |
detected_diseases.add((disease, severity))
|
| 239 |
+
|
| 240 |
|
| 241 |
+
|
| 242 |
+
print("Detected diseases:", detected_diseases)
|
| 243 |
ranges = analyze_measurements(ocr_full, df)
|
| 244 |
|
| 245 |
|
|
|
|
| 273 |
next_steps_range = disease_next_steps.get(condition.lower(), ['Consult a doctor'])
|
| 274 |
specialist_range = disease_doctor_specialty.get(condition.lower(), "General Practitioner")
|
| 275 |
home_care_range = disease_home_care.get(condition.lower(), [])
|
|
|
|
| 276 |
|
| 277 |
condition_version = condition.upper()
|
| 278 |
severity_version = severity.upper()
|
|
|
|
| 286 |
"info_link": link_range
|
| 287 |
})
|
| 288 |
|
| 289 |
+
|
| 290 |
ranges = analyze_measurements(ocr_full, df)
|
| 291 |
print(analyze_measurements(ocr_full, df))
|
| 292 |
# print ("Ranges is being printed", ranges)
|
| 293 |
historical_med_data = detect_past_diseases(ocr_full)
|
|
|
|
| 294 |
|
| 295 |
return {
|
| 296 |
"ocr_text": ocr_full.strip(),
|
|
|
|
| 321 |
def health():
|
| 322 |
return {"response": "ok"}
|
| 323 |
|
| 324 |
+
'''@app.route("/save_report/")
|
| 325 |
async def save_report(request: Request):
|
| 326 |
data = await request.json()
|
| 327 |
+
print("Report recieved from frontend:", data)'''
|
| 328 |
|
| 329 |
@app.on_event("startup")
|
| 330 |
def _log_routes():
|
bert.py
CHANGED
|
@@ -183,14 +183,14 @@ def analyze_measurements(text, df):
|
|
| 183 |
"Range": f"{row['low']} to {row['high']} {row['unit']}"
|
| 184 |
})
|
| 185 |
|
| 186 |
-
print (results)
|
| 187 |
|
| 188 |
for res in results:
|
| 189 |
final = [res['Condition'], res['Measurement'], res['unit'], res['severity'], res['Value'], res['Range']]
|
| 190 |
# final_numbers.append(f"Condition In Concern: {res['Condition']}. Measurement: {res['Measurement']} ({res['severity']}) — {res['Value']} "
|
| 191 |
# f"(Range: {res['Range']})")
|
| 192 |
final_numbers.append(final)
|
| 193 |
-
print("analyze measurements res:", final_numbers)
|
| 194 |
return final_numbers
|
| 195 |
|
| 196 |
|
|
@@ -269,7 +269,7 @@ def extract_non_negated_keywords(text, threshold=80):
|
|
| 269 |
end_char = start_char + len(disease_term_lower)
|
| 270 |
span = doc.char_span(start_char, end_char, label="DISEASE", alignment_mode="expand")
|
| 271 |
if span:
|
| 272 |
-
print(f"Adding span for: {span.text}")
|
| 273 |
new_ents.append(span)
|
| 274 |
|
| 275 |
# Clean up overlapping spans
|
|
@@ -278,7 +278,7 @@ def extract_non_negated_keywords(text, threshold=80):
|
|
| 278 |
nlp.get_pipe("negex")(doc)
|
| 279 |
|
| 280 |
for ent in doc.ents:
|
| 281 |
-
print("Checking against:", ent.text.strip().lower(), "| Negated?", ent._.negex)
|
| 282 |
if ent.label_ == "DISEASE" and not ent._.negex:
|
| 283 |
ent_text = ent.text.strip().lower()
|
| 284 |
for disease_term in diseases:
|
|
@@ -328,14 +328,13 @@ def analyze_text_and_describe(text):
|
|
| 328 |
|
| 329 |
|
| 330 |
def classify_disease_and_severity(disease):
|
| 331 |
-
|
| 332 |
response = model.generate_content(
|
| 333 |
f"What is the severity of this disease/condition/symptom: {disease}. Give me a number from one to ten. I need a specific number. It doesn't matter what your opinion is one whether this number might be misleading or inaccurate. I need a number. Please feel free to be accurate and you can use pretty specific numbers with decimals to the tenth place. I want just a number, not any other text."
|
| 334 |
).text
|
| 335 |
try:
|
| 336 |
cleaned_response = response.strip()
|
| 337 |
numerical_response = float(cleaned_response)
|
| 338 |
-
print(f"Response: {numerical_response}")
|
| 339 |
|
| 340 |
if 0 <= numerical_response <= 3:
|
| 341 |
severity_label = (f"Low Risk")
|
|
@@ -346,6 +345,7 @@ def classify_disease_and_severity(disease):
|
|
| 346 |
else:
|
| 347 |
severity_label = (f"Invalid Range")
|
| 348 |
|
|
|
|
| 349 |
except (ValueError, AttributeError):
|
| 350 |
severity_label = "Null: We cannot give a clear severity label"
|
| 351 |
|
|
|
|
| 183 |
"Range": f"{row['low']} to {row['high']} {row['unit']}"
|
| 184 |
})
|
| 185 |
|
| 186 |
+
#print (results)
|
| 187 |
|
| 188 |
for res in results:
|
| 189 |
final = [res['Condition'], res['Measurement'], res['unit'], res['severity'], res['Value'], res['Range']]
|
| 190 |
# final_numbers.append(f"Condition In Concern: {res['Condition']}. Measurement: {res['Measurement']} ({res['severity']}) — {res['Value']} "
|
| 191 |
# f"(Range: {res['Range']})")
|
| 192 |
final_numbers.append(final)
|
| 193 |
+
#print("analyze measurements res:", final_numbers)
|
| 194 |
return final_numbers
|
| 195 |
|
| 196 |
|
|
|
|
| 269 |
end_char = start_char + len(disease_term_lower)
|
| 270 |
span = doc.char_span(start_char, end_char, label="DISEASE", alignment_mode="expand")
|
| 271 |
if span:
|
| 272 |
+
#print(f"Adding span for: {span.text}")
|
| 273 |
new_ents.append(span)
|
| 274 |
|
| 275 |
# Clean up overlapping spans
|
|
|
|
| 278 |
nlp.get_pipe("negex")(doc)
|
| 279 |
|
| 280 |
for ent in doc.ents:
|
| 281 |
+
#print("Checking against:", ent.text.strip().lower(), "| Negated?", ent._.negex)
|
| 282 |
if ent.label_ == "DISEASE" and not ent._.negex:
|
| 283 |
ent_text = ent.text.strip().lower()
|
| 284 |
for disease_term in diseases:
|
|
|
|
| 328 |
|
| 329 |
|
| 330 |
def classify_disease_and_severity(disease):
|
| 331 |
+
|
| 332 |
response = model.generate_content(
|
| 333 |
f"What is the severity of this disease/condition/symptom: {disease}. Give me a number from one to ten. I need a specific number. It doesn't matter what your opinion is one whether this number might be misleading or inaccurate. I need a number. Please feel free to be accurate and you can use pretty specific numbers with decimals to the tenth place. I want just a number, not any other text."
|
| 334 |
).text
|
| 335 |
try:
|
| 336 |
cleaned_response = response.strip()
|
| 337 |
numerical_response = float(cleaned_response)
|
|
|
|
| 338 |
|
| 339 |
if 0 <= numerical_response <= 3:
|
| 340 |
severity_label = (f"Low Risk")
|
|
|
|
| 345 |
else:
|
| 346 |
severity_label = (f"Invalid Range")
|
| 347 |
|
| 348 |
+
print(f"Disease: {disease} Severity Label: {severity_label}")
|
| 349 |
except (ValueError, AttributeError):
|
| 350 |
severity_label = "Null: We cannot give a clear severity label"
|
| 351 |
|
data/app.db
ADDED
|
Binary file (24.6 kB). View file
|
|
|
past_reports.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import json
|
| 4 |
+
import sqlite3
|
| 5 |
+
import threading
|
| 6 |
+
from typing import Any, List, Optional
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
from pydantic import BaseModel, Field
|
| 10 |
+
from fastapi import APIRouter, Query, HTTPException
|
| 11 |
+
|
| 12 |
+
# ===== Config =====
|
| 13 |
+
def _pick_writable_dir():
|
| 14 |
+
candidates = [
|
| 15 |
+
os.getenv("DB_DIR"), # <- recommended: set this in env
|
| 16 |
+
"/data", # HF Spaces/container convention
|
| 17 |
+
"/app/data", # container-friendly
|
| 18 |
+
os.path.join(os.getcwd(), "data"),
|
| 19 |
+
tempfile.gettempdir(),
|
| 20 |
+
]
|
| 21 |
+
for d in candidates:
|
| 22 |
+
if not d:
|
| 23 |
+
continue
|
| 24 |
+
try:
|
| 25 |
+
os.makedirs(d, exist_ok=True)
|
| 26 |
+
test = os.path.join(d, ".rwcheck")
|
| 27 |
+
with open(test, "w") as f:
|
| 28 |
+
f.write("ok")
|
| 29 |
+
os.remove(test)
|
| 30 |
+
return d
|
| 31 |
+
except Exception:
|
| 32 |
+
continue
|
| 33 |
+
# absolute fallback: current working directory
|
| 34 |
+
return os.getcwd()
|
| 35 |
+
|
| 36 |
+
DB_DIR = _pick_writable_dir()
|
| 37 |
+
DB_PATH = os.path.join(DB_DIR, os.getenv("DB_FILE", "app.db"))
|
| 38 |
+
|
| 39 |
+
# ===== SQLite bootstrap =====
|
| 40 |
+
_conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 41 |
+
_conn.execute(
|
| 42 |
+
"""
|
| 43 |
+
CREATE TABLE IF NOT EXISTS reports (
|
| 44 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 45 |
+
user_id TEXT NOT NULL,
|
| 46 |
+
report_date TEXT,
|
| 47 |
+
ocr_text TEXT,
|
| 48 |
+
anomalies TEXT,
|
| 49 |
+
measurements TEXT,
|
| 50 |
+
created_at TEXT DEFAULT (datetime('now'))
|
| 51 |
+
)
|
| 52 |
+
"""
|
| 53 |
+
)
|
| 54 |
+
_conn.execute(
|
| 55 |
+
"CREATE INDEX IF NOT EXISTS idx_reports_user_created ON reports(user_id, created_at DESC)"
|
| 56 |
+
)
|
| 57 |
+
_conn.commit()
|
| 58 |
+
_db_lock = threading.Lock()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _safe_parse_json(text):
|
| 62 |
+
if text is None:
|
| 63 |
+
return None
|
| 64 |
+
s = text.strip()
|
| 65 |
+
if not s:
|
| 66 |
+
return None
|
| 67 |
+
# Try real JSON first
|
| 68 |
+
try:
|
| 69 |
+
return json.loads(s)
|
| 70 |
+
except json.JSONDecodeError:
|
| 71 |
+
pass
|
| 72 |
+
# Common legacy cases: Python repr (single quotes, True/False/None)
|
| 73 |
+
try:
|
| 74 |
+
return ast.literal_eval(s)
|
| 75 |
+
except Exception:
|
| 76 |
+
return None # or return s if you prefer to surface the raw text
|
| 77 |
+
|
| 78 |
+
def _row_to_dict(row: sqlite3.Row) -> dict:
|
| 79 |
+
return {
|
| 80 |
+
"id": row[0],
|
| 81 |
+
"user_id": row[1],
|
| 82 |
+
"report_date": row[2],
|
| 83 |
+
"ocr_text": row[3],
|
| 84 |
+
"anomalies": _safe_parse_json(row[4]),
|
| 85 |
+
"measurements": _safe_parse_json(row[5]),
|
| 86 |
+
"created_at": row[6],
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def db_insert_report(payload: dict) -> int:
|
| 90 |
+
with _db_lock:
|
| 91 |
+
cur = _conn.cursor()
|
| 92 |
+
cur.execute(
|
| 93 |
+
"""
|
| 94 |
+
INSERT INTO reports (
|
| 95 |
+
user_id, report_date, ocr_text,
|
| 96 |
+
anomalies, measurements
|
| 97 |
+
)
|
| 98 |
+
VALUES (?, ?, ?, ?, ?)
|
| 99 |
+
""",
|
| 100 |
+
(
|
| 101 |
+
payload.get("user_id"),
|
| 102 |
+
payload.get("report_date"),
|
| 103 |
+
payload.get("ocr_text"),
|
| 104 |
+
payload.get("anomalies"),
|
| 105 |
+
payload.get("measurements"),
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
_conn.commit()
|
| 109 |
+
return cur.lastrowid
|
| 110 |
+
|
| 111 |
+
def db_fetch_reports(user_id: str, limit: int = 50, offset: int = 0) -> List[dict]:
|
| 112 |
+
_conn.row_factory = sqlite3.Row
|
| 113 |
+
cur = _conn.cursor()
|
| 114 |
+
cur.execute(
|
| 115 |
+
"""
|
| 116 |
+
SELECT id, user_id, report_date, ocr_text,
|
| 117 |
+
anomalies, measurements, created_at
|
| 118 |
+
FROM reports
|
| 119 |
+
WHERE user_id = ?
|
| 120 |
+
ORDER BY datetime(created_at) DESC, id DESC
|
| 121 |
+
LIMIT ? OFFSET ?
|
| 122 |
+
""",
|
| 123 |
+
(user_id, limit, offset),
|
| 124 |
+
)
|
| 125 |
+
return [_row_to_dict(r) for r in cur.fetchall()]
|
| 126 |
+
|
| 127 |
+
def db_get_report(report_id: int) -> Optional[dict]:
|
| 128 |
+
_conn.row_factory = sqlite3.Row
|
| 129 |
+
cur = _conn.cursor()
|
| 130 |
+
cur.execute(
|
| 131 |
+
"""
|
| 132 |
+
SELECT id, user_id, report_date, ocr_text,
|
| 133 |
+
anomalies, measurements, created_at
|
| 134 |
+
FROM reports
|
| 135 |
+
WHERE id = ?
|
| 136 |
+
""",
|
| 137 |
+
(report_id,),
|
| 138 |
+
)
|
| 139 |
+
row = cur.fetchone()
|
| 140 |
+
return _row_to_dict(row) if row else None
|
| 141 |
+
|
| 142 |
+
def db_delete_report(report_id: int) -> bool:
|
| 143 |
+
with _db_lock:
|
| 144 |
+
cur = _conn.cursor()
|
| 145 |
+
cur.execute("DELETE FROM reports WHERE id = ?", (report_id,))
|
| 146 |
+
_conn.commit()
|
| 147 |
+
return cur.rowcount > 0
|
| 148 |
+
|
| 149 |
+
# ===== Pydantic Schemas =====
|
| 150 |
+
class ReportIn(BaseModel):
|
| 151 |
+
user_id: str = Field(..., example="[email protected]")
|
| 152 |
+
report_date: Optional[str] = Field(None, example="2025-09-07")
|
| 153 |
+
ocr_text: Optional[str] = None
|
| 154 |
+
anomalies: Optional[Any] = None
|
| 155 |
+
measurements: Optional[Any] = None
|
| 156 |
+
|
| 157 |
+
class ReportOut(BaseModel):
|
| 158 |
+
id: int
|
| 159 |
+
user_id: str
|
| 160 |
+
report_date: Optional[str]
|
| 161 |
+
ocr_text: Optional[str]
|
| 162 |
+
anomalies: Optional[Any]
|
| 163 |
+
measurements: Optional[Any]
|
| 164 |
+
created_at: str
|
| 165 |
+
|
| 166 |
+
# ===== Router =====
|
| 167 |
+
router = APIRouter(tags=["Reports"])
|
| 168 |
+
|
| 169 |
+
@router.post("/save_report/", response_model=dict)
|
| 170 |
+
def save_report(body: ReportIn):
|
| 171 |
+
if not body.user_id:
|
| 172 |
+
raise HTTPException(status_code=400, detail="user_id is required")
|
| 173 |
+
print(f"Saving report for user: {body}")
|
| 174 |
+
rid = db_insert_report(body.dict())
|
| 175 |
+
return {"ok": True, "id": rid}
|
| 176 |
+
|
| 177 |
+
@router.get("/reports/", response_model=List[ReportOut])
|
| 178 |
+
def list_reports(
|
| 179 |
+
user_id: str = Query(..., description="User email to filter by"),
|
| 180 |
+
limit: int = Query(50, ge=1, le=200),
|
| 181 |
+
offset: int = Query(0, ge=0),
|
| 182 |
+
):
|
| 183 |
+
return db_fetch_reports(user_id=user_id, limit=limit, offset=offset)
|
| 184 |
+
|
| 185 |
+
@router.get("/reports/{report_id}", response_model=ReportOut)
|
| 186 |
+
def get_report(report_id: int):
|
| 187 |
+
row = db_get_report(report_id)
|
| 188 |
+
if not row:
|
| 189 |
+
raise HTTPException(status_code=404, detail="Report not found")
|
| 190 |
+
return row
|
| 191 |
+
|
| 192 |
+
@router.delete("/reports/{report_id}", response_model=dict)
|
| 193 |
+
def delete_report(report_id: int):
|
| 194 |
+
if db_delete_report(report_id):
|
| 195 |
+
return {"ok": True, "deleted": report_id}
|
| 196 |
+
raise HTTPException(status_code=404, detail="Report not found")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
#req = ReportIn(user_id="[email protected]", report_date="2025-09-08", ocr_text="Medical Report - Cancer Patient Name: Carol Davis Age: 55 Gender: Female Clinical History: Recent biopsy confirms breast cancer (invasive ductal carcinoma). No lymph node involvement. PET scan negative for metastasis.", anomalies=[{"findings":"BREAST CANCER(DETECTED AS HISTORICAL CONDITION, BUT STILL UNDER RISK.)","severity":"Severe Risk","recommendations":["Consult a doctor."],"treatment_suggestions":"Consult a specialist: General Practitioner","home_care_guidance":[],"info_link":"https://www.webmd.com/"},{"findings":"CANCER(DETECTED AS HISTORICAL CONDITION, BUT STILL UNDER RISK.)","severity":"Severe Risk","recommendations":["Consult a doctor."],"treatment_suggestions":"Consult a specialist: General Practitioner","home_care_guidance":[],"info_link":"https://www.webmd.com/"},{"findings":"BRAIN CANCER(DETECTED AS HISTORICAL CONDITION, BUT STILL UNDER RISK.)","severity":"Severe Risk","recommendations":["Consult a doctor."],"treatment_suggestions":"Consult a specialist: General Practitioner","home_care_guidance":[],"info_link":"https://www.webmd.com/"}], measurements=[])
|
| 201 |
+
#save_report(req)
|
| 202 |
+
print(db_fetch_reports(user_id="[email protected]"))
|
web/analyzer.html
CHANGED
|
@@ -189,30 +189,8 @@
|
|
| 189 |
</li>
|
| 190 |
</ul>
|
| 191 |
</nav>
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
const isLocal = /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
|
| 195 |
-
|
| 196 |
-
// Optional overrides
|
| 197 |
-
const qs = new URLSearchParams(location.search);
|
| 198 |
-
const override = qs.get("api"); // e.g. ?api=http://localhost:9000
|
| 199 |
-
const saved = localStorage.getItem("API_BASE"); // remember last override
|
| 200 |
-
|
| 201 |
-
const base =
|
| 202 |
-
override ||
|
| 203 |
-
saved ||
|
| 204 |
-
// Local dev: call FastAPI on 8000; HF: use same origin (works from / or /proxy/8002)
|
| 205 |
-
(isLocal ? "http://localhost:8000" : location.origin);
|
| 206 |
-
|
| 207 |
-
if (override) localStorage.setItem("API_BASE", override);
|
| 208 |
-
|
| 209 |
-
window.API_BASE = base.replace(/\/$/, ""); // trim trailing slash
|
| 210 |
-
// helper to build URLs without double slashes
|
| 211 |
-
window.api = (path) =>
|
| 212 |
-
window.API_BASE + (path.startsWith("/") ? path : "/" + path);
|
| 213 |
-
})();
|
| 214 |
-
</script>
|
| 215 |
-
|
| 216 |
<script>
|
| 217 |
const hamburger = document.getElementById("hamburger");
|
| 218 |
const mobileMenu = document.getElementById("mobile-menu");
|
|
@@ -530,16 +508,21 @@
|
|
| 530 |
findingsOutput.innerHTML = findings
|
| 531 |
.map((finding, i) => renderRecCard(finding, i))
|
| 532 |
.join("");
|
| 533 |
-
}
|
| 534 |
-
findingsOutput.textContent = "No measurements found.";
|
| 535 |
-
}
|
| 536 |
-
|
| 537 |
if (currentUser) {
|
| 538 |
-
await saveAnalysis(currentUser.uid, {
|
| 539 |
reportDate: date,
|
| 540 |
ocr_text: extractedText,
|
| 541 |
-
|
| 542 |
measurements: findings,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
});
|
| 544 |
}
|
| 545 |
|
|
|
|
| 189 |
</li>
|
| 190 |
</ul>
|
| 191 |
</nav>
|
| 192 |
+
<!--Shared helpers (API base + query params) -->
|
| 193 |
+
<script src="script.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
<script>
|
| 195 |
const hamburger = document.getElementById("hamburger");
|
| 196 |
const mobileMenu = document.getElementById("mobile-menu");
|
|
|
|
| 508 |
findingsOutput.innerHTML = findings
|
| 509 |
.map((finding, i) => renderRecCard(finding, i))
|
| 510 |
.join("");
|
| 511 |
+
}
|
|
|
|
|
|
|
|
|
|
| 512 |
if (currentUser) {
|
| 513 |
+
/*await saveAnalysis(currentUser.uid, {
|
| 514 |
reportDate: date,
|
| 515 |
ocr_text: extractedText,
|
| 516 |
+
anomalies: recs,
|
| 517 |
measurements: findings,
|
| 518 |
+
});*/
|
| 519 |
+
|
| 520 |
+
await postReportToBackend({
|
| 521 |
+
user_id: currentUser.email,
|
| 522 |
+
report_date: date,
|
| 523 |
+
ocr_text: extractedText,
|
| 524 |
+
anomalies: JSON.stringify(recs),
|
| 525 |
+
measurements: JSON.stringify(findings),
|
| 526 |
});
|
| 527 |
}
|
| 528 |
|
web/past_data.html
CHANGED
|
@@ -4,6 +4,8 @@
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<title>Past Analyzes - CTRL + ALT + HEAL</title>
|
| 6 |
<script src="https://cdn.tailwindcss.com"></script>
|
|
|
|
|
|
|
| 7 |
</head>
|
| 8 |
<body class="bg-[#F7F8F9] min-h-screen">
|
| 9 |
<nav class="bg-white border border-gray-200 px-6 py-4 mb-8">
|
|
@@ -99,16 +101,34 @@
|
|
| 99 |
onAuthStateChanged(auth, async (user) => {
|
| 100 |
if (user) {
|
| 101 |
statusEl.textContent = `Signed in as ${user.email || user.uid}`;
|
| 102 |
-
const q = query(
|
| 103 |
collection(db, "users", user.uid, "analyses"),
|
| 104 |
orderBy("createdAt", "desc")
|
| 105 |
);
|
| 106 |
-
const snap = await getDocs(q)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
}
|
| 111 |
-
|
|
|
|
| 112 |
} else {
|
| 113 |
statusEl.textContent = "Not signed in.";
|
| 114 |
recsEl.innerHTML = '<p class="text-sm text-gray-500">Please sign in to see your analyses.</p>';
|
|
|
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<title>Past Analyzes - CTRL + ALT + HEAL</title>
|
| 6 |
<script src="https://cdn.tailwindcss.com"></script>
|
| 7 |
+
<!--Shared helpers (API base + query params) -->
|
| 8 |
+
<script src="script.js"></script>
|
| 9 |
</head>
|
| 10 |
<body class="bg-[#F7F8F9] min-h-screen">
|
| 11 |
<nav class="bg-white border border-gray-200 px-6 py-4 mb-8">
|
|
|
|
| 101 |
onAuthStateChanged(auth, async (user) => {
|
| 102 |
if (user) {
|
| 103 |
statusEl.textContent = `Signed in as ${user.email || user.uid}`;
|
| 104 |
+
/*const q = query(
|
| 105 |
collection(db, "users", user.uid, "analyses"),
|
| 106 |
orderBy("createdAt", "desc")
|
| 107 |
);
|
| 108 |
+
const snap = await getDocs(q);*/
|
| 109 |
+
|
| 110 |
+
async function getPastReports() {
|
| 111 |
+
try {
|
| 112 |
+
const url = api('reports/', { user_id: user.email });
|
| 113 |
+
const response = await fetch(url, {
|
| 114 |
+
method: 'GET',
|
| 115 |
+
headers: {
|
| 116 |
+
'Content-Type': 'application/json',
|
| 117 |
+
},
|
| 118 |
+
});
|
| 119 |
+
if (!response.ok) {
|
| 120 |
+
throw new Error(`HTTP error! status: ${response.status}`);
|
| 121 |
+
}
|
| 122 |
+
const data = await response.json();
|
| 123 |
+
console.log('Report successfully sent to backend:', data);
|
| 124 |
+
recsEl.innerHTML = data.map(doc => renderAnalysis(doc)).join("");
|
| 125 |
+
} catch (error) {
|
| 126 |
+
console.error('Error sending report to backend:', error);
|
| 127 |
+
recsEl.innerHTML = '<p class="text-sm text-gray-500">No saved analyses yet.</p>';
|
| 128 |
+
}
|
| 129 |
}
|
| 130 |
+
getPastReports();
|
| 131 |
+
|
| 132 |
} else {
|
| 133 |
statusEl.textContent = "Not signed in.";
|
| 134 |
recsEl.innerHTML = '<p class="text-sm text-gray-500">Please sign in to see your analyses.</p>';
|
web/script.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// script.js
|
| 2 |
+
(function () {
|
| 3 |
+
const isLocal = /^(localhost|127\.0\.0\.1)$/.test(location.hostname);
|
| 4 |
+
|
| 5 |
+
// Current page querystring utilities
|
| 6 |
+
const qs = new URLSearchParams(location.search);
|
| 7 |
+
|
| 8 |
+
// Optional API base override: ?api=http://localhost:9000
|
| 9 |
+
const override = qs.get("api");
|
| 10 |
+
const saved = localStorage.getItem("API_BASE");
|
| 11 |
+
|
| 12 |
+
const baseRaw =
|
| 13 |
+
override ||
|
| 14 |
+
saved ||
|
| 15 |
+
// Local dev -> FastAPI on 8000; Prod -> same origin
|
| 16 |
+
(isLocal ? "http://localhost:8000" : location.origin);
|
| 17 |
+
|
| 18 |
+
if (override) localStorage.setItem("API_BASE", override);
|
| 19 |
+
|
| 20 |
+
let API_BASE = baseRaw.replace(/\/$/, ""); // trim trailing slash
|
| 21 |
+
|
| 22 |
+
function buildUrl(path, params) {
|
| 23 |
+
// allow absolute URLs
|
| 24 |
+
const full =
|
| 25 |
+
/^https?:\/\//i.test(path)
|
| 26 |
+
? path
|
| 27 |
+
: API_BASE + (path.startsWith("/") ? path : "/" + path);
|
| 28 |
+
|
| 29 |
+
const url = new URL(full);
|
| 30 |
+
if (params && typeof params === "object") {
|
| 31 |
+
for (const [k, v] of Object.entries(params)) {
|
| 32 |
+
if (v === undefined || v === null) continue;
|
| 33 |
+
if (Array.isArray(v)) {
|
| 34 |
+
v.forEach((val) => url.searchParams.append(k, String(val)));
|
| 35 |
+
} else {
|
| 36 |
+
url.searchParams.set(k, String(v));
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
return url.toString();
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
async function http(method, path, { params, data, headers, ...rest } = {}) {
|
| 44 |
+
const url = buildUrl(path, params);
|
| 45 |
+
const init = {
|
| 46 |
+
method,
|
| 47 |
+
headers: { Accept: "application/json", ...(headers || {}) },
|
| 48 |
+
...rest,
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
if (data instanceof FormData) {
|
| 52 |
+
init.body = data; // let browser set multipart boundary
|
| 53 |
+
} else if (data !== undefined) {
|
| 54 |
+
init.body = JSON.stringify(data);
|
| 55 |
+
init.headers["Content-Type"] = "application/json";
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
const res = await fetch(url, init);
|
| 59 |
+
if (!res.ok) {
|
| 60 |
+
const text = await res.text();
|
| 61 |
+
throw new Error(`${method} ${url} failed (${res.status}) - ${text}`);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
const ct = res.headers.get("content-type") || "";
|
| 65 |
+
return ct.includes("application/json") ? res.json() : res.text();
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
// ---- Expose globals (usable from any page) ----
|
| 69 |
+
window.API_BASE = API_BASE;
|
| 70 |
+
window.setApiBase = (url) => {
|
| 71 |
+
if (!url) return;
|
| 72 |
+
const norm = url.replace(/\/$/, "");
|
| 73 |
+
localStorage.setItem("API_BASE", norm);
|
| 74 |
+
API_BASE = norm;
|
| 75 |
+
window.API_BASE = norm;
|
| 76 |
+
};
|
| 77 |
+
|
| 78 |
+
// Build URL: api(path, params?)
|
| 79 |
+
window.api = (path, params) => buildUrl(path, params);
|
| 80 |
+
|
| 81 |
+
// Simple HTTP helpers
|
| 82 |
+
window.apiGet = (path, params, options) =>
|
| 83 |
+
http("GET", path, { params, ...(options || {}) });
|
| 84 |
+
window.apiPost = (path, data, options) =>
|
| 85 |
+
http("POST", path, { data, ...(options || {}) });
|
| 86 |
+
window.apiPut = (path, data, options) =>
|
| 87 |
+
http("PUT", path, { data, ...(options || {}) });
|
| 88 |
+
window.apiDelete = (path, params, options) =>
|
| 89 |
+
http("DELETE", path, { params, ...(options || {}) });
|
| 90 |
+
window.apiUpload = (path, formData, params, options) =>
|
| 91 |
+
http("POST", path, { params, data: formData, ...(options || {}) });
|
| 92 |
+
|
| 93 |
+
// Query helpers for the *current page* (read-only)
|
| 94 |
+
window.qs = qs; // URLSearchParams instance
|
| 95 |
+
window.getQueryParam = (name, defVal = null) =>
|
| 96 |
+
qs.has(name) ? qs.get(name) : defVal;
|
| 97 |
+
window.getAllQueryParams = () => Object.fromEntries(qs.entries());
|
| 98 |
+
})();
|
| 99 |
+
|