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 @st.cache_resource 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)