Update app.py
Browse files123456789101139 unmodified lines5152535455565734 unmodified lines92939495969798991001011021031041058 unmodified lines1141151161171181191203 unmodified lines12412512612712812913013113213313413513613713813914014114245 unmodified lines1881891901911921931941955 unmodified lines2012022032042052062072082092102114 unmodified lines2162172182192202212224 unmodified lines2272282292302312322332342352362372387 unmodified lines2462472482492502512522532542552562572582592602612622632648 unmodified lines2732742752762772782794 unmodified lines28428528628728828929035 unmodified lines3263273283293303313323333343 unmodified lines3383393403413423433445 unmodified lines35035135235335435535635735835936036136234 unmodified lines397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446# app.py (Complete, for Hugging Face Spaces)from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, status, Requestfrom fastapi.responses import FileResponse, JSONResponse, HTMLResponsefrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestFormfrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModel, EmailStr, Fieldfrom typing import List, Optional # Import Optional from typingimport cv2import numpy as npimport tensorflow as tf39 unmodified linescomment = Column(Text)created_at = Column(DateTime, default=datetime.datetime.utcnow)Base.metadata.create_all(bind=engine) # Create tables# --- Pydantic Schemas ---class UserBase(BaseModel):34 unmodified linestoken_type: strclass TokenData(BaseModel):username: Optional[str] = None # Use Optional[str] instead of str | Noneclass OCRResponse(BaseModel):sakshi_output: strword_count: intprediction_label: str# --- Password Hashing ---pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")8 unmodified linesdb.close()async def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):# Correctly retrieve user by matching token with username.user = get_user_by_username(db, username=token)if not user:raise HTTPException(3 unmodified lines)return userasync def get_current_active_user(current_user: UserModel = Depends(get_current_user)): #Use UserModelif not current_user.is_active:raise HTTPException(status_code=400, detail="Inactive user")return current_userasync def get_current_admin_user(current_user: UserModel = Depends(get_current_active_user)): #Use UserModelif not current_user.is_admin:raise HTTPException(status_code=403, detail="Not an administrator")return current_user# --- CRUD Operations ---def get_user(db: Session, user_id: int):return db.query(UserModel).filter(UserModel.id == user_id).first()45 unmodified linesdef get_feedback(db: Session, skip: int = 0, limit: int = 100):return db.query(FeedbackModel).order_by(FeedbackModel.created_at.desc()).offset(skip).limit(limit).all()# --- FastAPI App Setup ---app = FastAPI(title="Hindi OCR API",5 unmodified linesMODEL_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/hindi_ocr_model.keras"ENCODER_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/label_encoder.pkl"FONT_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/NotoSansDevanagari-Regular.ttf"MODEL_PATH = "hindi_ocr_model.keras" # Local paths after downloadENCODER_PATH = "label_encoder.pkl"FONT_PATH = "NotoSansDevanagari-Regular.ttf"# --- Download Helper ---def download_file(url, dest):if not os.path.exists(dest):print(f"Downloading {dest}...")4 unmodified linesf.write(chunk)print(f"Downloaded {dest}")# --- Model Loading ---def load_model():if not os.path.exists(MODEL_PATH):return None4 unmodified linesreturn Nonewith open(ENCODER_PATH, 'rb') as f:return pickle.load(f)# --- Global Variables ---model = Nonelabel_encoder = Nonesession_files = {} # For storing temporary file paths# --- Startup Event ---@app.on_event("startup")async def startup_event():global model, label_encoder7 unmodified linesmodel = load_model()label_encoder = load_label_encoder()# Create an admin user if one doesn't existdb = SessionLocal()if not get_user_by_username(db, "admin"):admin_user = UserCreate(username="admin", email="admin@example.com", password="adminpassword") #Change the password herecreate_user(db, admin_user)admin = get_user_by_username(db, "admin")admin.is_admin = True # Make this user an admindb.commit()db.close()# --- Word Detection ---def detect_words(image):_, binary = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)kernel = np.ones((3,3), np.uint8)8 unmodified linesword_count += 1return word_img, word_count# --- Sakshi OCR ---def run_py_text_scan(image_path):buffer = io.StringIO()old_stdout = sys.stdout4 unmodified linessys.stdout = old_stdoutreturn buffer.getvalue()# --- Image Processing ---def process_image(image_array):img = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY)word_detected_img, word_count = detect_words(img)35 unmodified lines"prediction_label": pred_label}# --- API Endpoints ---# Authentication Endpoints@app.post("/token", response_model=Token)async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):user = get_user_by_username(db, form_data.username)3 unmodified linesdetail="Incorrect username or password",headers={"WWW-Authenticate": "Bearer"},)# Use username as the access token (for simplicity in this example)access_token = user.usernamereturn {"access_token": access_token, "token_type": "bearer"}5 unmodified linesdb_user_email = get_user_by_email(db, email=user.email)if db_user_email:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered")created = create_user(db=db, user=user)return created# OCR Endpoint@app.post("/process/", response_model=OCRResponse)async def process(file: UploadFile = File(...), current_user: UserModel = Depends(get_current_active_user)):if not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")34 unmodified linesraise HTTPException(status_code=404, detail="Prediction image not found")return FileResponse(session_files['prediction'])# Feedback Endpoint@app.post("/feedback/", response_model=FeedbackResponse)async def create_feedback_route(feedback: FeedbackCreate, current_user: UserModel = Depends(get_current_active_user),db: Session = Depends(get_db)):return create_feedback(db=db, feedback=feedback)# Admin Endpoints@app.get("/admin/users/", response_model=List[UserResponse])async def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_admin_user)):users = get_users(db, skip=skip, limit=limit)return users@app.get("/admin/users/{user_id}", response_model=UserResponse)async def read_user(user_id: int, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_admin_user)):db_user = get_user(db, user_id=user_id)if db_user is None:raise HTTPException(status_code=404, detail="User not found")return db_user@app.put("/admin/users/{user_id}", response_model=UserResponse)async def update_user_route(user_id: int, user: UserUpdate, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_admin_user)):updated_user = update_user(db=db, user_id=user_id, user=user)if updated_user is None:raise HTTPException(status_code=404, detail="User not found")return updated_user@app.delete("/admin/users/{user_id}", response_model=dict)async def delete_user_route(user_id: int, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_admin_user)):if delete_user(db=db, user_id=user_id):return {"message": "User deleted successfully"}else:raise HTTPException(status_code=404, detail="User not found")@app.get("/admin/feedback/", response_model=List[FeedbackResponse])async def read_feedback(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: UserModel = Depends(get_current_admin_user)):feedback = get_feedback(db, skip=skip, limit=limit)return feedback# Basic Root Endpoint@app.get("/")async def root():return {"message": "Hindi OCR API with Authentication and Admin. See /docs for API details."}# --- Run with uvicorn (for local testing) ---if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)1234567839 unmodified lines4849505152535434 unmodified lines89909192939495969798991001018 unmodified lines1101111121131141153 unmodified lines11912012112212312412512612712812913013113213313445 unmodified lines1801811821831841855 unmodified lines1911921931941951961971981992004 unmodified lines2052062072082092104 unmodified lines2152162172182192202212222232242257 unmodified lines2332342352362372382392402412422432442452462478 unmodified lines2562572582592602614 unmodified lines26626726826927027135 unmodified lines3073083093103113123 unmodified lines3163173183193203215 unmodified lines32732832933033133233333433533633734 unmodified lines372373374375376377378379380381382383384385386387388389390391392393394395396397from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, status, Requestfrom fastapi.responses import FileResponse, JSONResponse, HTMLResponsefrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestFormfrom pydantic import BaseModel, EmailStr, Fieldfrom typing import List, Optionalimport cv2import numpy as npimport tensorflow as tf39 unmodified linescomment = Column(Text)created_at = Column(DateTime, default=datetime.datetime.utcnow)Base.metadata.create_all(bind=engine)# --- Pydantic Schemas ---class UserBase(BaseModel):34 unmodified linestoken_type: strclass TokenData(BaseModel):username: Optional[str] = Noneclass OCRResponse(BaseModel):sakshi_output: strword_count: intprediction_label: str# --- Password Hashing ---pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")8 unmodified linesdb.close()async def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):user = get_user_by_username(db, username=token)if not user:raise HTTPException(3 unmodified lines)return userasync def get_current_active_user(current_user: UserModel = Depends(get_current_user)):if not current_user.is_active:raise HTTPException(status_code=400, detail="Inactive user")return current_userasync def get_current_admin_user(current_user: UserModel = Depends(get_current_active_user)):if not current_user.is_admin:raise HTTPException(status_code=403, detail="Not an administrator")return current_user# --- CRUD Operations ---def get_user(db: Session, user_id: int):return db.query(UserModel).filter(UserModel.id == user_id).first()45 unmodified linesdef get_feedback(db: Session, skip: int = 0, limit: int = 100):return db.query(FeedbackModel).order_by(FeedbackModel.created_at.desc()).offset(skip).limit(limit).all()# --- FastAPI App Setup ---app = FastAPI(title="Hindi OCR API",5 unmodified linesMODEL_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/hindi_ocr_model.keras"ENCODER_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/label_encoder.pkl"FONT_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/NotoSansDevanagari-Regular.ttf"MODEL_PATH = "hindi_ocr_model.keras"ENCODER_PATH = "label_encoder.pkl"FONT_PATH = "NotoSansDevanagari-Regular.ttf"def download_file(url, dest):if not os.path.exists(dest):print(f"Downloading {dest}...")4 unmodified linesf.write(chunk)print(f"Downloaded {dest}")def load_model():if not os.path.exists(MODEL_PATH):return None4 unmodified linesreturn Nonewith open(ENCODER_PATH, 'rb') as f:return pickle.load(f)model = Nonelabel_encoder = Nonesession_files = {}@app.on_event("startup")async def startup_event():global model, label_encoder7 unmodified linesmodel = load_model()label_encoder = load_label_encoder()db = SessionLocal()if not get_user_by_username(db, "admin"):admin_user = UserCreate(username="admin", email="admin@example.com", password="adminpassword")create_user(db, admin_user)admin = get_user_by_username(db, "admin")admin.is_admin = Truedb.commit()db.close()def detect_words(image):_, binary = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)kernel = np.ones((3,3), np.uint8)8 unmodified linesword_count += 1return word_img, word_countdef run_py_text_scan(image_path):buffer = io.StringIO()old_stdout = sys.stdout4 unmodified linessys.stdout = old_stdoutreturn buffer.getvalue()def process_image(image_array):img = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY)word_detected_img, word_count = detect_words(img)35 unmodified lines"prediction_label": pred_label}@app.post("/token", response_model=Token)async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):user = get_user_by_username(db, form_data.username)3 unmodified linesdetail="Incorrect username or password",headers={"WWW-Authenticate": "Bearer"},)access_token = user.usernamereturn {"access_token": access_token, "token_type": "bearer"}5 unmodified linesdb_user_email = get_user_by_email(db, email=user.email)if db_user_email:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Email already registered")created = create_user(db=db, user=user)return created@app.post("/process/", response_model=OCRResponse)async def process(file: UploadFile = File(...), current_user: UserModel = Depends(get_current_active_user)):if not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")34 unmodified linesraise HTTPException(status_code=404, detail="Prediction image not found")return FileResponse(session_files['prediction'])# --- Modified Feedback Endpoint ---# No authentication dependency is used here so that anyone can submit feedback.@app.post("/feedback/", response_model=FeedbackResponse)async def create_feedback_route(feedback: FeedbackCreate, db: Session = Depends(get_db)):return create_feedback(db=db, feedback=feedback)# --- Admin Endpoints ---@app.get("/admin/users/")async def admin_get_users(skip: int = 0, limit: int = 100, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):return get_users(db, skip=skip, limit=limit)@app.delete("/admin/users/{user_id}")async def admin_delete_user(user_id: int, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):if delete_user(db, user_id):return {"detail": "User deleted successfully"}raise HTTPException(status_code=404, detail="User not found")@app.get("/admin/feedback/")async def admin_get_feedback(skip: int = 0, limit: int = 100, current_user: UserModel = Depends(get_current_admin_user), db: Session = Depends(get_db)):return get_feedback(db, skip=skip, limit=limit)if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)
app.py+28-77