Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,61 @@
|
|
| 1 |
-
import argparse
|
| 2 |
-
import urllib.request
|
| 3 |
-
from threading import Thread
|
| 4 |
-
|
| 5 |
import gradio as gr
|
| 6 |
import torch
|
| 7 |
-
from transformers import AutoTokenizer,
|
| 8 |
-
import speech_recognition as sr
|
| 9 |
import pyttsx3
|
|
|
|
| 10 |
from huggingface_hub import InferenceClient
|
| 11 |
|
| 12 |
-
# API Key for
|
| 13 |
-
API_KEY = "
|
| 14 |
|
| 15 |
-
# Initialize InferenceClient with
|
| 16 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=API_KEY)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
|
| 21 |
-
# Load
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
return
|
| 42 |
|
| 43 |
|
| 44 |
# Convert voice input (audio) to text
|
|
@@ -54,62 +71,57 @@ def voice_to_text(audio):
|
|
| 54 |
text = "Could not request results from Google Speech Recognition service."
|
| 55 |
return text
|
| 56 |
|
| 57 |
-
|
| 58 |
# Convert text to speech (voice output)
|
| 59 |
def text_to_voice(text):
|
| 60 |
-
|
| 61 |
-
engine.save_to_file(text,
|
| 62 |
engine.runAndWait()
|
| 63 |
-
return
|
| 64 |
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
def respond(message, history, audio_input=None):
|
| 68 |
-
if audio_input:
|
| 69 |
-
message = voice_to_text(audio_input) # Convert audio input to text if available
|
| 70 |
-
|
| 71 |
-
# Prepare the prompt for the Socratic model
|
| 72 |
-
user_query = "".join(f"Student: {s}\nTeacher: {t}\n" for s, t in history[:-1])
|
| 73 |
-
last_query: str = history[-1][0]
|
| 74 |
-
user_query += f"Student: {last_query}"
|
| 75 |
-
|
| 76 |
-
content = f"Teacher: {user_query}"
|
| 77 |
-
|
| 78 |
-
# Get the model's response
|
| 79 |
-
model, tokenizer, streamer, device = load_model()
|
| 80 |
-
|
| 81 |
-
formatted = tokenizer.apply_chat_template([{"role": "user", "content": content}], tokenize=False, add_generation_prompt=True)
|
| 82 |
-
encoded_inputs = tokenizer([formatted], return_tensors="pt").to(device)
|
| 83 |
-
|
| 84 |
-
thread = Thread(target=model.generate, kwargs=dict(encoded_inputs, max_new_tokens=250, streamer=streamer))
|
| 85 |
-
thread.start()
|
| 86 |
-
|
| 87 |
-
response = ""
|
| 88 |
-
for word in streamer:
|
| 89 |
-
response += word
|
| 90 |
-
|
| 91 |
-
# Convert response text to speech (audio output)
|
| 92 |
-
audio_output = text_to_voice(response)
|
| 93 |
-
|
| 94 |
-
return response, audio_output
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
# Gradio UI with text and audio input/output
|
| 98 |
def create_interface():
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
gr.Textbox(label="Text
|
| 107 |
-
gr.Audio(label="
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
if __name__ == "__main__":
|
| 115 |
-
create_interface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
|
|
| 4 |
import pyttsx3
|
| 5 |
+
import speech_recognition as sr
|
| 6 |
from huggingface_hub import InferenceClient
|
| 7 |
|
| 8 |
+
# API Key for HuggingFace InferenceClient
|
| 9 |
+
API_KEY = "AIzaSyBWBxsPBykuJ6z_kMYlAq9k9u3YU2Uy8Oc"
|
| 10 |
|
| 11 |
+
# Initialize the InferenceClient (replace with your model name if necessary)
|
| 12 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=API_KEY)
|
| 13 |
|
| 14 |
+
# Hardcoded system message
|
| 15 |
+
system_message = "You are a friendly and helpful chatbot."
|
| 16 |
|
| 17 |
+
# Load model with quantization and auto-device setup for faster loading
|
| 18 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 19 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
+
"eurecom-ds/Phi-3-mini-4k-socratic", # Replace with your model
|
| 21 |
+
torch_dtype=torch.bfloat16,
|
| 22 |
+
load_in_4bit=True, # Enable 4-bit quantization for faster inference
|
| 23 |
+
device_map="auto", # Automatically use GPU if available
|
| 24 |
+
)
|
| 25 |
|
| 26 |
+
# Tokenizer for the model
|
| 27 |
+
tokenizer = AutoTokenizer.from_pretrained("eurecom-ds/Phi-3-mini-4k-socratic")
|
| 28 |
|
| 29 |
+
# Function to handle text responses
|
| 30 |
+
def respond(message, history: list, audio_input=None):
|
| 31 |
+
if audio_input:
|
| 32 |
+
message = voice_to_text(audio_input)
|
| 33 |
+
|
| 34 |
+
messages = [{"role": "system", "content": system_message}]
|
| 35 |
+
|
| 36 |
+
for val in history:
|
| 37 |
+
if val[0]:
|
| 38 |
+
messages.append({"role": "user", "content": val[0]})
|
| 39 |
+
if val[1]:
|
| 40 |
+
messages.append({"role": "assistant", "content": val[1]})
|
| 41 |
+
|
| 42 |
+
messages.append({"role": "user", "content": message})
|
| 43 |
|
| 44 |
+
response = "" # Initialize response
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
for message_response in client.chat_completion(messages, max_tokens=150, stream=True): # Reduce max tokens for faster response
|
| 48 |
+
if 'choices' in message_response and len(message_response['choices']) > 0:
|
| 49 |
+
delta_content = message_response['choices'][0].get('delta', {}).get('content', '')
|
| 50 |
+
if delta_content:
|
| 51 |
+
response += delta_content
|
| 52 |
+
else:
|
| 53 |
+
print("Error: No valid content in response")
|
| 54 |
+
break
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error during API request: {e}")
|
| 57 |
|
| 58 |
+
return response
|
| 59 |
|
| 60 |
|
| 61 |
# Convert voice input (audio) to text
|
|
|
|
| 71 |
text = "Could not request results from Google Speech Recognition service."
|
| 72 |
return text
|
| 73 |
|
|
|
|
| 74 |
# Convert text to speech (voice output)
|
| 75 |
def text_to_voice(text):
|
| 76 |
+
engine = pyttsx3.init()
|
| 77 |
+
engine.save_to_file(text, 'response.mp3')
|
| 78 |
engine.runAndWait()
|
| 79 |
+
return 'response.mp3'
|
| 80 |
|
| 81 |
|
| 82 |
+
# Gradio Interface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
def create_interface():
|
| 84 |
+
with gr.Blocks() as demo:
|
| 85 |
+
chatbot = gr.Chatbot()
|
| 86 |
+
msg = gr.Textbox(label="Enter your message")
|
| 87 |
+
clear = gr.Button("Clear")
|
| 88 |
+
|
| 89 |
+
# Inputs and Outputs for Text and Audio
|
| 90 |
+
with gr.Row():
|
| 91 |
+
text_input = gr.Textbox(label="Text Input", placeholder="Enter your message...")
|
| 92 |
+
audio_input = gr.Audio(type="filepath", label="Audio Input (Optional)")
|
| 93 |
+
|
| 94 |
+
# Outputs for Text and Audio Response
|
| 95 |
+
with gr.Row():
|
| 96 |
+
text_output = gr.Textbox(label="Text Output")
|
| 97 |
+
audio_output = gr.Audio(label="Voice Output")
|
| 98 |
+
|
| 99 |
+
# Interaction logic
|
| 100 |
+
def user(user_message, history):
|
| 101 |
+
return "", history + [[user_message, ""]]
|
| 102 |
+
|
| 103 |
+
def bot(history):
|
| 104 |
+
user_query = "".join(f"Student: {s}\nTeacher: {t}\n" for s, t in history[:-1])
|
| 105 |
+
last_query = history[-1][0]
|
| 106 |
+
user_query += f"Student: {last_query}"
|
| 107 |
+
response = respond(user_query, history)
|
| 108 |
+
history[-1][1] = response
|
| 109 |
+
return history, response # Return updated history and response
|
| 110 |
+
|
| 111 |
+
# Submit text input
|
| 112 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot]).then(bot, [chatbot], [chatbot, text_output])
|
| 113 |
+
|
| 114 |
+
# Submit audio input
|
| 115 |
+
audio_input.change(user, [audio_input, chatbot], [audio_input, chatbot]).then(bot, [chatbot], [chatbot, text_output])
|
| 116 |
+
|
| 117 |
+
# Clear button
|
| 118 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 119 |
+
|
| 120 |
+
return demo
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# Launch Gradio app
|
| 124 |
if __name__ == "__main__":
|
| 125 |
+
demo = create_interface()
|
| 126 |
+
demo.queue()
|
| 127 |
+
demo.launch(server_name="0.0.0.0", server_port=2121) # You can change port as needed
|