Spaces:
Sleeping
Sleeping
Update app.py
Browse files29 unmodified lines30313233343536333435363839373839404113 unmodified lines5556575859606162636444 unmodified lines1091101111121131141151161171 unmodified line1191201211161221231241251261271281291301311329 unmodified lines1421431441351451461471481491501511391521531421541551561571581591491601611621631531641651551661671681698 unmodified lines17817918018118218318418518618718818919019119220 unmodified lines21321421519619721621719921821922022122220420522322420722522622722829 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"MODEL_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")
# Create output directory if it doesn't existos.makedirs(OUTPUT_DIR, exist_ok=True)# Use a temporary directory for outputsOUTPUT_DIR = tempfile.mkdtemp()
# Download model and encoderdef download_file(url, dest):13 unmodified lines with 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 lines sys.stdout = old_stdout return buffer.getvalue()
# File storage for sessionsession_files = {}
# Main OCR processing functiondef process_image(image_array): # Convert image array to grayscale1 unmodified line # Word detection word_detected_img, word_count = detect_words(img) word_detection_path = os.path.join(OUTPUT_DIR, "word_detection.png") word_detection_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").name cv2.imwrite(word_detection_path, word_detected_img) # Store the file path in our session dict session_files['word_detection'] = word_detection_path # First OCR model prediction pred_path = None try: img_resized = cv2.resize(img, (128, 32)) img_norm = img_resized / 255.09 unmodified lines ax.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") pred_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").name plt.savefig(pred_path) plt.close() # Store the file path in our session dict session_files['prediction'] = pred_path else: pred_path = None pred_label = "Model or encoder not loaded" except Exception as e: pred_path = None pred_label = f"Error: {str(e)}" # Sakshi OCR processing with 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) os.unlink(tmp_file.name) return { "sakshi_output": sakshi_output, "word_detection_path": word_detection_path, "word_detection_path": word_detection_path if 'word_detection' in session_files else None, "word_count": word_count, "prediction_path": pred_path, "prediction_path": pred_path if 'prediction' in session_files else None, "prediction_label": pred_label }
8 unmodified lines if not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") # Clean up previous session files for key, filepath in session_files.items(): if os.path.exists(filepath): try: os.unlink(filepath) except: pass session_files.clear() # Create a temporary file to save the uploaded image temp_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(): 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(word_detection_path) return FileResponse(session_files['word_detection'])
@app.get("/prediction/")async def get_prediction(): """Return the prediction image.""" prediction_path = Path(OUTPUT_DIR) / "prediction.png" if not prediction_path.exists(): 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(prediction_path) return FileResponse(session_files['prediction'])
@app.get("/")async def root():app.py+37-19