|
from fastapi import FastAPI, Query, Request |
|
from fastapi.responses import HTMLResponse |
|
from fastapi.templating import Jinja2Templates |
|
from fastapi.staticfiles import StaticFiles |
|
from fastapi.middleware.cors import CORSMiddleware |
|
from utils.vector_search import get_similar_symptoms |
|
from utils.sql_queries import get_diseases_by_symptoms, get_related_symptoms |
|
import sqlite3 |
|
|
|
app = FastAPI() |
|
|
|
|
|
app.add_middleware( |
|
CORSMiddleware, |
|
allow_origins=["*"], |
|
allow_credentials=True, |
|
allow_methods=["*"], |
|
allow_headers=["*"], |
|
) |
|
|
|
templates = Jinja2Templates(directory="templates") |
|
|
|
@app.get("/", response_class=HTMLResponse) |
|
def index(request: Request): |
|
return templates.TemplateResponse("index.html", {"request": request}) |
|
|
|
|
|
def is_valid_symptom(symptom): |
|
conn = sqlite3.connect("disease.db") |
|
cur = conn.cursor() |
|
cur.execute("SELECT COUNT(*) FROM symptom WHERE name = ?", (symptom,)) |
|
count = cur.fetchone()[0] |
|
conn.close() |
|
return count > 0 |
|
|
|
@app.get("/search") |
|
def search(symptom: str, selected: list[str] = Query([])): |
|
|
|
similar = get_similar_symptoms(symptom) |
|
|
|
|
|
if is_valid_symptom(symptom): |
|
|
|
search_symptoms = [symptom] + selected |
|
else: |
|
|
|
valid_symptom_found = False |
|
for sim in similar: |
|
if is_valid_symptom(sim): |
|
search_symptoms = [sim] + selected |
|
valid_symptom_found = True |
|
break |
|
|
|
|
|
if not valid_symptom_found: |
|
search_symptoms = similar + selected |
|
|
|
|
|
diseases = get_diseases_by_symptoms(search_symptoms) |
|
|
|
|
|
suggestions = get_related_symptoms(diseases, exclude=search_symptoms) |
|
|
|
return { |
|
"matching_diseases": diseases, |
|
"related_symptoms": suggestions, |
|
"semantic_matches": similar |
|
} |
|
|