Pontonkid commited on
Commit
ac36bdc
·
verified ·
1 Parent(s): b0073f1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import whisper as openai_whisper
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ from TTS.api import TTS
4
+ import gradio as gr
5
+ import torch
6
+ import os
7
+
8
+ # 1. Speech-to-Text (STT) Implementation
9
+ def setup_stt():
10
+ model = openai_whisper.load_model("base") # Explicit OpenAI Whisper
11
+ return model
12
+
13
+ def transcribe_audio(model, audio_file):
14
+ result = model.transcribe(audio_file)
15
+ print("Transcription:", result['text'])
16
+ return result['text']
17
+
18
+ # 2. Natural Language Processing (NLP) Implementation
19
+ def setup_nlp():
20
+ model_name = "gpt2"
21
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
22
+ model = AutoModelForCausalLM.from_pretrained(model_name)
23
+ return tokenizer, model
24
+
25
+ def generate_response(tokenizer, model, input_text):
26
+ prompt = f"User: {input_text}\nAssistant:"
27
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
28
+
29
+ response = model.generate(
30
+ input_ids,
31
+ max_length=150,
32
+ num_return_sequences=1,
33
+ temperature=0.7,
34
+ top_p=0.9,
35
+ pad_token_id=tokenizer.eos_token_id,
36
+ no_repeat_ngram_size=2
37
+ )
38
+ return tokenizer.decode(response[0], skip_special_tokens=True)
39
+
40
+ # 3. Text-to-Speech (TTS) Implementation
41
+ def setup_tts():
42
+ tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
43
+ return tts
44
+
45
+ def generate_speech(tts, text, file_path="output.wav"):
46
+ tts.tts_to_file(text, file_path=file_path)
47
+ return file_path
48
+
49
+ # 4. Voice AI System Class
50
+ class VoiceAISystem:
51
+ def __init__(self):
52
+ print("Initializing Voice AI System...")
53
+ print("Loading STT model...")
54
+ self.stt_model = setup_stt()
55
+ print("Loading NLP model...")
56
+ self.tokenizer, self.nlp_model = setup_nlp()
57
+ print("Loading TTS model...")
58
+ self.tts_model = setup_tts()
59
+
60
+ # GPU Optimization
61
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
62
+ print(f"Using device: {self.device}")
63
+ self.nlp_model = self.nlp_model.to(self.device)
64
+ print("System initialization complete!")
65
+
66
+ def process_audio(self, audio_file):
67
+ try:
68
+ os.makedirs("tmp", exist_ok=True)
69
+
70
+ print("Transcribing audio...")
71
+ text = transcribe_audio(self.stt_model, audio_file)
72
+
73
+ print("Generating response...")
74
+ with torch.cuda.amp.autocast(enabled=torch.cuda.is_available()):
75
+ response = generate_response(self.tokenizer, self.nlp_model, text)
76
+
77
+ print("Converting response to speech...")
78
+ output_path = os.path.join("tmp", "response.wav")
79
+ audio_response = generate_speech(self.tts_model, response, output_path)
80
+
81
+ return audio_response, text, response
82
+ except Exception as e:
83
+ print(f"Error during processing: {str(e)}")
84
+ return None, f"Error: {str(e)}", "Error processing request"
85
+
86
+ # 5. Gradio UI Integration
87
+ def create_voice_ai_interface():
88
+ system = VoiceAISystem()
89
+
90
+ def chat(audio):
91
+ if audio is None:
92
+ return None, "No audio provided", "No response generated"
93
+ return system.process_audio(audio)
94
+
95
+ interface = gr.Interface(
96
+ fn=chat,
97
+ inputs=[
98
+ gr.Audio(
99
+ type="filepath",
100
+ label="Speak here"
101
+ )
102
+ ],
103
+ outputs=[
104
+ gr.Audio(label="AI Response"),
105
+ gr.Textbox(label="Transcribed Text"),
106
+ gr.Textbox(label="AI Response Text")
107
+ ],
108
+ title="Voice AI System",
109
+ description="Click to record your voice and interact with the AI"
110
+ )
111
+
112
+ return interface
113
+
114
+ # Launch the interface
115
+ if __name__ == "__main__":
116
+ iface = create_voice_ai_interface()
117
+ iface.launch(share=True)