broadfield-dev commited on
Commit
957d93a
Β·
verified Β·
1 Parent(s): 81ba655

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -31
app.py CHANGED
@@ -1,45 +1,97 @@
 
1
  from transformers import AutoProcessor, Gemma3nForConditionalGeneration
2
  from PIL import Image
3
  import requests
4
  import torch
 
5
 
 
6
  model_id = "google/gemma-3n-e4b-it"
7
-
8
- model = Gemma3nForConditionalGeneration.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16,).eval()
9
-
10
  processor = AutoProcessor.from_pretrained(model_id)
11
 
12
- messages = [
13
- {
14
- "role": "system",
15
- "content": [{"type": "text", "text": "You are a helpful assistant."}]
16
- },
17
- {
18
- "role": "user",
19
- "content": [
20
- {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"},
21
- {"type": "text", "text": "Describe this image in detail."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  ]
23
- }
24
- ]
25
 
26
- inputs = processor.apply_chat_template(
27
- messages,
28
- add_generation_prompt=True,
29
- tokenize=True,
30
- return_dict=True,
31
- return_tensors="pt",
32
- ).to(model.device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- input_len = inputs["input_ids"].shape[-1]
 
 
35
 
36
- with torch.inference_mode():
37
- generation = model.generate(**inputs, max_new_tokens=100, do_sample=False)
38
- generation = generation[0][input_len:]
39
 
40
- decoded = processor.decode(generation, skip_special_tokens=True)
41
- print(decoded)
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # **Overall Impression:** The image is a close-up shot of a vibrant garden scene,
44
- # focusing on a cluster of pink cosmos flowers and a busy bumblebee.
45
- # It has a slightly soft, natural feel, likely captured in daylight.
 
1
+ import gradio as gr
2
  from transformers import AutoProcessor, Gemma3nForConditionalGeneration
3
  from PIL import Image
4
  import requests
5
  import torch
6
+ import io
7
 
8
+ # Initialize the model and processor
9
  model_id = "google/gemma-3n-e4b-it"
10
+ model = Gemma3nForConditionalGeneration.from_pretrained(
11
+ model_id, device_map="auto", torch_dtype=torch.bfloat16
12
+ ).eval()
13
  processor = AutoProcessor.from_pretrained(model_id)
14
 
15
+ def process_inputs(image_input, image_url, text_prompt):
16
+ """
17
+ Process image (from file or URL) and text prompt to generate a response using the Gemma model.
18
+
19
+ Args:
20
+ image_input: Uploaded image file
21
+ image_url: URL of an image
22
+ text_prompt: Text input from the user
23
+
24
+ Returns:
25
+ Generated text response from the model
26
+ """
27
+ try:
28
+ # Handle image input: prioritize uploaded image, then URL, then None
29
+ image = None
30
+ if image_input is not None:
31
+ image = Image.open(image_input).convert("RGB")
32
+ elif image_url:
33
+ response = requests.get(image_url, stream=True)
34
+ response.raise_for_status()
35
+ image = Image.open(io.BytesIO(response.content)).convert("RGB")
36
+
37
+ # Prepare messages for the model
38
+ messages = [
39
+ {
40
+ "role": "system",
41
+ "content": [{"type": "text", "text": "You are a helpful assistant."}]
42
+ },
43
+ {
44
+ "role": "user",
45
+ "content": []
46
+ }
47
  ]
 
 
48
 
49
+ # Add image to content if provided
50
+ if image is not None:
51
+ messages[1]["content"].append({"type": "image", "image": image})
52
+
53
+ # Add text prompt if provided
54
+ if text_prompt:
55
+ messages[1]["content"].append({"type": "text", "text": text_prompt})
56
+ else:
57
+ return "Please provide a text prompt."
58
+
59
+ # Process inputs using the processor
60
+ inputs = processor.apply_chat_template(
61
+ messages,
62
+ add_generation_prompt=True,
63
+ tokenize=True,
64
+ return_dict=True,
65
+ return_tensors="pt",
66
+ ).to(model.device)
67
+
68
+ input_len = inputs["input_ids"].shape[-1]
69
+
70
+ # Generate response
71
+ with torch.inference_mode():
72
+ generation = model.generate(**inputs, max_new_tokens=500, do_sample=False)
73
+ generation = generation[0][input_len:]
74
 
75
+ # Decode and return the response
76
+ decoded = processor.decode(generation, skip_special_tokens=True)
77
+ return decoded
78
 
79
+ except Exception as e:
80
+ return f"Error: {str(e)}"
 
81
 
82
+ # Define the Gradio interface
83
+ iface = gr.Interface(
84
+ fn=process_inputs,
85
+ inputs=[
86
+ gr.Image(type="file", label="Upload Image (optional)"),
87
+ gr.Textbox(label="Image URL (optional)", placeholder="Enter image URL"),
88
+ gr.Textbox(label="Text Prompt", placeholder="Enter your prompt here")
89
+ ],
90
+ outputs=gr.Textbox(label="Model Response"),
91
+ title="Gemma-3 Multimodal App",
92
+ description="Upload an image or provide an image URL, and enter a text prompt to interact with the Gemma-3 model. The model can describe images, answer questions about them, or respond to text-only prompts.",
93
+ allow_flagging="never"
94
+ )
95
 
96
+ # Launch the app
97
+ iface.launch()