Spaces:
Sleeping
Sleeping
File size: 15,525 Bytes
eff43f8 cd5a84c eff43f8 42eda46 eff43f8 42eda46 eff43f8 42eda46 eff43f8 42eda46 eff43f8 42eda46 eff43f8 35c50c7 eff43f8 35c50c7 eff43f8 014f66b 42eda46 eff43f8 42eda46 eff43f8 8d44ee8 eff43f8 8d44ee8 eff43f8 42eda46 eff43f8 42eda46 eff43f8 42eda46 eff43f8 7478e67 eff43f8 42eda46 eff43f8 42eda46 eff43f8 42eda46 eff43f8 014f66b 42eda46 7478e67 42eda46 eff43f8 37a643a eff43f8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
#TODO:
#Add an upload image process which just adds the image, the theme, and the name to the DB
#Add a process image function which takes the image, name, and theme, and returns the evaluation, theme score, and style score, and adds the audio file to the DB along with these new properties
#the idea is that phone users will just add their name/image/theme, and the laptop users will process the image and add the audio file
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
import io
import base64
import requests
import json
from elevenlabs import play, save, VoiceSettings, Voice
from elevenlabs.client import ElevenLabs
import threading
import uuid
import os
from datetime import datetime
#from dotenv import load_dotenv
max_image_entries_to_show = 5
import os
openai_key = os.getenv('OPENAI_KEY')
elevenlabs_key = os.getenv('ELEVENLABS_KEY')
client = ElevenLabs(
api_key=elevenlabs_key
)
voice=Voice(
voice_id='smuMyFzCBUOkSZpsK0Kd', #chad
#voice_id='R9GFzAjWireUSSmUdyhn', #gordon
settings=VoiceSettings(stability=0.71, similarity_boost=0.25, style=0.0, use_speaker_boost=True)
)
current_theme = "Household Objects"
gallery_images = []
def play_audio(audio_url):
play(audio_url)
def playmusic():
"""Function to initiate the thread."""
thread = threading.Thread(target=playmusic_thread, args=())
thread.start()
def submit_photo(name, base64_image, time_stamp, theme):
import requests
# log all values
print(f"Name: {name}")
print(f"Time Stamp: {time_stamp}")
print(f"Theme: {theme}")
url = "http://127.0.0.1:5000/photos"
response = requests.post(url, json={
"name": name,
"image": base64_image,
"time_stamp": time_stamp,
"theme": theme,
})
return response.json()
def submit_photo_with_results(name, base64_image, time_stamp, audio_url, theme, style_score, theme_score, total_score, evaluation):
import requests
# log all values
print(f"Name: {name}")
print(f"Time Stamp: {time_stamp}")
print(f"Audio URL: {audio_url}")
print(f"Theme: {theme}")
print(f"Style Score: {style_score}")
print(f"Theme Score: {theme_score}")
print(f"Total Score: {total_score}")
print(f"Evaluation: {evaluation}")
url = "http://127.0.0.1:5000/photos_with_results"
response = requests.post(url, json={
"name": name,
"image": base64_image,
"time_stamp": time_stamp,
"audio_url": audio_url,
"theme": theme,
"style_score": style_score,
"theme_score": theme_score,
"total_score": total_score,
"evaluation": evaluation
})
return response.json()
def generate_theme():
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai_key}"
}
prompt_text_dumb = f'''
You are the judge of a photography contest where players are given various themes and need to take a photograph inspired, or based on, that theme. Generate a new theme for the contest.
Themes should be household objects you can find indoors. Foods, toiletries, appliances, and furniture are all good examples. But get creative with it.
Also return dialog in the style of a big dumb idiot, explaining the new theme chosen to the audience.
The last theme was {current_theme}.
The json structure to return is
{{
"dialog": "<Dumb Idiot style dialog revealing the theme to the audience.>",
"theme": "<New theme generated>"
}}
'''
prompt_text = f'''
You are the judge of a photography contest where players are given various themes and need to take a photograph inspired, or based on, that theme. Generate a new theme for the contest.
Themes can be figurative or literal, common or unusual. Get creative with it, and always pick the 2nd idea you think of, not the first!
Also return dialog in the style of Gordon Ramsay, explaining the new theme chosen to the audience. This should be just 2 or 3 sentences and should typically be dramatic, borderline offensive, or over the top encouraging - just like Gordon Ramsay does in reality TV shows.
The last theme was {current_theme}.
The json structure to return is
{{
"dialog": "<Gordon Ramsay style dialog revealing the theme to the audience.>",
"theme": "<New theme generated>"
}}
'''
data = {
"model": "gpt-4-turbo",
"response_format": { "type": "json_object" },
"messages": [
{"role": "system", "content": prompt_text},
],
"temperature": 1.0
}
print ("PROMPT TEXT:\n")
print (prompt_text)
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
response_json = response.json()
print(response_json)
output_json = json.loads(response_json['choices'][0]['message']['content'])
try:
theme = output_json['theme']
dialog = output_json['dialog']
# to do - put this into a audio button
#speak(dialog)
print(f"dialog: {dialog}")
print(f"theme: {theme}")
current_theme = theme
return theme
except KeyError as e:
print(f"Key error: {e}")
return "Failed to generate theme."
except json.JSONDecodeError:
print("JSON decoding failed")
return "Invalid response format."
def create_image_with_text(image_data, text):
image = Image.open(io.BytesIO(base64.b64decode(image_data)))
image = image.resize((500, 500)) # Resize for uniformity in the gallery
draw = ImageDraw.Draw(image)
font = ImageFont.load_default() # Use a default font or specify a path to a TTF file
text_position = (10, 450) # Position at the bottom of the image
text_color = "white" # White text for visibility
draw.text(text_position, text, fill=text_color, font=font)
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
return base64.b64encode(buffered.getvalue()).decode('utf-8')
def encode_image(image):
if image.mode != 'RGB':
image = image.convert('RGB')
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
return base64.b64encode(buffered.getvalue()).decode('utf-8')
def process_image(image, name):
global gallery_images
global current_theme
if name == "":
return "Please enter a name."
if image is None:
return "Please upload an image."
print ("PROCESSING IMAGE", name, current_theme, image)
audio_guid = str(uuid.uuid4())
print ("Image: ", image)
#base64_image = encode_image(image)
evaluation, theme_score, style_score = describe_image(image, name, current_theme) # Updated to unpack three values
audio_filepath = gen_tts_and_save_to_path(evaluation, audio_guid)
# put at top of list
gallery_images.insert(0, (image, name, current_theme, theme_score, style_score, evaluation, audio_filepath))
return "Your entry has been judged! Learn how you scored in the Judging Panel."
def describe_image(image_array, name, theme):
base64_image = encode_image(image_array)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {openai_key}"
}
prompt_text = f'''
You are the judge of a photography contest where players are given various themes and need to take a photograph inspired, or based on, that theme. Award 0 to 5 points based on style (overall composition, visual quality) and theme (how well they translate the theme into a visual image. This can be literal or abstract). Also return a text evaluation of their work, in the style of Gordon Ramsay. This should be just 2 or 3 sentences and should typically be dramatic, surprising, or over the top encouraging - just like Gordon Ramsay does in reality TV shows. Players can't see the scores so say them out loud in the evaluation in addition to the json. Note that this is primarily for kids, so be ridiculous but also be a bit generous to keep them engaged.
However in all cases reference details from the image so we know you're actually paying attention.
The theme is {theme}. Here is the photograph submitted by {name}:
The json structure to return is
{{
"evaluation": "<Gordon Ramsey style evaluation feedback here, in the style of a reality TV show.>",
"style_score": 0, //0 to 5 points
"theme_score": 0, //0 to 5 points
}}
'''
prompt_text_dumb = f'''
You are the judge of a photography contest where players are given various themes and need to take a photograph inspired, or based on, that theme. Award 0 to 5 points based on style (overall composition, visual quality) and theme (how well they translate the theme into a visual image. This can be literal or abstract). Also return a text evaluation of their work, in the style of a big dumb idiot. This should be just 2 or 3 sentences in the spirit of a reality tv show, but where the host is a big dumb idiot. Players can't see the scores so say them out loud in the evaluation in addition to the json.
The theme is {theme}. Here is the photograph submitted by {name}:
The json structure to return is
{{
"evaluation": "<Big dumb idiot style evaluation feedback here, in the style of a reality TV show.>",
"style_score": 0, //0 to 5 points
"theme_score": 0, //0 to 5 points
}}
'''
print ("PROMPT TEXT:\n")
print (prompt_text)
payload = {
"model": "gpt-4o",
"response_format": { "type": "json_object" },
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt_text},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
]
}
],
"max_tokens": 600,
"temperature": 1 # Slightly lower temperature to encourage more consistent outputs
}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
response_json = response.json()
print(response_json)
try:
# Assuming the model response is formatted as a JSON string within the content field
output_json = json.loads(response_json['choices'][0]['message']['content'])
evaluation = output_json['evaluation']
theme_score = output_json['theme_score']
style_score = output_json['style_score']
except KeyError as e:
print(f"Key error: {e}")
evaluation = "Failed to retrieve json. Please check the input or try again later."
except json.JSONDecodeError:
print("JSON decoding failed")
evaluation = "Invalid res ponse format."
print (f"EVALUATION: {evaluation}")
print (f"THEME SCORE: {theme_score}")
print (f"STYLE SCORE: {style_score}")
return evaluation, theme_score, style_score
def clear_gallery():
global gallery_images
gallery_images = []
return update_gallery()
def update_gallery():
global gallery_images
gallery_items = []
for i in range(max_image_entries_to_show):
if (i < len(gallery_images)):
print ("loading image: ", i)
(image, name, theme, theme_score, style_score, evaluation, audio_filepath ) = gallery_images[i]
name_output = gr.Textbox(label="Player", interactive=False, value=name, visible=True)
theme_output = gr.Textbox(label="Theme", interactive=False, value=theme, visible=True)
image_output = gr.Image(image, label="Photo", type="pil", visible=True)
description_output = gr.Label(label="Image Description", value =evaluation, visible=True)
audio_filepath = gr.Audio(audio_filepath, visible=True)
score_output = gr.Label(label="Scores", value = theme_score + style_score, visible=True)
else:
name_output = gr.Textbox(label="Player", interactive=False, value="", visible=False)
theme_output = gr.Textbox(label="Theme", interactive=False, value="", visible=False)
image_output = gr.Image(label="Photo", type="pil", visible=False)
description_output = gr.Label(label="Image Description", visible=False)
audio_filepath = gr.Audio(visible=False)
score_output = gr.Label(label="Scores", visible=False)
gallery_items.append(name_output)
gallery_items.append(theme_output)
gallery_items.append(image_output)
gallery_items.append(description_output)
gallery_items.append(audio_filepath)
gallery_items.append(score_output)
return gallery_items
def gen_tts_and_save_to_path(text, filename):
audio = client.generate(
voice=voice,
text=text,
model="eleven_turbo_v2"
)
full_path = "audio/" + filename + ".mp3"
os.makedirs(os.path.dirname(full_path), exist_ok=True)
save(audio, full_path)
return full_path
def set_theme(input):
global current_theme
current_theme = input
print ("changed theme: ", current_theme)
return current_theme
def game_start():
global current_theme
return current_theme
with gr.Blocks() as demo:
with gr.Tab("Photo Submission"):
with gr.Row():
name_input = gr.Textbox(label="Player Name")
theme_reminder = gr.Textbox(current_theme, label="Current Theme")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Image")
judge_button = gr.Button("Judge Image")
process_image_output = gr.Textbox(label="Judging Feedback", interactive=False)
#score_output = gr.Label(label="Scores")
judge_button.click(fn=process_image, inputs=[image_input, name_input], outputs=[process_image_output])
with gr.Tab("Judging Panel"):
with gr.Row():
theme_textbox = gr.Textbox(label="Change Theme", interactive=True, value=current_theme)
generate_theme_button = gr.Button("Generate Theme")
theme_audio = gr.Audio(label="Theme Audio", autoplay=True, visible=False)
generate_theme_button.click(
fn=generate_theme,
inputs=None,
outputs=theme_textbox
)
refresh_button = gr.Button("Refresh Gallery")
gallery_items = update_gallery()
# Use the function and connect outputs properly
refresh_button.click(
fn=update_gallery,
inputs=[],
outputs=gallery_items
)
with gr.Tab("Dev"):
with gr.Column():
clear_button = gr.Button("Clear Gallery")
begin_game_button = gr.Button("Begin Game")
bg_music = gr.Audio(label="Background Music", autoplay=True)
def playmusic():
return "jeopardy.mp3"
begin_game_button.click(playmusic, inputs=None, outputs=bg_music)
clear_button.click(clear_gallery, inputs=[], outputs=gallery_items)
theme_textbox.change(set_theme, inputs=theme_textbox, outputs=theme_reminder)
demo.load(game_start, inputs=None, outputs=[theme_textbox])
demo.load(update_gallery,
inputs=[],
outputs=gallery_items
)
#demo.launch(server_name="0.0.0.0", server_port=7861, share=True, debug=True)
demo.launch()
|