Update app.py
Browse files
app.py
CHANGED
@@ -7,162 +7,153 @@ import scipy.io.wavfile
|
|
7 |
import requests
|
8 |
|
9 |
# Set your API keys
|
10 |
-
|
11 |
-
os.environ
|
12 |
-
os.environ\["GROQ\_API\_KEY"] = "gsk\_XLiu21NA9i1wvJvnhfZFWGdyb3FYCZ6frWmT3eTj4iUz0Vmx5ZmK"
|
13 |
|
14 |
state = {
|
15 |
-
"started": False,
|
16 |
-
"history":
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
"
|
21 |
-
}
|
22 |
-
|
23 |
-
def convert\_audio\_to\_text(audio, lang\_choices):
|
24 |
-
if audio is None:
|
25 |
-
return ""
|
26 |
-
|
27 |
-
```
|
28 |
-
try:
|
29 |
-
sr_rate, audio_data = audio
|
30 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as fp:
|
31 |
-
scipy.io.wavfile.write(fp.name, sr_rate, audio_data)
|
32 |
-
recog = sr.Recognizer()
|
33 |
-
with sr.AudioFile(fp.name) as src:
|
34 |
-
recorded = recog.record(src)
|
35 |
-
lang = "en-US" if "English" in lang_choices else "ur-PK" if "Urdu" in lang_choices else "en-US"
|
36 |
-
return recog.recognize_google(recorded, language=lang).lower()
|
37 |
-
except Exception as e:
|
38 |
-
return f"[Error] Couldn't transcribe: {str(e)}"
|
39 |
-
```
|
40 |
-
|
41 |
-
def query\_llm(api, messages, model=None):
|
42 |
-
headers = {
|
43 |
-
"Authorization": f"Bearer {os.environ\[f'{api}\_API\_KEY']}",
|
44 |
-
"Content-Type": "application/json"
|
45 |
}
|
46 |
-
payload = {
|
47 |
-
"messages": messages,
|
48 |
-
"model": model or ("llama3-70b-8192" if api == "GROQ" else "mistral-medium")
|
49 |
-
}
|
50 |
-
endpoint = {
|
51 |
-
"MISTRAL": "[https://api.mistral.ai/v1/chat/completions](https://api.mistral.ai/v1/chat/completions)",
|
52 |
-
"GROQ": "[https://api.groq.com/openai/v1/chat/completions](https://api.groq.com/openai/v1/chat/completions)"
|
53 |
-
}\[api]
|
54 |
-
|
55 |
-
```
|
56 |
-
response = requests.post(endpoint, headers=headers, json=payload)
|
57 |
-
if response.status_code == 200:
|
58 |
-
return response.json()["choices"][0]["message"]["content"].strip()
|
59 |
-
else:
|
60 |
-
return f"[{api} Error] {response.status_code} - {response.text}"
|
61 |
-
```
|
62 |
-
|
63 |
-
def begin\_game():
|
64 |
-
state\["started"] = True
|
65 |
-
state\["history"] = \[]
|
66 |
-
state\["question\_num"] = 1
|
67 |
-
state\["hint\_mode"] = False
|
68 |
-
state\["final\_answer"] = ""
|
69 |
-
state\["current\_q"] = "Does it belong to the world of living things?"
|
70 |
-
return (
|
71 |
-
f"Question 1: {state\['current\_q']}",
|
72 |
-
"",
|
73 |
-
gr.update(visible=False),
|
74 |
-
gr.update(visible=True),
|
75 |
-
gr.update(visible=False)
|
76 |
-
)
|
77 |
|
78 |
-
def
|
79 |
-
if
|
80 |
-
return "
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
if
|
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 |
-
def
|
130 |
-
|
131 |
-
return (
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
with gr.Blocks(title="Kasoti") as demo:
|
137 |
-
gr.Markdown("## 🧠 Kasoti")
|
138 |
-
gr.Markdown("Think of something. I will try to guess it in 20 yes/no questions. Answer with **yes/no** or **ہاں/نہیں**.")
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
with gr.
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
hint_toggle.click(fn=
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
demo.launch()
|
|
|
7 |
import requests
|
8 |
|
9 |
# Set your API keys
|
10 |
+
os.environ["MISTRAL_API_KEY"] = "R1ISnVkHrj7fSd5Dh6ZSZHqCJhhct0ZR"
|
11 |
+
os.environ["GROQ_API_KEY"] = "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"
|
|
|
12 |
|
13 |
state = {
|
14 |
+
"started": False,
|
15 |
+
"history": [],
|
16 |
+
"current_q": "",
|
17 |
+
"question_num": 0,
|
18 |
+
"hint_mode": False,
|
19 |
+
"final_answer": ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
+
def convert_audio_to_text(audio, lang_choices):
|
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 "English" in lang_choices else "ur-PK" if "Urdu" in lang_choices else "en-US"
|
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 |
+
def query_llm(api, messages, model=None):
|
39 |
+
headers = {
|
40 |
+
"Authorization": f"Bearer {os.environ[f'{api}_API_KEY']}",
|
41 |
+
"Content-Type": "application/json"
|
42 |
+
}
|
43 |
+
payload = {
|
44 |
+
"messages": messages,
|
45 |
+
"model": model or ("llama3-70b-8192" if api == "GROQ" else "mistral-medium")
|
46 |
+
}
|
47 |
+
endpoint = {
|
48 |
+
"MISTRAL": "https://api.mistral.ai/v1/chat/completions",
|
49 |
+
"GROQ": "https://api.groq.com/openai/v1/chat/completions"
|
50 |
+
}[api]
|
51 |
+
|
52 |
+
response = requests.post(endpoint, headers=headers, json=payload)
|
53 |
+
if response.status_code == 200:
|
54 |
+
return response.json()["choices"][0]["message"]["content"].strip()
|
55 |
+
else:
|
56 |
+
return f"[{api} Error] {response.status_code} - {response.text}"
|
57 |
+
|
58 |
+
def begin_game():
|
59 |
+
state["started"] = True
|
60 |
+
state["history"] = []
|
61 |
+
state["question_num"] = 1
|
62 |
+
state["hint_mode"] = False
|
63 |
+
state["final_answer"] = ""
|
64 |
+
state["current_q"] = "Does it belong to the world of living things?"
|
65 |
+
return (
|
66 |
+
f"Question 1: {state['current_q']}",
|
67 |
+
"",
|
68 |
+
gr.update(visible=False),
|
69 |
+
gr.update(visible=True),
|
70 |
+
gr.update(visible=False)
|
71 |
+
)
|
72 |
+
|
73 |
+
def interpret_answer(user_answer):
|
74 |
+
if not state["started"]:
|
75 |
+
return "⛔ Please start a new game.", "", gr.update(visible=False), "", gr.update(visible=False)
|
76 |
+
|
77 |
+
normalized = user_answer.strip().lower()
|
78 |
+
if normalized not in ["yes", "no", "ہاں", "نہیں"]:
|
79 |
+
return "⚠️ Respond with 'yes' or 'no' (or ہاں/نہیں).", user_answer, gr.update(visible=False), "", gr.update(visible=False)
|
80 |
+
|
81 |
+
state["history"].append((state["current_q"], normalized))
|
82 |
+
|
83 |
+
if state["question_num"] >= 20:
|
84 |
+
state["started"] = False
|
85 |
+
guess = generate_final_guess()
|
86 |
+
state["final_answer"] = guess
|
87 |
+
return "Game Over!", user_answer, gr.update(visible=True), "", gr.update(value=guess, visible=True)
|
88 |
+
|
89 |
+
if state["question_num"] % 5 == 0:
|
90 |
+
guess = generate_final_guess()
|
91 |
+
if "i think" in guess.lower() or "maybe" in guess.lower():
|
92 |
+
state["current_q"] = f"{guess} Am I right?"
|
93 |
+
return state["current_q"], user_answer, gr.update(visible=False), "", gr.update(visible=False)
|
94 |
+
|
95 |
+
state["question_num"] += 1
|
96 |
+
state["current_q"] = get_next_question()
|
97 |
+
return f"Question {state['question_num']}: {state['current_q']}", user_answer, gr.update(visible=False), "", gr.update(visible=False)
|
98 |
+
|
99 |
+
def get_next_question():
|
100 |
+
history_prompt = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
101 |
+
prompt = (
|
102 |
+
"You're playing a guessing game. Only respond with a yes/no question, nothing else.\n"
|
103 |
+
"Based on the following history, ask the next smart question:\n\n"
|
104 |
+
f"{history_prompt}\n\n"
|
105 |
+
"Next question only:"
|
106 |
)
|
107 |
+
return query_llm("MISTRAL", [{"role": "user", "content": prompt}])
|
108 |
+
|
109 |
+
def generate_final_guess():
|
110 |
+
history = "\n".join([f"Q: {q}\nA: {a}" for q, a in state["history"]])
|
111 |
+
prompt = f"""Guess the secret concept based on these Q&A. If you're not sure, say "I need more clues."\n\n{history}\n\nYour guess:"""
|
112 |
+
return query_llm("MISTRAL", [{"role": "user", "content": 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 |
+
question = state["current_q"]
|
118 |
+
history = "\n".join([f"{q} - {a}" for q, a in state["history"]])
|
119 |
+
prompt = f"""The player seems confused by this question: "{question}". Previous Q&A were:\n{history}\n\nGive a helpful, simple hint."""
|
120 |
+
return query_llm("MISTRAL", [{"role": "user", "content": prompt}])
|
121 |
+
|
122 |
+
def toggle_hint_mode():
|
123 |
+
state["hint_mode"] = not state["hint_mode"]
|
124 |
+
return (
|
125 |
+
"Hint Mode: ON" if state["hint_mode"] else "Hint Mode: OFF",
|
126 |
+
gr.update(visible=True)
|
127 |
+
)
|
128 |
|
129 |
with gr.Blocks(title="Kasoti") as demo:
|
130 |
+
gr.Markdown("## 🧠 Kasoti")
|
131 |
+
gr.Markdown("Think of something. I will try to guess it in 20 yes/no questions. Answer with **yes/no** or **ہاں/نہیں**.")
|
132 |
+
|
133 |
+
with gr.Row():
|
134 |
+
start = gr.Button("🎲 Start Game", scale=1)
|
135 |
+
hint_toggle = gr.Button("💡 Toggle Hint Mode", scale=1)
|
136 |
+
hint_status = gr.Textbox(value="Hint Mode: OFF", show_label=False, interactive=False)
|
137 |
+
|
138 |
+
with gr.Row():
|
139 |
+
with gr.Column(scale=1):
|
140 |
+
gr.Markdown("### 🎤 Input")
|
141 |
+
lang_sel = gr.CheckboxGroup(["English", "Urdu"], label="Select Language", value=["English"])
|
142 |
+
mic_input = gr.Audio(sources=["microphone"], type="numpy", label="Record Your Answer")
|
143 |
+
transcribe = gr.Button("🎙️ Transcribe")
|
144 |
+
typed_ans = gr.Textbox(label="✍️ Or type your answer")
|
145 |
+
submit = gr.Button("✅ Submit Answer")
|
146 |
+
|
147 |
+
with gr.Column(scale=2):
|
148 |
+
gr.Markdown("### 🎮 Game Status")
|
149 |
+
game_q_box = gr.Textbox(label="🧩 Current Question", interactive=False, lines=2)
|
150 |
+
game_history = gr.Textbox(label="🧾 Hint / Status", interactive=False, lines=2)
|
151 |
+
final_answer_box = gr.Textbox(label="🎯 Final Answer", visible=False, lines=2, interactive=False)
|
152 |
+
|
153 |
+
start.click(fn=begin_game, outputs=[game_q_box, game_history, final_answer_box, submit, final_answer_box])
|
154 |
+
hint_toggle.click(fn=toggle_hint_mode, outputs=[hint_status, game_history])
|
155 |
+
hint_toggle.click(fn=hint_response, outputs=[game_history])
|
156 |
+
transcribe.click(fn=convert_audio_to_text, inputs=[mic_input, lang_sel], outputs=[typed_ans])
|
157 |
+
submit.click(fn=interpret_answer, inputs=[typed_ans], outputs=[game_q_box, typed_ans, final_answer_box, game_history, final_answer_box])
|
158 |
+
|
159 |
+
demo.launch() make UI better pls
|
|
|
|