Update app.py
Browse files
app.py
CHANGED
|
@@ -1,65 +1,155 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
"
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
"hard": [
|
| 19 |
-
"Philosophy begins in wonder and ends in understanding.",
|
| 20 |
-
"The subconscious mind is a powerful force.",
|
| 21 |
-
"Language is the roadmap of a culture."
|
| 22 |
-
]
|
| 23 |
}
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def start_game(difficulty):
|
| 30 |
-
global current_phrase, selected_lang
|
| 31 |
-
current_phrase = random.choice(phrases[difficulty])
|
| 32 |
-
detected = detect(current_phrase)
|
| 33 |
-
selected_lang = random.choice(['es', 'fr', 'de', 'hi', 'ur', 'ar'])
|
| 34 |
-
translated = GoogleTranslator(source='en', target=selected_lang).translate(current_phrase)
|
| 35 |
-
return translated, "Try guessing what this means in English!"
|
| 36 |
-
|
| 37 |
-
def check_guess(user_guess):
|
| 38 |
-
if not current_phrase:
|
| 39 |
-
return "Click 'Start Game' first!"
|
| 40 |
-
if user_guess.strip().lower() == current_phrase.strip().lower():
|
| 41 |
-
return f"✅ Correct! It was: '{current_phrase}'"
|
| 42 |
-
else:
|
| 43 |
-
return f"❌ Incorrect! Try again!"
|
| 44 |
-
|
| 45 |
-
with gr.Blocks() as demo:
|
| 46 |
-
gr.Markdown("## 🌍 Language Guess Game - Remix Edition")
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
with gr.Row():
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
with gr.Row():
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
import speech_recognition as sr
|
| 4 |
+
import numpy as np
|
| 5 |
+
import tempfile
|
| 6 |
+
import scipy.io.wavfile
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
# API key setup
|
| 10 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
|
| 12 |
+
# Game session
|
| 13 |
+
state = {
|
| 14 |
+
"started": False,
|
| 15 |
+
"history": [],
|
| 16 |
+
"current_q": "",
|
| 17 |
+
"question_num": 0,
|
| 18 |
+
"hint_mode": False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
}
|
| 20 |
|
| 21 |
+
# ---- AUDIO ----
|
| 22 |
+
def convert_audio_to_text(audio, lang_choice):
|
| 23 |
+
if audio is None:
|
| 24 |
+
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
try:
|
| 27 |
+
sr_rate, audio_data = audio
|
| 28 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as fp:
|
| 29 |
+
scipy.io.wavfile.write(fp.name, sr_rate, audio_data)
|
| 30 |
+
recog = sr.Recognizer()
|
| 31 |
+
with sr.AudioFile(fp.name) as src:
|
| 32 |
+
recorded = recog.record(src)
|
| 33 |
+
lang = "en-US" if lang_choice == "English" else "ur-PK"
|
| 34 |
+
return recog.recognize_google(recorded, language=lang).lower()
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"[Error] Couldn't transcribe: {str(e)}"
|
| 37 |
+
|
| 38 |
+
# ---- OPENAI CHAT COMPLETION ----
|
| 39 |
+
def ask_openai(prompt):
|
| 40 |
+
headers = {
|
| 41 |
+
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
| 42 |
+
"Content-Type": "application/json"
|
| 43 |
+
}
|
| 44 |
+
data = {
|
| 45 |
+
"model": "gpt-3.5-turbo",
|
| 46 |
+
"messages": [{"role": "user", "content": prompt}]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
|
| 50 |
+
if response.status_code == 200:
|
| 51 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 52 |
+
return "[OpenAI Error]"
|
| 53 |
+
|
| 54 |
+
# ---- GAME FLOW ----
|
| 55 |
+
def begin_game():
|
| 56 |
+
state["started"] = True
|
| 57 |
+
state["history"] = []
|
| 58 |
+
state["question_num"] = 1
|
| 59 |
+
state["hint_mode"] = False
|
| 60 |
+
state["current_q"] = "Does it belong to the world of living things?"
|
| 61 |
+
return (
|
| 62 |
+
"🌸 Let's start! Think of anything — a person, object, or place. I’ll guess in 20 tries!\n\n"
|
| 63 |
+
"Please reply with **yes** or **no**.\n\n"
|
| 64 |
+
f"Question 1: {state['current_q']}",
|
| 65 |
+
gr.update(visible=False),
|
| 66 |
+
gr.update(visible=True)
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def interpret_answer(user_answer):
|
| 70 |
+
if not state["started"]:
|
| 71 |
+
return "⛔ Start a new game first.", "", "", gr.update(visible=False)
|
| 72 |
+
|
| 73 |
+
normalized = user_answer.strip().lower()
|
| 74 |
+
if normalized not in ["yes", "no", "ہاں", "نہیں"]:
|
| 75 |
+
return "Please respond with 'yes' or 'no' (or ہاں/نہیں).", "", user_answer, gr.update(visible=state["hint_mode"])
|
| 76 |
+
|
| 77 |
+
# Record history
|
| 78 |
+
state["history"].append((state["current_q"], normalized))
|
| 79 |
+
|
| 80 |
+
if state["question_num"] >= 20:
|
| 81 |
+
state["started"] = False
|
| 82 |
+
guess = generate_final_guess()
|
| 83 |
+
return f"🎯 That's it! Here's my final guess: {guess}", "", user_answer, gr.update(visible=False)
|
| 84 |
+
|
| 85 |
+
if state["question_num"] % 5 == 0:
|
| 86 |
+
guess = generate_final_guess()
|
| 87 |
+
if "i think" in guess.lower():
|
| 88 |
+
state["current_q"] = f"{guess} Am I right?"
|
| 89 |
+
return f"🤔 {state['current_q']}", "", user_answer, gr.update(visible=state["hint_mode"])
|
| 90 |
+
|
| 91 |
+
# Next question
|
| 92 |
+
state["question_num"] += 1
|
| 93 |
+
state["current_q"] = get_next_question()
|
| 94 |
+
return f"🔎 Question {state['question_num']}: {state['current_q']}", "", user_answer, gr.update(visible=state["hint_mode"])
|
| 95 |
+
|
| 96 |
+
def get_next_question():
|
| 97 |
+
history_prompt = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 98 |
+
prompt = f"""You're playing a guessing game. You can only ask yes/no questions. Based on the following history, ask the next smart question:
|
| 99 |
+
|
| 100 |
+
{history_prompt}
|
| 101 |
+
|
| 102 |
+
Your question:"""
|
| 103 |
+
return ask_openai(prompt).strip()
|
| 104 |
+
|
| 105 |
+
def generate_final_guess():
|
| 106 |
+
history = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 107 |
+
prompt = f"""Guess the secret concept based on these Q&A. If you're not sure, say "I need more clues."
|
| 108 |
+
|
| 109 |
+
{history}
|
| 110 |
+
|
| 111 |
+
Your guess:"""
|
| 112 |
+
return ask_openai(prompt)
|
| 113 |
+
|
| 114 |
+
def hint_response():
|
| 115 |
+
if not state["hint_mode"] or not state["started"]:
|
| 116 |
+
return "Hint mode is off or game not active."
|
| 117 |
+
|
| 118 |
+
question = state["current_q"]
|
| 119 |
+
history = "\n".join([f"{q} - {a}" for q, a in state["history"]])
|
| 120 |
+
prompt = f"""The player seems confused by this question: "{question}". Previous Q&A were:\n{history}\n\nGive a helpful, simple hint."""
|
| 121 |
+
return ask_openai(prompt)
|
| 122 |
+
|
| 123 |
+
def toggle_hint_mode():
|
| 124 |
+
state["hint_mode"] = not state["hint_mode"]
|
| 125 |
+
return ("Hint Mode: ON" if state["hint_mode"] else "Hint Mode: OFF"), gr.update(visible=state["hint_mode"])
|
| 126 |
+
|
| 127 |
+
# ---- UI ----
|
| 128 |
+
with gr.Blocks(title="KasotiX - Original Edition") as demo:
|
| 129 |
+
gr.Markdown("<h1 style='text-align: center;'>🌼 KasotiX Game 🌼</h1>")
|
| 130 |
+
gr.Markdown("<p style='text-align: center;'>Can I guess what you're thinking in 20 tries? Think of something and let’s go!</p>")
|
| 131 |
|
| 132 |
with gr.Row():
|
| 133 |
+
start = gr.Button("Start Game 🎲")
|
| 134 |
+
hint_toggle = gr.Button("Toggle Hint Mode 💡")
|
| 135 |
+
hint_status = gr.Textbox(value="Hint Mode: OFF", interactive=False, show_label=False)
|
| 136 |
|
| 137 |
with gr.Row():
|
| 138 |
+
with gr.Column():
|
| 139 |
+
lang_sel = gr.Dropdown(["English", "Urdu"], label="Language", value="English")
|
| 140 |
+
mic_input = gr.Audio(sources=["microphone"], type="numpy")
|
| 141 |
+
transcribe = gr.Button("Transcribe 🎤")
|
| 142 |
+
typed_ans = gr.Textbox(label="Answer (or paste transcription here)")
|
| 143 |
+
submit = gr.Button("Submit Answer ✅")
|
| 144 |
|
| 145 |
+
with gr.Column():
|
| 146 |
+
game_text = gr.Textbox(label="Game Status", lines=8, interactive=False)
|
| 147 |
+
hint_box = gr.Textbox(label="Hint", visible=False)
|
| 148 |
|
| 149 |
+
start.click(fn=begin_game, outputs=[game_text, hint_box, submit])
|
| 150 |
+
hint_toggle.click(fn=toggle_hint_mode, outputs=[hint_status, hint_box])
|
| 151 |
+
hint_toggle.click(fn=hint_response, outputs=[hint_box])
|
| 152 |
+
transcribe.click(fn=convert_audio_to_text, inputs=[mic_input, lang_sel], outputs=[typed_ans])
|
| 153 |
+
submit.click(fn=interpret_answer, inputs=[typed_ans], outputs=[game_text, typed_ans, typed_ans, hint_box])
|
| 154 |
|
| 155 |
demo.launch()
|