Hammedalmodel commited on
Commit
3387487
·
verified ·
1 Parent(s): f43cd25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -47
app.py CHANGED
@@ -2,8 +2,7 @@ from transformers import MllamaForConditionalGeneration, AutoProcessor
2
  from PIL import Image
3
  import torch
4
  import gradio as gr
5
- import requests
6
- from io import BytesIO
7
 
8
  # Initialize model and processor
9
  ckpt = "unsloth/Llama-3.2-11B-Vision-Instruct"
@@ -13,57 +12,52 @@ model = MllamaForConditionalGeneration.from_pretrained(
13
  ).to("cuda")
14
  processor = AutoProcessor.from_pretrained(ckpt)
15
 
16
- def extract_text(image_input):
17
- """
18
- Extract handwritten text from the given image.
19
- `image_input` can be a file path or a URL.
20
- """
21
- try:
22
- # Handle file upload or URL
23
- if isinstance(image_input, str) and image_input.startswith("http"):
24
- response = requests.get(image_input)
25
- response.raise_for_status() # Check for errors
26
- image = Image.open(BytesIO(response.content)).convert("RGB")
27
- else:
28
- image = Image.open(image_input).convert("RGB")
29
-
30
- # Create message structure
31
- messages = [
32
- {
33
- "role": "user",
34
- "content": [
35
- {"type": "text", "text": "Extract handwritten text from the image and output only the extracted text without any additional description or commentary in output"},
36
- {"type": "image"}
37
- ]
38
- }
39
- ]
40
-
41
- # Process input
42
- texts = processor.apply_chat_template(messages, add_generation_prompt=True)
43
- inputs = processor(text=texts, images=[image], return_tensors="pt").to("cuda")
44
-
45
- # Generate output
46
- outputs = model.generate(**inputs, max_new_tokens=250)
47
- result = processor.decode(outputs[0], skip_special_tokens=True)
48
-
49
- # Clean up the output
50
- if "assistant" in result.lower():
51
- result = result[result.lower().find("assistant") + len("assistant"):].strip()
52
- result = result.replace("user", "").strip()
53
-
54
- return result
55
-
56
- except Exception as e:
57
- return f"Error: {str(e)}"
58
 
59
  # Create Gradio interface
60
  demo = gr.Interface(
61
  fn=extract_text,
62
- inputs=gr.Textbox(label="Image URL or Upload Image"),
63
  outputs=gr.Textbox(label="Extracted Text"),
64
  title="Handwritten Text Extractor",
65
- description="Provide an image URL or upload an image containing handwritten text to extract its content.",
66
  )
67
 
68
  # Launch the app
69
- demo.launch(debug=True)
 
2
  from PIL import Image
3
  import torch
4
  import gradio as gr
5
+ import spaces
 
6
 
7
  # Initialize model and processor
8
  ckpt = "unsloth/Llama-3.2-11B-Vision-Instruct"
 
12
  ).to("cuda")
13
  processor = AutoProcessor.from_pretrained(ckpt)
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
  demo = 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
+ demo.launch(debug=True)