Update app.py
Browse files
app.py
CHANGED
@@ -1,163 +1,162 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import os
|
3 |
-
|
4 |
-
import
|
5 |
-
from
|
6 |
-
from
|
7 |
-
from
|
8 |
-
from
|
9 |
-
|
10 |
-
import
|
11 |
-
import
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
ds =
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
buffered =
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
"
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
"
|
60 |
-
|
61 |
-
|
62 |
-
"
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
"
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
c
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
conn.
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
buffered =
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
c
|
123 |
-
|
124 |
-
|
125 |
-
conn.
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
gr.Markdown("
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
# Launch the interface
|
163 |
iface.launch(share=True)
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import base64
|
4 |
+
from io import BytesIO
|
5 |
+
from mistralai import Mistral
|
6 |
+
from pydantic import BaseModel, Field
|
7 |
+
from datasets import load_dataset
|
8 |
+
from PIL import Image
|
9 |
+
import json
|
10 |
+
import sqlite3
|
11 |
+
from datetime import datetime
|
12 |
+
|
13 |
+
# Load the dataset
|
14 |
+
ds = load_dataset("svjack/pokemon-blip-captions-en-zh")
|
15 |
+
ds = ds["train"]
|
16 |
+
|
17 |
+
# Load environment variables
|
18 |
+
api_key = os.environ.get('MISTRAL_API_KEY')
|
19 |
+
|
20 |
+
if not api_key:
|
21 |
+
raise ValueError("MISTRAL_API_KEY is not set in the environment variables.")
|
22 |
+
|
23 |
+
# Create sample history
|
24 |
+
hist = [str({"en": ds[i]["en_text"], "zh": ds[i]["zh_text"]}) for i in range(8)]
|
25 |
+
hist_str = "\n".join(hist)
|
26 |
+
|
27 |
+
# Define the Caption model
|
28 |
+
class Caption(BaseModel):
|
29 |
+
en: str = Field(...,
|
30 |
+
description="English caption of image",
|
31 |
+
max_length=84)
|
32 |
+
zh: str = Field(...,
|
33 |
+
description="Chinese caption of image",
|
34 |
+
max_length=64)
|
35 |
+
|
36 |
+
# Initialize the Mistral client
|
37 |
+
client = Mistral(api_key=api_key)
|
38 |
+
|
39 |
+
def generate_caption(image):
|
40 |
+
# Convert image to base64
|
41 |
+
buffered = BytesIO()
|
42 |
+
image.save(buffered, format="JPEG")
|
43 |
+
base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
44 |
+
|
45 |
+
messages = [
|
46 |
+
{
|
47 |
+
"role": "system",
|
48 |
+
"content": f'''
|
49 |
+
You are a highly accurate image to caption transformer.
|
50 |
+
Describe the image content in English and Chinese respectively. Make sure to FOCUS on item CATEGORY and COLOR!
|
51 |
+
Do NOT provide NAMES! KEEP it SHORT!
|
52 |
+
While adhering to the following JSON schema: {Caption.model_json_schema()}
|
53 |
+
Following are some samples you should adhere to for style and tone:
|
54 |
+
{hist_str}
|
55 |
+
'''
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"role": "user",
|
59 |
+
"content": [
|
60 |
+
{
|
61 |
+
"type": "text",
|
62 |
+
"text": "Describe the image in English and Chinese"
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"type": "image_url",
|
66 |
+
"image_url": f"data:image/jpeg;base64,{base64_image}"
|
67 |
+
}
|
68 |
+
]
|
69 |
+
}
|
70 |
+
]
|
71 |
+
|
72 |
+
chat_response = client.chat.complete(
|
73 |
+
model="pixtral-12b-2409",
|
74 |
+
messages=messages,
|
75 |
+
response_format = {
|
76 |
+
"type": "json_object",
|
77 |
+
}
|
78 |
+
)
|
79 |
+
|
80 |
+
response_content = chat_response.choices[0].message.content
|
81 |
+
|
82 |
+
try:
|
83 |
+
caption_dict = json.loads(response_content)
|
84 |
+
return Caption(**caption_dict)
|
85 |
+
except json.JSONDecodeError as e:
|
86 |
+
print(f"Error decoding JSON: {e}")
|
87 |
+
return None
|
88 |
+
|
89 |
+
# Initialize SQLite database
|
90 |
+
def init_db():
|
91 |
+
conn = sqlite3.connect('feedback.db')
|
92 |
+
c = conn.cursor()
|
93 |
+
c.execute('''CREATE TABLE IF NOT EXISTS thumbs_up
|
94 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
95 |
+
timestamp TEXT,
|
96 |
+
input_data TEXT,
|
97 |
+
output_data TEXT)''')
|
98 |
+
conn.commit()
|
99 |
+
conn.close()
|
100 |
+
|
101 |
+
init_db()
|
102 |
+
|
103 |
+
def process_image(image):
|
104 |
+
if image is None:
|
105 |
+
return "Please upload an image first."
|
106 |
+
|
107 |
+
result = generate_caption(image)
|
108 |
+
|
109 |
+
if result:
|
110 |
+
return f"English caption: {result.en}\nChinese caption: {result.zh}"
|
111 |
+
else:
|
112 |
+
return "Failed to generate caption. Please check the API call or network connectivity."
|
113 |
+
|
114 |
+
def thumbs_up(image, caption):
|
115 |
+
# Convert image to base64 string for storage
|
116 |
+
buffered = BytesIO()
|
117 |
+
image.save(buffered, format="JPEG")
|
118 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
119 |
+
|
120 |
+
conn = sqlite3.connect('feedback.db')
|
121 |
+
c = conn.cursor()
|
122 |
+
c.execute("INSERT INTO thumbs_up (timestamp, input_data, output_data) VALUES (?, ?, ?)",
|
123 |
+
(datetime.now().isoformat(), img_str, caption))
|
124 |
+
conn.commit()
|
125 |
+
conn.close()
|
126 |
+
print(f"Thumbs up data saved to database.")
|
127 |
+
return gr.Notification("Thank you for your feedback!", type="success")
|
128 |
+
|
129 |
+
# Create Gradio interface
|
130 |
+
custom_css = """
|
131 |
+
.highlight-btn {
|
132 |
+
background-color: #3498db !important;
|
133 |
+
border-color: #3498db !important;
|
134 |
+
color: white !important;
|
135 |
+
}
|
136 |
+
.highlight-btn:hover {
|
137 |
+
background-color: #2980b9 !important;
|
138 |
+
border-color: #2980b9 !important;
|
139 |
+
}
|
140 |
+
"""
|
141 |
+
|
142 |
+
with gr.Blocks() as iface:
|
143 |
+
gr.Markdown("# Image Captioner")
|
144 |
+
gr.Markdown("Upload an image to generate captions in English and Chinese. Use the 'Thumbs Up' button if you like the result!")
|
145 |
+
|
146 |
+
with gr.Row():
|
147 |
+
with gr.Column(scale=1):
|
148 |
+
input_image = gr.Image(type="pil")
|
149 |
+
with gr.Row():
|
150 |
+
clear_btn = gr.Button("Clear")
|
151 |
+
submit_btn = gr.Button("Submit", elem_classes=["highlight-btn"])
|
152 |
+
|
153 |
+
with gr.Column(scale=1):
|
154 |
+
output_text = gr.Textbox()
|
155 |
+
thumbs_up_btn = gr.Button("Thumbs Up")
|
156 |
+
|
157 |
+
clear_btn.click(fn=lambda: None, inputs=None, outputs=input_image)
|
158 |
+
submit_btn.click(fn=process_image, inputs=input_image, outputs=output_text)
|
159 |
+
thumbs_up_btn.click(fn=thumbs_up, inputs=[input_image, output_text], outputs=None)
|
160 |
+
|
161 |
+
# Launch the interface
|
|
|
162 |
iface.launch(share=True)
|