CoolFace
Apppublic

BytecodeApps/docverse-api

sourceHugging Faceapache-2.0updated 7mo agoView on Hugging Face
0likes
main.py90 linesDownload Raw Back to app
1import sys2from fastapi import FastAPI, UploadFile, File, Depends, HTTPException, status3from fastapi.middleware.cors import CORSMiddleware4from sqlalchemy.orm import Session5from datetime import datetime6 7# Initialize FastAPI App8app = FastAPI(9    title="DocVerse Medical Intelligence API",10    description="FastAPI Backend for Document Scanning, NLP, and Risk Analysis",11    version="1.0.0",12)13 14# CORS Middleware Configurations15app.add_middleware(16    CORSMiddleware,17    allow_origins=["*"], # In production, restrict this18    allow_credentials=True,19    allow_methods=["*"],20    allow_headers=["*"],21)22 23from app.db.database import engine, get_db24from app.models.database_models import Base, User, Report, LabResult, RiskFlag25 26# Create all tables in DB if they don't exist27Base.metadata.create_all(bind=engine)28 29# Route Definitions30@app.get("/")31def health_check():32    return {"status": "ok", "timestamp": datetime.utcnow()}33 34@app.post("/api/v1/auth/register")35def register_user(user_data: dict, db: Session = Depends(get_db)):36    """ Register a new user and generate a JWT token """37    # Real logic: Hash password with passlib38    new_user = User(email=user_data.get("email"), password_hash="hashed_pw_here")39    db.add(new_user)40    db.commit()41    db.refresh(new_user)42    return {"message": "User registered successfully", "user_id": str(new_user.id)}43 44@app.post("/api/v1/auth/login")45def login(credentials: dict, db: Session = Depends(get_db)):46    """ Login user and return JWT """47    return {"access_token": "mock_jwt_token", "token_type": "bearer"}48 49@app.post("/api/v1/scan/upload")50async def upload_document(51    file: UploadFile = File(...), 52    current_user: str = "mock_user",  # JWT Dependency in reality53    db: Session = Depends(get_db)54):55    """ Upload document (PDF/Image) for OCR Processing """56    if not file.filename.endswith(('.pdf', '.png', '.jpg', '.jpeg')):57        raise HTTPException(status_code=400, detail="Invalid file format.")58    59    # 1. Encrypt and save file to secure storage (S3)60    # 2. Add Celery Task to process OCR and NLP61    task_id = "mock_task_id_999"62    return {"message": "File uploaded and processing started.", "task_id": task_id}63 64@app.get("/api/v1/scan/status/{task_id}")65def get_scan_status(task_id: str):66    """ Check the processing status of the OCR/NLP pipeline """67    return {"task_id": task_id, "status": "completed", "progress": 100}68 69@app.get("/api/v1/reports")70def get_reports(current_user: str = "mock_user", db: Session = Depends(get_db)):71    """ Get paginated list of encrypted user reports """72    # Real logic: Filter by current authenticated user73    reports = db.query(Report).all()74    return {"reports": [{"id": str(r.id), "file_name": r.file_name, "status": r.status} for r in reports]}75 76@app.get("/api/v1/health/labs")77def get_lab_trends(current_user: str = "mock_user", db: Session = Depends(get_db)):78    """ Retrieve timeline data for lab tests to chart in Flutter """79    labs = db.query(LabResult).all()80    return {"lab_trends": [{"test": l.test_name, "value": l.test_value, "flag": l.flag} for l in labs]}81 82@app.post("/api/v1/reminders")83def create_reminder(reminder: dict, current_user: str = "mock_user", db: Session = Depends(get_db)):84    """ Add a medication reminder """85    return {"message": "Reminder created successfully", "reminder_id": "999"}86 87if __name__ == "__main__":88    import uvicorn89    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)90