#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": "", "theme": "" }} ''' 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": "", "theme": "" }} ''' 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": "", "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": "", "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()