Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +106 -81
src/streamlit_app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import speech_recognition as sr
|
| 3 |
import tempfile
|
|
@@ -6,13 +8,13 @@ import os
|
|
| 6 |
import requests
|
| 7 |
import numpy as np
|
| 8 |
|
| 9 |
-
# API Keys
|
| 10 |
os.environ["MISTRAL_API_KEY"] = "cNjUx79Hl0A2AeiAMf6yi7o7ah4APoZy"
|
| 11 |
os.environ["GROQ_API_KEY"] = "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"
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
if "
|
| 15 |
-
st.session_state.
|
| 16 |
"active": False,
|
| 17 |
"questions_asked": 0,
|
| 18 |
"answers": [],
|
|
@@ -20,22 +22,20 @@ if "state" not in st.session_state:
|
|
| 20 |
"consult_mode": False
|
| 21 |
}
|
| 22 |
|
| 23 |
-
|
| 24 |
-
def transcribe_audio(uploaded_file, language):
|
| 25 |
-
if uploaded_file is None:
|
| 26 |
-
return ""
|
| 27 |
try:
|
| 28 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as
|
| 29 |
-
|
| 30 |
-
|
| 31 |
|
| 32 |
recognizer = sr.Recognizer()
|
| 33 |
-
with sr.AudioFile(
|
| 34 |
audio = recognizer.record(source)
|
| 35 |
lang_code = "en-US" if language == "English" else "ur-PK"
|
| 36 |
-
|
|
|
|
| 37 |
except Exception as e:
|
| 38 |
-
return f"Transcription
|
| 39 |
|
| 40 |
def query_llm(api, messages, model=None):
|
| 41 |
headers = {
|
|
@@ -46,90 +46,115 @@ def query_llm(api, messages, model=None):
|
|
| 46 |
"messages": messages,
|
| 47 |
"model": model or ("llama3-70b-8192" if api == "GROQ" else "mistral-medium")
|
| 48 |
}
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
return "API Error"
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
return "yes" if ans in ["yes", "y", "ہاں", "haan"] else "no" if ans in ["no", "n", "نہیں", "nahi"] else None
|
| 58 |
|
| 59 |
def generate_question(answers):
|
| 60 |
-
prompt = "You are playing Kasoti.
|
| 61 |
for i, (q, a) in enumerate(answers, 1):
|
| 62 |
prompt += f"{i}. Q: {q}\n A: {a}\n"
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
def make_guess(answers):
|
| 66 |
-
prompt = "Based on this history, make a
|
| 67 |
for i, (q, a) in enumerate(answers, 1):
|
| 68 |
prompt += f"{i}. Q: {q}\n A: {a}\n"
|
| 69 |
-
return query_llm("GROQ", [{"role": "user", "content": prompt}])
|
| 70 |
|
| 71 |
def get_hint(question, answers):
|
| 72 |
-
prompt = f"The player is unsure about: {question}
|
| 73 |
for q, a in answers:
|
| 74 |
prompt += f"- Q: {q}\n A: {a}\n"
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
st.info("Think of a famous person, place, or object. Answer with **yes/no** or **ہاں/نہیں** only.")
|
| 82 |
|
| 83 |
-
|
| 84 |
-
st.session_state.
|
| 85 |
"active": True,
|
| 86 |
"questions_asked": 1,
|
| 87 |
"answers": [],
|
| 88 |
-
"current_question": "Is it a living thing?"
|
| 89 |
-
"consult_mode": False
|
| 90 |
})
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
else:
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
import streamlit as st
|
| 4 |
import speech_recognition as sr
|
| 5 |
import tempfile
|
|
|
|
| 8 |
import requests
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
+
# Set API Keys
|
| 12 |
os.environ["MISTRAL_API_KEY"] = "cNjUx79Hl0A2AeiAMf6yi7o7ah4APoZy"
|
| 13 |
os.environ["GROQ_API_KEY"] = "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"
|
| 14 |
|
| 15 |
+
# Initialize session state
|
| 16 |
+
if "game_state" not in st.session_state:
|
| 17 |
+
st.session_state.game_state = {
|
| 18 |
"active": False,
|
| 19 |
"questions_asked": 0,
|
| 20 |
"answers": [],
|
|
|
|
| 22 |
"consult_mode": False
|
| 23 |
}
|
| 24 |
|
| 25 |
+
def transcribe_audio(audio_bytes, language):
|
|
|
|
|
|
|
|
|
|
| 26 |
try:
|
| 27 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
|
| 28 |
+
tmp.write(audio_bytes)
|
| 29 |
+
tmp_path = tmp.name
|
| 30 |
|
| 31 |
recognizer = sr.Recognizer()
|
| 32 |
+
with sr.AudioFile(tmp_path) as source:
|
| 33 |
audio = recognizer.record(source)
|
| 34 |
lang_code = "en-US" if language == "English" else "ur-PK"
|
| 35 |
+
text = recognizer.recognize_google(audio, language=lang_code)
|
| 36 |
+
return text.lower()
|
| 37 |
except Exception as e:
|
| 38 |
+
return f"⚠️ Transcription failed: {e}"
|
| 39 |
|
| 40 |
def query_llm(api, messages, model=None):
|
| 41 |
headers = {
|
|
|
|
| 46 |
"messages": messages,
|
| 47 |
"model": model or ("llama3-70b-8192" if api == "GROQ" else "mistral-medium")
|
| 48 |
}
|
| 49 |
+
endpoint = {
|
| 50 |
+
"MISTRAL": "https://api.mistral.ai/v1/chat/completions",
|
| 51 |
+
"GROQ": "https://api.groq.com/openai/v1/chat/completions"
|
| 52 |
+
}[api]
|
|
|
|
| 53 |
|
| 54 |
+
response = requests.post(endpoint, headers=headers, json=payload)
|
| 55 |
+
return response.json()["choices"][0]["message"]["content"] if response.status_code == 200 else None
|
|
|
|
| 56 |
|
| 57 |
def generate_question(answers):
|
| 58 |
+
prompt = "You are playing Kasoti. Based on these yes/no answers, ask the next best question:\n\n"
|
| 59 |
for i, (q, a) in enumerate(answers, 1):
|
| 60 |
prompt += f"{i}. Q: {q}\n A: {a}\n"
|
| 61 |
+
prompt += "\nAsk ONLY the next best yes/no question."
|
| 62 |
+
return query_llm("GROQ", [{"role": "user", "content": prompt}]) or "Is it something you can hold?"
|
| 63 |
|
| 64 |
def make_guess(answers):
|
| 65 |
+
prompt = "Based on this history, make a guess:\n\n"
|
| 66 |
for i, (q, a) in enumerate(answers, 1):
|
| 67 |
prompt += f"{i}. Q: {q}\n A: {a}\n"
|
| 68 |
+
return query_llm("GROQ", [{"role": "user", "content": prompt}]) or "I need more information."
|
| 69 |
|
| 70 |
def get_hint(question, answers):
|
| 71 |
+
prompt = f"The player is unsure about answering: '{question}'. Previous history:\n"
|
| 72 |
for q, a in answers:
|
| 73 |
prompt += f"- Q: {q}\n A: {a}\n"
|
| 74 |
+
prompt += "\nSuggest a helpful hint."
|
| 75 |
+
return query_llm("MISTRAL", [{"role": "user", "content": prompt}]) or "Try to think about what it really means."
|
| 76 |
|
| 77 |
+
def normalize_answer(ans):
|
| 78 |
+
ans = ans.strip().lower()
|
| 79 |
+
return {"yes": "yes", "y": "yes", "ہاں": "yes", "haan": "yes",
|
| 80 |
+
"no": "no", "n": "no", "نہیں": "no", "nahi": "no"}.get(ans, None)
|
|
|
|
| 81 |
|
| 82 |
+
def start_game():
|
| 83 |
+
st.session_state.game_state.update({
|
| 84 |
"active": True,
|
| 85 |
"questions_asked": 1,
|
| 86 |
"answers": [],
|
| 87 |
+
"current_question": "Is it a living thing?"
|
|
|
|
| 88 |
})
|
| 89 |
+
st.success("🎯 Think of something. I’ll guess it in 20 questions or less!")
|
| 90 |
+
st.info(st.session_state.game_state["current_question"])
|
| 91 |
+
|
| 92 |
+
def handle_answer(user_input):
|
| 93 |
+
gs = st.session_state.game_state
|
| 94 |
+
norm_ans = normalize_answer(user_input)
|
| 95 |
+
if not norm_ans:
|
| 96 |
+
st.warning("Please answer 'yes' or 'no' (or ہاں / نہیں).")
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
# Handle guess confirmation
|
| 100 |
+
if gs["current_question"] and "is this correct?" in gs["current_question"].lower():
|
| 101 |
+
if norm_ans == "yes":
|
| 102 |
+
st.success("🎉 YAY! I guessed it!")
|
| 103 |
+
gs["active"] = False
|
| 104 |
else:
|
| 105 |
+
q = generate_question(gs["answers"])
|
| 106 |
+
gs["current_question"] = q
|
| 107 |
+
gs["questions_asked"] += 1
|
| 108 |
+
st.info(q)
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
gs["answers"].append((gs["current_question"], norm_ans))
|
| 112 |
+
if gs["questions_asked"] >= 20:
|
| 113 |
+
final = make_guess(gs["answers"])
|
| 114 |
+
st.error(f"🎮 Game Over! My final guess: {final}")
|
| 115 |
+
gs["active"] = False
|
| 116 |
+
return
|
| 117 |
+
|
| 118 |
+
if gs["questions_asked"] % 5 == 0:
|
| 119 |
+
guess = make_guess(gs["answers"])
|
| 120 |
+
if guess.startswith("I think it's"):
|
| 121 |
+
gs["current_question"] = guess + " Is this correct?"
|
| 122 |
+
st.warning(gs["current_question"])
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
next_q = generate_question(gs["answers"])
|
| 126 |
+
gs["current_question"] = next_q
|
| 127 |
+
gs["questions_asked"] += 1
|
| 128 |
+
st.info(next_q)
|
| 129 |
+
|
| 130 |
+
# UI
|
| 131 |
+
st.set_page_config(page_title="Kasoti Game 🎮", layout="centered")
|
| 132 |
+
st.title("🎮 Kasoti - 20 Questions Game")
|
| 133 |
+
st.markdown("Think of a **person, place, or object**. Answer with **yes/no** or **ہاں/نہیں**. I will guess!")
|
| 134 |
+
|
| 135 |
+
if st.button("Start Game"):
|
| 136 |
+
start_game()
|
| 137 |
+
|
| 138 |
+
language = st.selectbox("Select Language for Audio Input", ["English", "Urdu"])
|
| 139 |
+
audio_input = st.file_uploader("🎤 Upload your Answer (WAV format)", type=["wav"])
|
| 140 |
+
if audio_input:
|
| 141 |
+
transcribed = transcribe_audio(audio_input.read(), language)
|
| 142 |
+
st.text_area("Transcribed Answer", value=transcribed, key="text_input")
|
| 143 |
+
|
| 144 |
+
manual_input = st.text_input("Or type your answer here (yes/no/ہاں/نہیں):")
|
| 145 |
+
|
| 146 |
+
if st.button("Submit Answer"):
|
| 147 |
+
answer_text = manual_input or st.session_state.get("text_input", "")
|
| 148 |
+
if not answer_text:
|
| 149 |
+
st.warning("Please provide an answer.")
|
| 150 |
+
else:
|
| 151 |
+
handle_answer(answer_text)
|
| 152 |
+
|
| 153 |
+
if st.checkbox("Enable Consult Mode"):
|
| 154 |
+
st.session_state.game_state["consult_mode"] = True
|
| 155 |
+
if st.button("🔍 Get Hint"):
|
| 156 |
+
hint = get_hint(
|
| 157 |
+
st.session_state.game_state["current_question"],
|
| 158 |
+
st.session_state.game_state["answers"]
|
| 159 |
+
)
|
| 160 |
+
st.info(f"💡 Hint: {hint}")
|