File size: 1,911 Bytes
1407852
 
eb204c7
 
 
 
 
 
 
 
 
1407852
 
 
 
 
 
84f5738
 
 
 
 
1407852
84f5738
1407852
 
 
84f5738
 
1407852
84f5738
1407852
 
 
 
84f5738
1407852
 
84f5738
1407852
 
 
84f5738
1407852
 
 
 
 
84f5738
1407852
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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)