import gradio as gr
import openai
import random
import os
# Set your OpenAI API key securely using environment variables
openai.api_key = os.getenv("OPENAI_API_KEY")
# Updated list of 5-letter food words
food_words = [
"bread", "donut", "momos", "wraps", "melon",
"vadas", "pasta", "tacos", "pizza", "sushi",
"beans", "candy", "wafer", "spice", "honey"
]
answer = random.choice(food_words).lower()
current_guess = ""
attempts = 0
grid_content = [[{"letter": "", "color": ""} for _ in range(5)] for _ in range(6)]
def generate_grid_html():
"""Generate HTML to render the current state of the grid."""
html_content = ""
for row in grid_content:
row_html = "".join(
f"
{entry['letter'].upper()}
"
for entry in row
)
html_content += f"{row_html}
"
return html_content
def submit_guess():
"""Submit the guess, update the grid, and apply color coding."""
global current_guess, grid_content, attempts, answer
feedback = [{"letter": char, "color": "grey"} for char in current_guess]
answer_copy = list(answer)
# First pass: Check for exact matches (green)
for i, char in enumerate(current_guess):
if char == answer[i]:
feedback[i]["color"] = "green"
answer_copy[i] = None
# Second pass: Check for misplaced matches (yellow)
for i, char in enumerate(current_guess):
if feedback[i]["color"] != "green" and char in answer_copy:
feedback[i]["color"] = "yellow"
answer_copy[answer_copy.index(char)] = None
if attempts < 6:
grid_content[attempts] = feedback
attempts += 1
if current_guess == answer:
return generate_grid_html(), f"🎉 Correct! The word was {answer.upper()}!"
elif attempts == 6:
return generate_grid_html(), f"😢 Game Over! The word was {answer.upper()}."
current_guess = ""
return generate_grid_html(), "Enter your next guess."
def transcribe_audio(audio_file):
"""Use OpenAI Whisper to transcribe audio."""
with open(audio_file, "rb") as f:
transcript = openai.Audio.transcribe("whisper-1", f)
return transcript["text"].strip().lower()
def handle_audio_input(audio_file):
"""Handle the audio input and check the guess."""
global current_guess
spoken_text = transcribe_audio(audio_file)
if len(spoken_text) == 5 and spoken_text.isalpha():
current_guess = spoken_text
return submit_guess()
return generate_grid_html(), "Please say a valid 5-letter word."
def restart_game():
global answer, current_guess, attempts, grid_content
answer = random.choice(food_words).lower()
current_guess = ""
attempts = 0
grid_content = [[{"letter": "", "color": ""} for _ in range(5)] for _ in range(6)]
return generate_grid_html(), "Game restarted. Enter a 5-letter word."
with gr.Blocks(css="""
.grid-row { display: flex; justify-content: center; margin-bottom: 5px; }
.grid-cell { width: 50px; height: 50px; border: 1px solid #ccc; margin: 2px;
display: flex; align-items: center; justify-content: center;
font-size: 20px; font-weight: bold; text-transform: uppercase; }
.green { background-color: lightgreen; }
.yellow { background-color: gold; }
.grey { background-color: lightgrey; }
""") as demo:
gr.Markdown("# 🍲 Foodle: Guess the Food Dish!")
grid_display = gr.HTML(generate_grid_html())
status_display = gr.Textbox("Enter your next guess.", interactive=False)
audio_input = gr.Audio(type="filepath", label="Speak your guess")
audio_input.change(handle_audio_input, inputs=audio_input, outputs=[grid_display, status_display])
gr.Button("Restart Game").click(restart_game, outputs=[grid_display, status_display])
demo.launch()