ShadowTEM commited on
Commit
cb4264a
·
verified ·
1 Parent(s): 6638b2e

added html render

Browse files
Files changed (1) hide show
  1. app.py +181 -176
app.py CHANGED
@@ -1,176 +1,181 @@
1
- import os
2
- import time
3
- import json
4
- import asyncio
5
- import numpy as np
6
- import soundfile as sf
7
- from datetime import datetime
8
- from pydub import AudioSegment
9
-
10
- # External dependencies.
11
- from flask import Flask, request, jsonify, send_file
12
-
13
- # Import your modules.
14
- from app.stt import AudioProcessor
15
- from app.llm import LLMProcessor
16
- from app.vectorstore import vectorstore
17
- from app.tts import tts
18
- from app.utils import remove_stars
19
-
20
- # Set a custom user agent.
21
- os.environ["USER_AGENT"] = "my-app/1.0"
22
-
23
- # Rename your class to avoid confusion with Flask's app instance.
24
- class CancerApp:
25
- def __init__(self, vectorstore_index_path):
26
- self.audio_processor = AudioProcessor()
27
- self.llm_processor = LLMProcessor()
28
- self.vectorstore = vectorstore(vectorstore_index_path, Initlize_with=3)
29
- self.vectorstore_index = self.vectorstore.load_vectorstore(vectorstore_index_path)
30
- # Run an initial search to load vectorstore contents.
31
- self.vectorstore.search_vectorstore("cancer", 1)
32
- self.tts = tts()
33
-
34
- def text_to_speech(self, message, output_filename, Saved_response=""):
35
- search_results = self.vectorstore.search_vectorstore(message, 5)
36
- query = Saved_response + message
37
- for i, result in enumerate(search_results, 1):
38
- query += f"\n{i}. {result}"
39
-
40
- try:
41
- gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
42
- except Exception as e:
43
- print("Gemini error:", e)
44
- gemini_response = f"Error: {str(e)}"
45
- gemini_response = remove_stars(gemini_response)
46
- Saved_response += "message: " + message + "\n" + "gemini_response: " + gemini_response + "\n"
47
- self.audio_processor.log_conversation(message, bot_text=gemini_response)
48
- audio_data, sample_rate = asyncio.run(self.tts.cpu_stream_to_audio(gemini_response))
49
- sf.write(output_filename, audio_data, sample_rate)
50
- return Saved_response
51
-
52
- def speech_to_speech(self, audiofile_path, output_filename, Saved_response=""):
53
- transcription = self.audio_processor.transcribe_audio(audiofile_path, language="en")
54
- search_results = self.vectorstore.search_vectorstore(transcription, 5)
55
- query = Saved_response + transcription
56
- for i, result in enumerate(search_results, 1):
57
- query += f"\n{i}. {result}"
58
- try:
59
- gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
60
- except Exception as e:
61
- print("Gemini error:", e)
62
- gemini_response = f"Error: {str(e)}"
63
- gemini_response = remove_stars(gemini_response)
64
- Saved_response += "transcription: " + transcription + "\n" + "gemini_response: " + gemini_response + "\n"
65
- self.audio_processor.log_conversation(transcription, bot_text=gemini_response)
66
- audio_data, sample_rate = asyncio.run(self.tts.cpu_stream_to_audio(gemini_response))
67
- sf.write(output_filename, audio_data, sample_rate)
68
- return Saved_response
69
-
70
- def speech_to_text(self, audiofile_path, Saved_response=""):
71
- try:
72
- transcription = self.audio_processor.transcribe_audio(audiofile_path, language="en")
73
- except Exception as ex:
74
- print(f"Transcription error: {ex}")
75
- transcription = ""
76
-
77
- if not transcription:
78
- print("No transcription available; aborting further processing.")
79
- return "", Saved_response
80
-
81
- try:
82
- search_results = self.vectorstore.search_vectorstore(transcription, 5)
83
- except Exception as ex:
84
- print(f"Vectorstore search error: {ex}")
85
- search_results = []
86
-
87
- query = f"{Saved_response}{transcription}"
88
- for i, result in enumerate(search_results, 1):
89
- query += f"\n{i}. {result}"
90
-
91
- try:
92
- gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
93
- gemini_response = remove_stars(gemini_response)
94
- except Exception as e:
95
- print("Gemini error:", e)
96
- gemini_response = f"Error: {str(e)}"
97
- gemini_response = remove_stars(gemini_response)
98
- Saved_response += f"transcription: {transcription}\n" + f"gemini_response: {gemini_response}\n"
99
- self.audio_processor.log_conversation(transcription, bot_text=gemini_response)
100
- return gemini_response, Saved_response
101
-
102
- def text_to_text(self, message, Saved_response=""):
103
- search_results = self.vectorstore.search_vectorstore(message, 5)
104
- query = Saved_response + message
105
- for i, result in enumerate(search_results, 1):
106
- query += f"\n{i}. {result}"
107
-
108
- try:
109
- gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
110
- gemini_response = remove_stars(gemini_response)
111
- except Exception as e:
112
- print("Gemini error:", e)
113
- gemini_response = f"Error: {str(e)}"
114
- Saved_response += "message: " + message + "\n" + "gemini_response: " + gemini_response + "\n"
115
- self.audio_processor.log_conversation(message, bot_text=gemini_response)
116
- return gemini_response, Saved_response
117
-
118
- # Create Flask API instance.
119
- flask_app = Flask(__name__)
120
-
121
- # Instantiate the CancerApp with your vectorstore path.
122
- vectordb_path = os.path.join("VectorDB", "vectorstore_20250328_011300")
123
- cancer_app_instance = CancerApp(vectordb_path)
124
-
125
- # Endpoint for text-to-text processing.
126
- @flask_app.route('/text_to_text', methods=['POST'])
127
- def api_text_to_text():
128
- data = request.get_json()
129
- message = data.get("message", "")
130
- saved_response = data.get("Saved_response", "")
131
- response, saved_response = cancer_app_instance.text_to_text(message, Saved_response=saved_response)
132
- return jsonify({"gemini_response": response, "Saved_response": saved_response})
133
-
134
- # Endpoint for text-to-speech processing.
135
- @flask_app.route('/text_to_speech', methods=['POST'])
136
- def api_text_to_speech():
137
- data = request.get_json()
138
- message = data.get("message", "")
139
- output_filename = data.get("output_filename", "output.wav")
140
- saved_response = data.get("Saved_response", "")
141
- saved_response = cancer_app_instance.text_to_speech(message, output_filename, Saved_response=saved_response)
142
- return jsonify({"output_filename": output_filename, "Saved_response": saved_response})
143
-
144
- # Endpoint for speech-to-text processing.
145
- @flask_app.route('/speech_to_text', methods=['POST'])
146
- def api_speech_to_text():
147
- if 'audiofile' not in request.files:
148
- return jsonify({"error": "No audio file provided"}), 400
149
- audio_file = request.files['audiofile']
150
- # Save uploaded file temporarily.
151
- audio_ext = audio_file.filename.split('.')[-1]
152
- audio_path = f"temp_audio_input.{audio_ext}"
153
- audio_file.save(audio_path)
154
- saved_response = request.form.get("Saved_response", "")
155
- gemini_response, saved_response = cancer_app_instance.speech_to_text(audio_path, Saved_response=saved_response)
156
- os.remove(audio_path)
157
- return jsonify({"gemini_response": gemini_response, "Saved_response": saved_response})
158
-
159
- # Endpoint for speech-to-speech processing.
160
- @flask_app.route('/speech_to_speech', methods=['POST'])
161
- def api_speech_to_speech():
162
- if 'audiofile' not in request.files:
163
- return jsonify({"error": "No audio file provided"}), 400
164
- audio_file = request.files['audiofile']
165
- audio_ext = audio_file.filename.split('.')[-1]
166
- audio_path = f"temp_audio_input.{audio_ext}"
167
- audio_file.save(audio_path)
168
- output_filename = request.form.get("output_filename", "speech_output.wav")
169
- saved_response = request.form.get("Saved_response", "")
170
- saved_response = cancer_app_instance.speech_to_speech(audio_path, output_filename, Saved_response=saved_response)
171
- os.remove(audio_path)
172
- # Return the output file for download.
173
- return send_file(output_filename, as_attachment=True)
174
-
175
- if __name__ == '__main__':
176
- flask_app.run(host='0.0.0.0', port=7860, debug=True)
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import asyncio
5
+ import numpy as np
6
+ import soundfile as sf
7
+ from datetime import datetime
8
+ from pydub import AudioSegment
9
+
10
+ # External dependencies.
11
+ from flask import Flask, request, jsonify, send_file
12
+
13
+ # Import your modules.
14
+ from app.stt import AudioProcessor
15
+ from app.llm import LLMProcessor
16
+ from app.vectorstore import vectorstore
17
+ from app.tts import tts
18
+ from app.utils import remove_stars
19
+
20
+ # Set a custom user agent.
21
+ os.environ["USER_AGENT"] = "my-app/1.0"
22
+
23
+ # Rename your class to avoid confusion with Flask's app instance.
24
+ class CancerApp:
25
+ def __init__(self, vectorstore_index_path):
26
+ self.audio_processor = AudioProcessor()
27
+ self.llm_processor = LLMProcessor()
28
+ self.vectorstore = vectorstore(vectorstore_index_path, Initlize_with=3)
29
+ self.vectorstore_index = self.vectorstore.load_vectorstore(vectorstore_index_path)
30
+ # Run an initial search to load vectorstore contents.
31
+ self.vectorstore.search_vectorstore("cancer", 1)
32
+ self.tts = tts()
33
+
34
+ def text_to_speech(self, message, output_filename, Saved_response=""):
35
+ search_results = self.vectorstore.search_vectorstore(message, 5)
36
+ query = Saved_response + message
37
+ for i, result in enumerate(search_results, 1):
38
+ query += f"\n{i}. {result}"
39
+
40
+ try:
41
+ gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
42
+ except Exception as e:
43
+ print("Gemini error:", e)
44
+ gemini_response = f"Error: {str(e)}"
45
+ gemini_response = remove_stars(gemini_response)
46
+ Saved_response += "message: " + message + "\n" + "gemini_response: " + gemini_response + "\n"
47
+ self.audio_processor.log_conversation(message, bot_text=gemini_response)
48
+ audio_data, sample_rate = asyncio.run(self.tts.cpu_stream_to_audio(gemini_response))
49
+ sf.write(output_filename, audio_data, sample_rate)
50
+ return Saved_response
51
+
52
+ def speech_to_speech(self, audiofile_path, output_filename, Saved_response=""):
53
+ transcription = self.audio_processor.transcribe_audio(audiofile_path, language="en")
54
+ search_results = self.vectorstore.search_vectorstore(transcription, 5)
55
+ query = Saved_response + transcription
56
+ for i, result in enumerate(search_results, 1):
57
+ query += f"\n{i}. {result}"
58
+ try:
59
+ gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
60
+ except Exception as e:
61
+ print("Gemini error:", e)
62
+ gemini_response = f"Error: {str(e)}"
63
+ gemini_response = remove_stars(gemini_response)
64
+ Saved_response += "transcription: " + transcription + "\n" + "gemini_response: " + gemini_response + "\n"
65
+ self.audio_processor.log_conversation(transcription, bot_text=gemini_response)
66
+ audio_data, sample_rate = asyncio.run(self.tts.cpu_stream_to_audio(gemini_response))
67
+ sf.write(output_filename, audio_data, sample_rate)
68
+ return Saved_response
69
+
70
+ def speech_to_text(self, audiofile_path, Saved_response=""):
71
+ try:
72
+ transcription = self.audio_processor.transcribe_audio(audiofile_path, language="en")
73
+ except Exception as ex:
74
+ print(f"Transcription error: {ex}")
75
+ transcription = ""
76
+
77
+ if not transcription:
78
+ print("No transcription available; aborting further processing.")
79
+ return "", Saved_response
80
+
81
+ try:
82
+ search_results = self.vectorstore.search_vectorstore(transcription, 5)
83
+ except Exception as ex:
84
+ print(f"Vectorstore search error: {ex}")
85
+ search_results = []
86
+
87
+ query = f"{Saved_response}{transcription}"
88
+ for i, result in enumerate(search_results, 1):
89
+ query += f"\n{i}. {result}"
90
+
91
+ try:
92
+ gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
93
+ gemini_response = remove_stars(gemini_response)
94
+ except Exception as e:
95
+ print("Gemini error:", e)
96
+ gemini_response = f"Error: {str(e)}"
97
+ gemini_response = remove_stars(gemini_response)
98
+ Saved_response += f"transcription: {transcription}\n" + f"gemini_response: {gemini_response}\n"
99
+ self.audio_processor.log_conversation(transcription, bot_text=gemini_response)
100
+ return gemini_response, Saved_response
101
+
102
+ def text_to_text(self, message, Saved_response=""):
103
+ search_results = self.vectorstore.search_vectorstore(message, 5)
104
+ query = Saved_response + message
105
+ for i, result in enumerate(search_results, 1):
106
+ query += f"\n{i}. {result}"
107
+
108
+ try:
109
+ gemini_response = self.llm_processor.call_gemini_llm("gemini-2.0-flash", query)
110
+ gemini_response = remove_stars(gemini_response)
111
+ except Exception as e:
112
+ print("Gemini error:", e)
113
+ gemini_response = f"Error: {str(e)}"
114
+ Saved_response += "message: " + message + "\n" + "gemini_response: " + gemini_response + "\n"
115
+ self.audio_processor.log_conversation(message, bot_text=gemini_response)
116
+ return gemini_response, Saved_response
117
+
118
+ # Create Flask API instance.
119
+ flask_app = Flask(__name__)
120
+
121
+ # Instantiate the CancerApp with your vectorstore path.
122
+ vectordb_path = os.path.join("VectorDB", "vectorstore_20250328_011300")
123
+ cancer_app_instance = CancerApp(vectordb_path)
124
+
125
+ #implement html
126
+ @flask_app.route('/')
127
+ def index():
128
+ return render_template('index.html')
129
+
130
+ # Endpoint for text-to-text processing.
131
+ @flask_app.route('/text_to_text', methods=['POST'])
132
+ def api_text_to_text():
133
+ data = request.get_json()
134
+ message = data.get("message", "")
135
+ saved_response = data.get("Saved_response", "")
136
+ response, saved_response = cancer_app_instance.text_to_text(message, Saved_response=saved_response)
137
+ return jsonify({"gemini_response": response, "Saved_response": saved_response})
138
+
139
+ # Endpoint for text-to-speech processing.
140
+ @flask_app.route('/text_to_speech', methods=['POST'])
141
+ def api_text_to_speech():
142
+ data = request.get_json()
143
+ message = data.get("message", "")
144
+ output_filename = data.get("output_filename", "output.wav")
145
+ saved_response = data.get("Saved_response", "")
146
+ saved_response = cancer_app_instance.text_to_speech(message, output_filename, Saved_response=saved_response)
147
+ return jsonify({"output_filename": output_filename, "Saved_response": saved_response})
148
+
149
+ # Endpoint for speech-to-text processing.
150
+ @flask_app.route('/speech_to_text', methods=['POST'])
151
+ def api_speech_to_text():
152
+ if 'audiofile' not in request.files:
153
+ return jsonify({"error": "No audio file provided"}), 400
154
+ audio_file = request.files['audiofile']
155
+ # Save uploaded file temporarily.
156
+ audio_ext = audio_file.filename.split('.')[-1]
157
+ audio_path = f"temp_audio_input.{audio_ext}"
158
+ audio_file.save(audio_path)
159
+ saved_response = request.form.get("Saved_response", "")
160
+ gemini_response, saved_response = cancer_app_instance.speech_to_text(audio_path, Saved_response=saved_response)
161
+ os.remove(audio_path)
162
+ return jsonify({"gemini_response": gemini_response, "Saved_response": saved_response})
163
+
164
+ # Endpoint for speech-to-speech processing.
165
+ @flask_app.route('/speech_to_speech', methods=['POST'])
166
+ def api_speech_to_speech():
167
+ if 'audiofile' not in request.files:
168
+ return jsonify({"error": "No audio file provided"}), 400
169
+ audio_file = request.files['audiofile']
170
+ audio_ext = audio_file.filename.split('.')[-1]
171
+ audio_path = f"temp_audio_input.{audio_ext}"
172
+ audio_file.save(audio_path)
173
+ output_filename = request.form.get("output_filename", "speech_output.wav")
174
+ saved_response = request.form.get("Saved_response", "")
175
+ saved_response = cancer_app_instance.speech_to_speech(audio_path, output_filename, Saved_response=saved_response)
176
+ os.remove(audio_path)
177
+ # Return the output file for download.
178
+ return send_file(output_filename, as_attachment=True)
179
+
180
+ if __name__ == '__main__':
181
+ flask_app.run(host='0.0.0.0', port=7860, debug=True)