Spaces:
Sleeping
Sleeping
Update app.py
Browse files29 unmodified lines3031323334353637383940414213 unmodified lines56575859606144 unmodified lines1061071081091101111 unmodified line1131141151161171181191201211229 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571588 unmodified lines16716816917017117220 unmodified lines19319419519619719819920020120220320420520620720820921029 unmodified linesFONT_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/NotoSansDevanagari-Regular.ttf"# Paths for local storageMODEL_PATH = "hindi_ocr_model.keras"ENCODER_PATH = "label_encoder.pkl"FONT_PATH = "NotoSansDevanagari-Regular.ttf"OUTPUT_DIR = "output"# Create output directory if it doesn't existos.makedirs(OUTPUT_DIR, exist_ok=True)# Download model and encoderdef download_file(url, dest):13 unmodified lineswith open(ENCODER_PATH, 'rb') as f:return pickle.load(f)# Download required files on startup@app.on_event("startup")async def startup_event():44 unmodified linessys.stdout = old_stdoutreturn buffer.getvalue()# Main OCR processing functiondef process_image(image_array):# Convert image array to grayscale1 unmodified line# Word detectionword_detected_img, word_count = detect_words(img)word_detection_path = os.path.join(OUTPUT_DIR, "word_detection.png")cv2.imwrite(word_detection_path, word_detected_img)# First OCR model predictiontry:img_resized = cv2.resize(img, (128, 32))img_norm = img_resized / 255.09 unmodified linesax.imshow(img, cmap='gray')ax.set_title(f"Predicted: {pred_label}", fontsize=12)ax.axis('off')pred_path = os.path.join(OUTPUT_DIR, "prediction.png")plt.savefig(pred_path)plt.close()else:pred_path = Nonepred_label = "Model or encoder not loaded"except Exception as e:pred_path = Nonepred_label = f"Error: {str(e)}"# Sakshi OCR processingwith tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:cv2.imwrite(tmp_file.name, img)sakshi_output = run_sakshi_ocr(tmp_file.name)os.remove(tmp_file.name)return {"sakshi_output": sakshi_output,"word_detection_path": word_detection_path,"word_count": word_count,"prediction_path": pred_path,"prediction_label": pred_label}8 unmodified linesif not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")# Create a temporary file to save the uploaded imagetemp_file = tempfile.NamedTemporaryFile(delete=False)try:20 unmodified lines@app.get("/word-detection/")async def get_word_detection():"""Return the word detection image."""word_detection_path = Path(OUTPUT_DIR) / "word_detection.png"if not word_detection_path.exists():raise HTTPException(status_code=404, detail="Word detection image not found. Process an image first.")return FileResponse(word_detection_path)@app.get("/prediction/")async def get_prediction():"""Return the prediction image."""prediction_path = Path(OUTPUT_DIR) / "prediction.png"if not prediction_path.exists():raise HTTPException(status_code=404, detail="Prediction image not found. Process an image first.")return FileResponse(prediction_path)@app.get("/")async def root():29 unmodified lines30313233343536373839404113 unmodified lines5556575859606162636444 unmodified lines1091101111121131141151161171 unmodified line1191201211221231241251261271281291301311329 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681698 unmodified lines17817918018118218318418518618718818919019119220 unmodified lines21321421521621721821922022122222322422522622722829 unmodified linesFONT_URL = "https://huggingface.co/sameernotes/hindi-ocr/resolve/main/NotoSansDevanagari-Regular.ttf"# Paths for local storageMODEL_PATH = os.path.join(tempfile.gettempdir(), "hindi_ocr_model.keras")ENCODER_PATH = os.path.join(tempfile.gettempdir(), "label_encoder.pkl")FONT_PATH = os.path.join(tempfile.gettempdir(), "NotoSansDevanagari-Regular.ttf")# Use a temporary directory for outputsOUTPUT_DIR = tempfile.mkdtemp()# Download model and encoderdef download_file(url, dest):13 unmodified lineswith open(ENCODER_PATH, 'rb') as f:return pickle.load(f)# Set up global variablesmodel = Nonelabel_encoder = None# Download required files on startup@app.on_event("startup")async def startup_event():44 unmodified linessys.stdout = old_stdoutreturn buffer.getvalue()# File storage for sessionsession_files = {}# Main OCR processing functiondef process_image(image_array):# Convert image array to grayscale1 unmodified line# Word detectionword_detected_img, word_count = detect_words(img)word_detection_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").namecv2.imwrite(word_detection_path, word_detected_img)# Store the file path in our session dictsession_files['word_detection'] = word_detection_path# First OCR model predictionpred_path = Nonetry:img_resized = cv2.resize(img, (128, 32))img_norm = img_resized / 255.09 unmodified linesax.imshow(img, cmap='gray')ax.set_title(f"Predicted: {pred_label}", fontsize=12)ax.axis('off')pred_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").nameplt.savefig(pred_path)plt.close()# Store the file path in our session dictsession_files['prediction'] = pred_pathelse:pred_label = "Model or encoder not loaded"except Exception as e:pred_label = f"Error: {str(e)}"# Sakshi OCR processingwith tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:cv2.imwrite(tmp_file.name, img)sakshi_output = run_sakshi_ocr(tmp_file.name)os.unlink(tmp_file.name)return {"sakshi_output": sakshi_output,"word_detection_path": word_detection_path if 'word_detection' in session_files else None,"word_count": word_count,"prediction_path": pred_path if 'prediction' in session_files else None,"prediction_label": pred_label}8 unmodified linesif not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="File must be an image")# Clean up previous session filesfor key, filepath in session_files.items():if os.path.exists(filepath):try:os.unlink(filepath)except:passsession_files.clear()# Create a temporary file to save the uploaded imagetemp_file = tempfile.NamedTemporaryFile(delete=False)try:20 unmodified lines@app.get("/word-detection/")async def get_word_detection():"""Return the word detection image."""if 'word_detection' not in session_files or not os.path.exists(session_files['word_detection']):raise HTTPException(status_code=404, detail="Word detection image not found. Process an image first.")return FileResponse(session_files['word_detection'])@app.get("/prediction/")async def get_prediction():"""Return the prediction image."""if 'prediction' not in session_files or not os.path.exists(session_files['prediction']):raise HTTPException(status_code=404, detail="Prediction image not found. Process an image first.")return FileResponse(session_files['prediction'])@app.get("/")async def root():
app.py+37-19