Didier commited on
Commit
7c8d2d3
·
1 Parent(s): fa3c0d0

Initial commit

Browse files
16-park-ave-milton-park-1024x683.jpg ADDED
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File: app.py
3
+
4
+ Description: Visual question answering (with pixtral-12b-2409)
5
+
6
+ Author: Didier Guillevic
7
+ Date: 2024-09-29
8
+ """
9
+ import logging
10
+ logger = logging.getLogger(__name__)
11
+
12
+ import gradio as gr
13
+ import PIL
14
+ import base64
15
+ from io import BytesIO
16
+
17
+ import os
18
+ from mistralai import Mistral
19
+
20
+ #
21
+ # Mistral AI client
22
+ #
23
+ api_key = os.environ["MISTRAL_API_KEY"]
24
+ client = Mistral(api_key=api_key)
25
+ model_id = "pixtral-12b-2409"
26
+
27
+ #
28
+ # Utils
29
+ #
30
+ def image_to_base64(filepath):
31
+ file_format = filepath.split('.')[-1].lower()
32
+ with open(filepath, "rb") as image_file:
33
+ base64_string = base64.b64encode(image_file.read()).decode('utf-8')
34
+ return base64_string, file_format
35
+
36
+ def pil_to_base64(pil_image, image_format='jpeg'): # Default to 'png' if format not known
37
+ # Save the PIL image to a BytesIO object in the specified format
38
+ buffered = BytesIO()
39
+ pil_image.save(buffered, format=image_format)
40
+
41
+ # Convert the image to a base64 string
42
+ base64_string = base64.b64encode(buffered.getvalue()).decode('utf-8')
43
+
44
+ return base64_string, image_format
45
+
46
+
47
+ #
48
+ # Generate a response
49
+ #
50
+ def answer_question(text, image, temperature=0.0, max_tokens=1_024):
51
+ # Convert image to base64 string
52
+ #base64_string, file_format = image_to_base64(image)
53
+ base64_string, file_format = pil_to_base64(image)
54
+
55
+ messages = [
56
+ {
57
+ "role": "user",
58
+ "content": [
59
+ {
60
+ "type": "text",
61
+ "text": text
62
+ },
63
+ {
64
+ "type": "image_url",
65
+ "image_url": f"data:image/{file_format};base64,{base64_string}"
66
+ }
67
+ ]
68
+ }
69
+ ]
70
+
71
+ chat_response = client.chat.complete(
72
+ model=model_id,
73
+ messages=messages,
74
+ temperature=temperature,
75
+ max_tokens=max_tokens
76
+ )
77
+
78
+ return chat_response.choices[0].message.content
79
+
80
+
81
+ def clear_all():
82
+ # Clear question, image, output_text
83
+ return ('', None, '')
84
+
85
+
86
+ #
87
+ # User interface
88
+ #
89
+ with gr.Blocks() as demo:
90
+
91
+ gr.Markdown("""
92
+ ## Visual question answering / image captioning
93
+ """)
94
+ with gr.Row():
95
+ with gr.Column():
96
+ question = gr.Textbox(
97
+ placeholder="Ask anything about the image..",
98
+ lines=2,
99
+ render=True)
100
+ image = gr.Image(type="pil") # return type: 'numpy', 'pil', 'filepath'
101
+ with gr.Row():
102
+ temperature = gr.Slider(
103
+ label="Temperature",
104
+ minimum=0.0,
105
+ maximum=1.0,
106
+ value=0.0,
107
+ step=0.1
108
+ )
109
+ max_tokens = gr.Slider(
110
+ label="Max tokens",
111
+ minimum=128,
112
+ maximum=2_048,
113
+ value=1_024,
114
+ step=128
115
+ )
116
+ with gr.Column():
117
+ output_text = gr.Textbox(
118
+ lines=10,
119
+ label="Pixtral 12B",
120
+ render=True
121
+ )
122
+ with gr.Row():
123
+ clear_btn = gr.Button("Clear", variant="secondary")
124
+ submit_btn = gr.Button(value="Submit", variant="primary")
125
+
126
+ # Examples
127
+ examples = gr.Examples(
128
+ [
129
+ [
130
+ 'Can you describe this image?', './sample_ID.jpeg'
131
+ ],
132
+ [
133
+ 'In which city and country was this picture taken?',
134
+ './16-park-ave-milton-park-1024x683.jpg'
135
+ ],
136
+ [ (
137
+ 'Please extract the identification information present in the image. '
138
+ 'Format the response in a JSON format such as "{name_of_element : [value]}".'
139
+ ),
140
+ './driver_license.png'
141
+ ],
142
+ ],
143
+ inputs=[question, image],
144
+ outputs=[output_text,],
145
+ fn=answer_question,
146
+ cache_examples=False,
147
+ label="Examples"
148
+ )
149
+
150
+ # Click actions
151
+ clear_btn.click(
152
+ clear_all,
153
+ inputs=[],
154
+ outputs=[question, image, output_text]
155
+ )
156
+ submit_btn.click(
157
+ fn=answer_question,
158
+ inputs=[question, image, temperature, max_tokens],
159
+ outputs=[output_text,]
160
+ )
161
+
162
+ # Documentation
163
+ with gr.Accordion("Documentation", open=False):
164
+ gr.Markdown("""
165
+ - model: Serving pixtral-12b (https://mistral.ai/news/pixtral-12b/)
166
+ - temperature: 0.0=little variable in output, 1.0=lots of variability in output
167
+ - max_tokens: maximum number of tokens to generate as output (1 word approx 1.5 tokens)
168
+ """)
169
+
170
+ demo.launch()
driver_license.png ADDED
sample_ID.jpeg ADDED