Spaces:
Sleeping
Sleeping
Update app.py
Browse files12123648567839 unmodified lines484950545152535434 unmodified lines8990919592939495969798102991001018 unmodified lines1101111121171131141153 unmodified lines11912012112712812212312412512613312712812913013113813913213313445 unmodified lines1801811821911921831841855 unmodified lines1911921932041941951961972081981992004 unmodified lines2052062072192082092104 unmodified lines2152162172302182192202332212222352232242257 unmodified lines2332342352492362372522382392402552412422432442592602612452462478 unmodified lines2562572582762592602614 unmodified lines26626726828726927027135 unmodified lines3073083093293303313103113123 unmodified lines3163173183413193203215 unmodified lines32732832935333033133235635733335933433533633734 unmodified lines372373374400375376377402378379380405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436381382383384385438439440441386387388389390391392393394395444396446397# 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 typingfrom typing import List, Optionalimport cv2import numpy as npimport tensorflow as tf39 unmodified lines comment = Column(Text) created_at = Column(DateTime, default=datetime.datetime.utcnow)
Base.metadata.create_all(bind=engine) # Create tablesBase.metadata.create_all(bind=engine)
# --- Pydantic Schemas ---class UserBase(BaseModel):34 unmodified lines token_type: str
class TokenData(BaseModel): username: Optional[str] = None # Use Optional[str] instead of str | None username: Optional[str] = None
class OCRResponse(BaseModel): sakshi_output: str word_count: int prediction_label: str
# --- Password Hashing ---pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
8 unmodified lines db.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 user
async def get_current_active_user(current_user: UserModel = Depends(get_current_user)): #Use UserModelasync 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_user
async def get_current_admin_user(current_user: UserModel = Depends(get_current_active_user)): #Use UserModelasync 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" # Local paths after downloadMODEL_PATH = "hindi_ocr_model.keras"ENCODER_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 lines f.write(chunk) print(f"Downloaded {dest}")
# --- Model Loading ---def load_model(): if not os.path.exists(MODEL_PATH): return None4 unmodified lines return None with open(ENCODER_PATH, 'rb') as f: return pickle.load(f)# --- Global Variables ---
model = Nonelabel_encoder = Nonesession_files = {} # For storing temporary file pathssession_files = {}
# --- Startup Event ---@app.on_event("startup")async def startup_event(): global model, label_encoder7 unmodified lines model = load_model() label_encoder = load_label_encoder()
# Create an admin user if one doesn't exist db = SessionLocal() if not get_user_by_username(db, "admin"): admin_user = UserCreate(username="admin", email="admin@example.com", password="adminpassword") #Change the password here 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 = True # Make this user an admin admin.is_admin = True db.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 lines word_count += 1 return word_img, word_count
# --- Sakshi OCR ---def run_py_text_scan(image_path): buffer = io.StringIO() old_stdout = sys.stdout4 unmodified lines sys.stdout = old_stdout return 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 lines detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) # Use username as the access token (for simplicity in this example) access_token = user.username return {"access_token": access_token, "token_type": "bearer"}
5 unmodified lines db_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) 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)):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 lines raise HTTPException(status_code=404, detail="Prediction image not found") return FileResponse(session_files['prediction'])
# Feedback Endpoint# --- 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, current_user: UserModel = Depends(get_current_active_user),db: Session = Depends(get_db)):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/", 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# --- 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)
# Basic Root Endpoint@app.get("/")async def root(): return {"message": "Hindi OCR API with Authentication and Admin. See /docs for API details."}@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)
# --- Run with uvicorn (for local testing) ---if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) uvicorn.run(app, host="0.0.0.0", port=8000)app.py+28-77