ZennyKenny commited on
Commit
0fd8a0b
·
verified ·
1 Parent(s): 6e9b692

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -36
app.py CHANGED
@@ -1,45 +1,63 @@
1
- import gradio as gr
2
- from transformers import TrOCRProcessor, VisionEncoderDecoderModel
3
  from PIL import Image
4
  import torch
 
5
  import spaces
6
 
7
- # Load TrOCR model
8
- processor = TrOCRProcessor.from_pretrained("microsoft/trocr-large-handwritten")
9
- model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-large-handwritten")
 
 
 
 
10
 
11
  @spaces.GPU
12
- def recognize_text(image):
13
- try:
14
- # Convert image to RGB
15
- image = image.convert("RGB")
16
- print("Image converted to RGB.")
17
-
18
- # Preprocess the image using the processor
19
- pixel_values = processor(image, return_tensors="pt").pixel_values
20
- print("Image preprocessed. Pixel values shape:", pixel_values.shape)
21
-
22
- # Generate text from the image
23
- with torch.no_grad():
24
- generated_ids = model.generate(pixel_values)
25
- print("Generated IDs:", generated_ids)
26
-
27
- # Decode the generated IDs to text
28
- text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
29
- print("Decoded text:", text)
30
-
31
- return text
32
- except Exception as e:
33
- print(f"Error: {str(e)}")
34
- return f"Error: {str(e)}"
35
-
36
- # Gradio UI
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  note = gr.Interface(
38
- fn=recognize_text,
39
- inputs=gr.Image(type="pil"),
40
- outputs="text",
41
- title="Handwritten Note to Digital Text",
42
- description="Upload an image of handwritten text, and the AI will convert it to digital text."
43
  )
44
 
45
- note.launch()
 
 
1
+ from transformers import MllamaForConditionalGeneration, AutoProcessor
 
2
  from PIL import Image
3
  import torch
4
+ import gradio as gr
5
  import spaces
6
 
7
+ # Initialize model and processor
8
+ ocr = "unsloth/Llama-3.2-11B-Vision-Instruct"
9
+ model = MllamaForConditionalGeneration.from_pretrained(
10
+ ocr,
11
+ torch_dtype=torch.bfloat16
12
+ ).to("cuda")
13
+ processor = AutoProcessor.from_pretrained(ocr)
14
 
15
  @spaces.GPU
16
+ def extract_text(image):
17
+ # Convert image to RGB
18
+ image = Image.open(image).convert("RGB")
19
+
20
+ # Create message structure
21
+ messages = [
22
+ {
23
+ "role": "user",
24
+ "content": [
25
+ {"type": "text", "text": "Extract handwritten text from the image and output only the extracted text without any additional description or commentary in output"},
26
+ {"type": "image"}
27
+ ]
28
+ }
29
+ ]
30
+
31
+ # Process input
32
+ texts = processor.apply_chat_template(messages, add_generation_prompt=True)
33
+ inputs = processor(text=texts, images=[image], return_tensors="pt").to("cuda")
34
+
35
+
36
+ # Generate output
37
+ outputs = model.generate(**inputs, max_new_tokens=250)
38
+ result = processor.decode(outputs[0], skip_special_tokens=True)
39
+
40
+ print(result)
41
+
42
+ # Clean up the output to remove the prompt and assistant text
43
+ if "assistant" in result.lower():
44
+ result = result[result.lower().find("assistant") + len("assistant"):].strip()
45
+
46
+ # Remove any remaining conversation markers
47
+ result = result.replace("user", "").replace("Extract handwritten text from the image and output only the extracted text without any additional description or commentary in output", "").strip()
48
+
49
+ print(result)
50
+
51
+ return result
52
+
53
+ # Create Gradio interface
54
  note = gr.Interface(
55
+ fn=extract_text,
56
+ inputs=gr.Image(type="filepath", label="Upload Image"),
57
+ outputs=gr.Textbox(label="Extracted Text"),
58
+ title="Handwritten Text Extractor",
59
+ description="Upload an image containing handwritten text to extract its content.",
60
  )
61
 
62
+ # Launch the app
63
+ note.launch(debug=True)