xzerus commited on
Commit
43b6fd6
·
verified ·
1 Parent(s): 08d3750

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -32
app.py CHANGED
@@ -1,35 +1,100 @@
1
- import os
2
- from transformers import AutoProcessor, AutoModelForCausalLM
3
- import gradio as gr
4
- import torch
5
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Load the Hugging Face token from environment variables
8
- hf_token = os.getenv("HF_AUTH_TOKEN")
9
- model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct"
10
- device = "cuda" if torch.cuda.is_available() else "cpu"
11
-
12
- # Load the model and processor with authentication
13
- processor = AutoProcessor.from_pretrained(model_name, use_auth_token=hf_token, trust_remote_code=True)
14
- model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=hf_token, torch_dtype=torch.float16, trust_remote_code=True).to(device)
15
-
16
- # Function to process image and text prompt
17
- def process_image(image, prompt="<ocr>"):
18
- inputs = processor(images=image, text=prompt, return_tensors="pt").to(device)
19
- outputs = model.generate(**inputs, max_new_tokens=1024)
20
- generated_text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
21
- return generated_text
22
-
23
- # Gradio Interface
24
- iface = gr.Interface(
25
- fn=process_image,
26
- inputs=[
27
- gr.Image(type="pil", label="Upload Image"),
28
- gr.Textbox(value="<ocr>", label="Prompt"),
29
- ],
30
- outputs="text",
31
- title="OCR with Llama-3.2-11B-Vision-Instruct",
32
- description="Upload an image and input a prompt (e.g., '<ocr>') to extract text.",
33
- )
34
 
35
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import MllamaForConditionalGeneration, AutoProcessor, TextIteratorStreamer
 
 
 
2
  from PIL import Image
3
+ import requests
4
+ import torch
5
+ from threading import Thread
6
+ import gradio as gr
7
+ from gradio import FileData
8
+ import time
9
+ import spaces
10
+ ckpt = "meta-llama/Llama-3.2-11B-Vision-Instruct"
11
+ model = MllamaForConditionalGeneration.from_pretrained(ckpt,
12
+ torch_dtype=torch.bfloat16).to("cuda")
13
+ processor = AutoProcessor.from_pretrained(ckpt)
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ @spaces.GPU
17
+ def bot_streaming(message, history, max_new_tokens=250):
18
+
19
+ txt = message["text"]
20
+ ext_buffer = f"{txt}"
21
+
22
+ messages= []
23
+ images = []
24
+
25
+
26
+ for i, msg in enumerate(history):
27
+ if isinstance(msg[0], tuple):
28
+ messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image"}]})
29
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
30
+ images.append(Image.open(msg[0][0]).convert("RGB"))
31
+ elif isinstance(history[i-1], tuple) and isinstance(msg[0], str):
32
+ # messages are already handled
33
+ pass
34
+ elif isinstance(history[i-1][0], str) and isinstance(msg[0], str): # text only turn
35
+ messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
36
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
37
+
38
+ # add current message
39
+ if len(message["files"]) == 1:
40
+
41
+ if isinstance(message["files"][0], str): # examples
42
+ image = Image.open(message["files"][0]).convert("RGB")
43
+ else: # regular input
44
+ image = Image.open(message["files"][0]["path"]).convert("RGB")
45
+ images.append(image)
46
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}, {"type": "image"}]})
47
+ else:
48
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
49
+
50
+
51
+ texts = processor.apply_chat_template(messages, add_generation_prompt=True)
52
+
53
+ if images == []:
54
+ inputs = processor(text=texts, return_tensors="pt").to("cuda")
55
+ else:
56
+ inputs = processor(text=texts, images=images, return_tensors="pt").to("cuda")
57
+ streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
58
+
59
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
60
+ generated_text = ""
61
+
62
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
63
+ thread.start()
64
+ buffer = ""
65
+
66
+ for new_text in streamer:
67
+ buffer += new_text
68
+ generated_text_without_prompt = buffer
69
+ time.sleep(0.01)
70
+ yield buffer
71
+
72
+
73
+ demo = gr.ChatInterface(fn=bot_streaming, title="Multimodal Llama", examples=[
74
+ [{"text": "Which era does this piece belong to? Give details about the era.", "files":["./examples/rococo.jpg"]},
75
+ 200],
76
+ [{"text": "Where do the droughts happen according to this diagram?", "files":["./examples/weather_events.png"]},
77
+ 250],
78
+ [{"text": "What happens when you take out white cat from this chain?", "files":["./examples/ai2d_test.jpg"]},
79
+ 250],
80
+ [{"text": "How long does it take from invoice date to due date? Be short and concise.", "files":["./examples/invoice.png"]},
81
+ 250],
82
+ [{"text": "Where to find this monument? Can you give me other recommendations around the area?", "files":["./examples/wat_arun.jpg"]},
83
+ 250],
84
+ ],
85
+ textbox=gr.MultimodalTextbox(),
86
+ additional_inputs = [gr.Slider(
87
+ minimum=10,
88
+ maximum=500,
89
+ value=250,
90
+ step=10,
91
+ label="Maximum number of new tokens to generate",
92
+ )
93
+ ],
94
+ cache_examples=False,
95
+ description="Try Multimodal Llama by Meta with transformers in this demo. Upload an image, and start chatting about it, or simply try one of the examples below. To learn more about Llama Vision, visit [our blog post](https://huggingface.co/blog/llama32). ",
96
+ stop_btn="Stop Generation",
97
+ fill_height=True,
98
+ multimodal=True)
99
+
100
+ demo.launch(debug=True)