Spaces:
Runtime error
Runtime error
Download streamlit_app.py from engrtm/Advanced-Handwritten-OCR: direct link, hf CLI and curl.
- Browser
- Download file 1.91 kB
-
https://huggingface.co/spaces/engrtm/Advanced-Handwritten-OCR/resolve/main/streamlit_app.py
- Command line
-
hf download hf://spaces/engrtm/Advanced-Handwritten-OCR/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/engrtm/Advanced-Handwritten-OCR/resolve/main/streamlit_app.py
1.91 kB
| import os | |
| # Redirect Streamlit config directory to a writable local folder | |
| os.environ["STREAMLIT_CONFIG_DIR"] = ".streamlit" | |
| os.makedirs(".streamlit", exist_ok=True) | |
| with open(".streamlit/config.toml", "w") as f: | |
| f.write("[browser]\ngatherUsageStats = false\n") | |
| import os | |
| # π§ Fix permission error by redirecting Streamlit config to a safe directory | |
| os.environ["STREAMLIT_CONFIG_DIR"] = ".streamlit" | |
| os.makedirs(".streamlit", exist_ok=True) | |
| with open(".streamlit/config.toml", "w") as f: | |
| f.write("[browser]\ngatherUsageStats = false\n") | |
| import streamlit as st | |
| from PIL import Image, ImageOps | |
| import torch | |
| from transformers import TrOCRProcessor, VisionEncoderDecoderModel | |
| # π§ Load model and processor | |
| def load_model(): | |
| processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten") | |
| model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten") | |
| return processor, model | |
| processor, model = load_model() | |
| # πΌοΈ App layout | |
| st.set_page_config(page_title="βοΈ Handwritten OCR", layout="centered") | |
| st.title("ποΈ Handwritten Image to Text") | |
| st.markdown("Upload an image of **handwritten text**, and this app will extract the text using TrOCR.") | |
| # π€ File uploader | |
| uploaded_file = st.file_uploader("Upload a handwritten image", type=["jpg", "jpeg", "png"]) | |
| if uploaded_file: | |
| image = Image.open(uploaded_file).convert("RGB") | |
| st.image(image, caption="Uploaded Image", use_column_width=True) | |
| with st.spinner("π΅οΈ Extracting text..."): | |
| # Preprocess and predict | |
| pixel_values = processor(images=image, return_tensors="pt").pixel_values | |
| generated_ids = model.generate(pixel_values) | |
| extracted_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] | |
| st.success("β Text Extracted!") | |
| st.text_area("π Extracted Text", extracted_text, height=200) | |