Update app.py
Browse files
app.py
CHANGED
|
@@ -6,8 +6,10 @@ import tempfile
|
|
| 6 |
import scipy.io.wavfile
|
| 7 |
import requests
|
| 8 |
|
| 9 |
-
|
|
|
|
| 10 |
|
|
|
|
| 11 |
state = {
|
| 12 |
"started": False,
|
| 13 |
"history": [],
|
|
@@ -16,6 +18,7 @@ state = {
|
|
| 16 |
"hint_mode": False
|
| 17 |
}
|
| 18 |
|
|
|
|
| 19 |
def convert_audio_to_text(audio, lang_choice):
|
| 20 |
if audio is None:
|
| 21 |
return ""
|
|
@@ -32,6 +35,7 @@ def convert_audio_to_text(audio, lang_choice):
|
|
| 32 |
except Exception as e:
|
| 33 |
return f"[Error] Couldn't transcribe: {str(e)}"
|
| 34 |
|
|
|
|
| 35 |
def ask_openai(prompt):
|
| 36 |
headers = {
|
| 37 |
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
|
@@ -41,12 +45,12 @@ def ask_openai(prompt):
|
|
| 41 |
"model": "gpt-3.5-turbo",
|
| 42 |
"messages": [{"role": "user", "content": prompt}]
|
| 43 |
}
|
| 44 |
-
|
| 45 |
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
|
| 46 |
if response.status_code == 200:
|
| 47 |
return response.json()["choices"][0]["message"]["content"]
|
| 48 |
return "[OpenAI Error]"
|
| 49 |
|
|
|
|
| 50 |
def begin_game():
|
| 51 |
state["started"] = True
|
| 52 |
state["history"] = []
|
|
@@ -54,19 +58,18 @@ def begin_game():
|
|
| 54 |
state["hint_mode"] = False
|
| 55 |
state["current_q"] = "Does it belong to the world of living things?"
|
| 56 |
return (
|
| 57 |
-
"
|
| 58 |
-
f"Question 1: {state['current_q']}",
|
| 59 |
gr.update(visible=False),
|
| 60 |
gr.update(visible=True)
|
| 61 |
)
|
| 62 |
|
| 63 |
def interpret_answer(user_answer):
|
| 64 |
if not state["started"]:
|
| 65 |
-
return "⛔
|
| 66 |
|
| 67 |
normalized = user_answer.strip().lower()
|
| 68 |
if normalized not in ["yes", "no", "ہاں", "نہیں"]:
|
| 69 |
-
return "
|
| 70 |
|
| 71 |
state["history"].append((state["current_q"], normalized))
|
| 72 |
|
|
@@ -83,24 +86,16 @@ def interpret_answer(user_answer):
|
|
| 83 |
|
| 84 |
state["question_num"] += 1
|
| 85 |
state["current_q"] = get_next_question()
|
| 86 |
-
return f"
|
| 87 |
|
| 88 |
def get_next_question():
|
| 89 |
history_prompt = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 90 |
-
prompt = f"
|
| 91 |
-
|
| 92 |
-
{history_prompt}
|
| 93 |
-
|
| 94 |
-
Your question:"""
|
| 95 |
return ask_openai(prompt).strip()
|
| 96 |
|
| 97 |
def generate_final_guess():
|
| 98 |
history = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 99 |
-
prompt = f"
|
| 100 |
-
|
| 101 |
-
{history}
|
| 102 |
-
|
| 103 |
-
Your guess:"""
|
| 104 |
return ask_openai(prompt)
|
| 105 |
|
| 106 |
def hint_response():
|
|
@@ -108,35 +103,42 @@ def hint_response():
|
|
| 108 |
return "Hint mode is off or game not active."
|
| 109 |
question = state["current_q"]
|
| 110 |
history = "\n".join([f"{q} - {a}" for q, a in state["history"]])
|
| 111 |
-
prompt = f"
|
| 112 |
return ask_openai(prompt)
|
| 113 |
|
| 114 |
def toggle_hint_mode():
|
| 115 |
state["hint_mode"] = not state["hint_mode"]
|
| 116 |
return ("Hint Mode: ON" if state["hint_mode"] else "Hint Mode: OFF"), gr.update(visible=state["hint_mode"])
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
gr.
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
gr.
|
| 130 |
-
lang_sel = gr.Dropdown(["English", "Urdu"], label="Select Language", value="English")
|
| 131 |
-
mic_input = gr.Audio(sources=["microphone"], type="numpy", label="Record Your Answer")
|
| 132 |
-
transcribe = gr.Button("🎙️ Transcribe")
|
| 133 |
-
typed_ans = gr.Textbox(label="✍️ Or type your answer here")
|
| 134 |
submit = gr.Button("✅ Submit Answer")
|
| 135 |
|
| 136 |
-
with gr.
|
| 137 |
-
gr.
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
start.click(fn=begin_game, outputs=[game_text, hint_box, submit])
|
| 142 |
hint_toggle.click(fn=toggle_hint_mode, outputs=[hint_status, hint_box])
|
|
@@ -144,4 +146,5 @@ with gr.Blocks(title="Kasoti") as demo:
|
|
| 144 |
transcribe.click(fn=convert_audio_to_text, inputs=[mic_input, lang_sel], outputs=[typed_ans])
|
| 145 |
submit.click(fn=interpret_answer, inputs=[typed_ans], outputs=[game_text, typed_ans, typed_ans, hint_box])
|
| 146 |
|
| 147 |
-
|
|
|
|
|
|
| 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 state
|
| 13 |
state = {
|
| 14 |
"started": False,
|
| 15 |
"history": [],
|
|
|
|
| 18 |
"hint_mode": False
|
| 19 |
}
|
| 20 |
|
| 21 |
+
# ---- AUDIO TRANSCRIPTION ----
|
| 22 |
def convert_audio_to_text(audio, lang_choice):
|
| 23 |
if audio is None:
|
| 24 |
return ""
|
|
|
|
| 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}",
|
|
|
|
| 45 |
"model": "gpt-3.5-turbo",
|
| 46 |
"messages": [{"role": "user", "content": prompt}]
|
| 47 |
}
|
|
|
|
| 48 |
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
|
| 49 |
if response.status_code == 200:
|
| 50 |
return response.json()["choices"][0]["message"]["content"]
|
| 51 |
return "[OpenAI Error]"
|
| 52 |
|
| 53 |
+
# ---- GAME LOGIC ----
|
| 54 |
def begin_game():
|
| 55 |
state["started"] = True
|
| 56 |
state["history"] = []
|
|
|
|
| 58 |
state["hint_mode"] = False
|
| 59 |
state["current_q"] = "Does it belong to the world of living things?"
|
| 60 |
return (
|
| 61 |
+
"🌸 Let's start! Think of anything — a person, object, or place. I’ll guess in 20 tries!\n\nPlease reply with yes/no.",
|
|
|
|
| 62 |
gr.update(visible=False),
|
| 63 |
gr.update(visible=True)
|
| 64 |
)
|
| 65 |
|
| 66 |
def interpret_answer(user_answer):
|
| 67 |
if not state["started"]:
|
| 68 |
+
return "⛔ Start a new game first.", "", "", gr.update(visible=False)
|
| 69 |
|
| 70 |
normalized = user_answer.strip().lower()
|
| 71 |
if normalized not in ["yes", "no", "ہاں", "نہیں"]:
|
| 72 |
+
return "Please respond with 'yes' or 'no' (or ہاں/نہیں).", "", user_answer, gr.update(visible=state["hint_mode"])
|
| 73 |
|
| 74 |
state["history"].append((state["current_q"], normalized))
|
| 75 |
|
|
|
|
| 86 |
|
| 87 |
state["question_num"] += 1
|
| 88 |
state["current_q"] = get_next_question()
|
| 89 |
+
return f"🔎 Q{state['question_num']}: {state['current_q']}", "", user_answer, gr.update(visible=state["hint_mode"])
|
| 90 |
|
| 91 |
def get_next_question():
|
| 92 |
history_prompt = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 93 |
+
prompt = f"You're playing a guessing game. Only ask yes/no questions.\n\n{history_prompt}\n\nNext question:"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return ask_openai(prompt).strip()
|
| 95 |
|
| 96 |
def generate_final_guess():
|
| 97 |
history = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
| 98 |
+
prompt = f"Guess the secret concept from this history. If unsure, say 'I need more clues.'\n\n{history}\n\nYour guess:"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return ask_openai(prompt)
|
| 100 |
|
| 101 |
def hint_response():
|
|
|
|
| 103 |
return "Hint mode is off or game not active."
|
| 104 |
question = state["current_q"]
|
| 105 |
history = "\n".join([f"{q} - {a}" for q, a in state["history"]])
|
| 106 |
+
prompt = f"Player is confused by: '{question}'. History:\n{history}\n\nGive a hint."
|
| 107 |
return ask_openai(prompt)
|
| 108 |
|
| 109 |
def toggle_hint_mode():
|
| 110 |
state["hint_mode"] = not state["hint_mode"]
|
| 111 |
return ("Hint Mode: ON" if state["hint_mode"] else "Hint Mode: OFF"), gr.update(visible=state["hint_mode"])
|
| 112 |
|
| 113 |
+
# ---- UI LAYOUT ----
|
| 114 |
+
with gr.Blocks(title="KasotiX - Revamped Edition") as demo:
|
| 115 |
+
with gr.Tab("🎮 Game"):
|
| 116 |
+
gr.Markdown("### 🌼 KasotiX - Can I guess in 20 tries?")
|
| 117 |
+
|
| 118 |
+
with gr.Row():
|
| 119 |
+
lang_sel = gr.Dropdown(["English", "Urdu"], label="Language")
|
| 120 |
+
mic_input = gr.Audio(sources=["microphone"], type="numpy", label="🎤 Record Answer")
|
| 121 |
+
|
| 122 |
+
with gr.Row():
|
| 123 |
+
transcribe = gr.Button("📄 Transcribe")
|
| 124 |
+
typed_ans = gr.Textbox(label="🧠 Your Answer")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
submit = gr.Button("✅ Submit Answer")
|
| 126 |
|
| 127 |
+
with gr.Row():
|
| 128 |
+
start = gr.Button("🔄 Start New Game")
|
| 129 |
+
hint_toggle = gr.Button("💡 Toggle Hint Mode")
|
| 130 |
+
|
| 131 |
+
with gr.Accordion("📊 Game Status", open=True):
|
| 132 |
+
game_text = gr.Textbox(label="Current Status", lines=4, interactive=False)
|
| 133 |
+
hint_status = gr.Textbox(value="Hint Mode: OFF", interactive=False, show_label=False)
|
| 134 |
+
|
| 135 |
+
hint_box = gr.Textbox(label="💡 Hint", visible=False)
|
| 136 |
+
|
| 137 |
+
with gr.Tab("🔧 Settings"):
|
| 138 |
+
gr.Markdown("Settings will be added here soon.")
|
| 139 |
+
|
| 140 |
+
with gr.Tab("📋 History"):
|
| 141 |
+
gr.Markdown("Past questions and answers will appear here soon.")
|
| 142 |
|
| 143 |
start.click(fn=begin_game, outputs=[game_text, hint_box, submit])
|
| 144 |
hint_toggle.click(fn=toggle_hint_mode, outputs=[hint_status, hint_box])
|
|
|
|
| 146 |
transcribe.click(fn=convert_audio_to_text, inputs=[mic_input, lang_sel], outputs=[typed_ans])
|
| 147 |
submit.click(fn=interpret_answer, inputs=[typed_ans], outputs=[game_text, typed_ans, typed_ans, hint_box])
|
| 148 |
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
demo.launch()
|