Aranwer commited on
Commit
6173475
·
verified ·
1 Parent(s): dbf8b59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -30
app.py CHANGED
@@ -1,30 +1,135 @@
1
- from transformers import AutoModelForCausalLM, AutoTokenizer
2
-
3
- # Load the Mistral model and tokenizer from Hugging Face Hub
4
- model_name = "mistralai/mistral-7b" # Change this to the desired model name
5
- model = AutoModelForCausalLM.from_pretrained(model_name)
6
- tokenizer = AutoTokenizer.from_pretrained(model_name)
7
-
8
- # Function to generate text
9
- def generate_text(prompt: str, max_length: int = 50):
10
- # Tokenize input prompt
11
- inputs = tokenizer(prompt, return_tensors="pt")
12
-
13
- # Generate text
14
- outputs = model.generate(
15
- input_ids=inputs['input_ids'],
16
- max_length=max_length, # Max tokens in output
17
- num_return_sequences=1, # Number of sequences to generate
18
- temperature=0.7, # Adjust for randomness (higher = more random)
19
- top_p=0.9, # Use top-p sampling for diversity
20
- top_k=50 # Top-k sampling for diversity
21
- )
22
-
23
- # Decode the generated text and return it
24
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
25
- return generated_text
26
-
27
- # Example usage
28
- prompt = "The future of artificial intelligence is"
29
- generated_output = generate_text(prompt)
30
- print("Generated Text:", generated_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import speech_recognition as sr
3
+ import tempfile
4
+ import scipy.io.wavfile
5
+ import os
6
+ import requests
7
+ import numpy as np
8
+
9
+ # API Keys
10
+ os.environ["MISTRAL_API_KEY"] = "your-mistral-key"
11
+ os.environ["GROQ_API_KEY"] = "your-groq-key"
12
+
13
+ # Game State
14
+ if "state" not in st.session_state:
15
+ st.session_state.state = {
16
+ "active": False,
17
+ "questions_asked": 0,
18
+ "answers": [],
19
+ "current_question": None,
20
+ "consult_mode": False
21
+ }
22
+
23
+ # Functions
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 tmp_file:
29
+ tmp_file.write(uploaded_file.read())
30
+ tmp_file_path = tmp_file.name
31
+
32
+ recognizer = sr.Recognizer()
33
+ with sr.AudioFile(tmp_file_path) as source:
34
+ audio = recognizer.record(source)
35
+ lang_code = "en-US" if language == "English" else "ur-PK"
36
+ return recognizer.recognize_google(audio, language=lang_code).lower()
37
+ except Exception as e:
38
+ return f"Transcription error: {e}"
39
+
40
+ def query_llm(api, messages, model=None):
41
+ headers = {
42
+ "Authorization": f"Bearer {os.environ[f'{api}_API_KEY']}",
43
+ "Content-Type": "application/json"
44
+ }
45
+ payload = {
46
+ "messages": messages,
47
+ "model": model or ("llama3-70b-8192" if api == "GROQ" else "mistral-medium")
48
+ }
49
+ url = "https://api.groq.com/openai/v1/chat/completions" if api == "GROQ" else "https://api.mistral.ai/v1/chat/completions"
50
+ response = requests.post(url, headers=headers, json=payload)
51
+ if response.ok:
52
+ return response.json()["choices"][0]["message"]["content"]
53
+ return "API Error"
54
+
55
+ def normalize_answer(ans):
56
+ ans = ans.strip().lower()
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. Ask the next best yes/no question.\n\n"
61
+ for i, (q, a) in enumerate(answers, 1):
62
+ prompt += f"{i}. Q: {q}\n A: {a}\n"
63
+ return query_llm("GROQ", [{"role": "user", "content": prompt}])
64
+
65
+ def make_guess(answers):
66
+ prompt = "Based on this history, make a best guess:\n\n"
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}\n\nHistory:\n"
73
+ for q, a in answers:
74
+ prompt += f"- Q: {q}\n A: {a}\n"
75
+ return query_llm("MISTRAL", [{"role": "user", "content": prompt}])
76
+
77
+ # Streamlit UI
78
+ st.set_page_config(page_title="🎮 Kasoti 20Q", layout="centered")
79
+
80
+ st.title("🎮 Kasoti - 20 Questions Game")
81
+ st.info("Think of a famous person, place, or object. Answer with **yes/no** or **ہاں/نہیں** only.")
82
+
83
+ if st.button("🔄 Start Game"):
84
+ st.session_state.state.update({
85
+ "active": True,
86
+ "questions_asked": 1,
87
+ "answers": [],
88
+ "current_question": "Is it a living thing?",
89
+ "consult_mode": False
90
+ })
91
+
92
+ if st.session_state.state["active"]:
93
+ st.success(f"🤔 Question {st.session_state.state['questions_asked']}: {st.session_state.state['current_question']}")
94
+
95
+ with st.form(key="answer_form"):
96
+ audio_file = st.file_uploader("🎙️ Upload your answer (WAV only)", type=["wav"])
97
+ language = st.selectbox("🗣️ Language", ["English", "Urdu"])
98
+ manual_input = st.text_input("💬 Or type your answer:")
99
+ submit = st.form_submit_button("➡️ Submit")
100
+
101
+ if submit:
102
+ answer = manual_input or transcribe_audio(audio_file, language)
103
+ normalized = normalize_answer(answer)
104
+ if not normalized:
105
+ st.warning("⚠️ Please reply with 'yes' or 'no' (or 'ہاں/نہیں').")
106
+ else:
107
+ question = st.session_state.state["current_question"]
108
+ st.session_state.state["answers"].append((question, normalized))
109
+
110
+ if "is this correct?" in question.lower():
111
+ if normalized == "yes":
112
+ st.balloons()
113
+ st.success("🎉 I guessed it right!")
114
+ st.session_state.state["active"] = False
115
+ else:
116
+ next_q = generate_question(st.session_state.state["answers"])
117
+ st.session_state.state["current_question"] = next_q
118
+ st.session_state.state["questions_asked"] += 1
119
+ elif st.session_state.state["questions_asked"] >= 20:
120
+ st.session_state.state["active"] = False
121
+ guess = make_guess(st.session_state.state["answers"])
122
+ st.error(f"❌ Game over! Final guess: {guess}")
123
+ elif st.session_state.state["questions_asked"] % 5 == 0:
124
+ guess = make_guess(st.session_state.state["answers"])
125
+ st.session_state.state["current_question"] = guess + " Is this correct?"
126
+ st.session_state.state["questions_asked"] += 1
127
+ else:
128
+ next_q = generate_question(st.session_state.state["answers"])
129
+ st.session_state.state["current_question"] = next_q
130
+ st.session_state.state["questions_asked"] += 1
131
+
132
+ if st.session_state.state["active"]:
133
+ if st.toggle("💡 Enable Consult Mode"):
134
+ hint = get_hint(st.session_state.state["current_question"], st.session_state.state["answers"])
135
+ st.info(f"💭 Hint: {hint}")