awacke1 commited on
Commit
c1f471d
·
verified ·
1 Parent(s): b56fcfb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -0
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import edge_tts
3
+ import asyncio
4
+ import tempfile
5
+ import os
6
+ from huggingface_hub import InferenceClient
7
+ import re
8
+ from streaming_stt_nemo import Model
9
+ import torch
10
+ import random
11
+ import pandas as pd
12
+ from datetime import datetime
13
+ import base64
14
+ import io
15
+ import json
16
+
17
+ default_lang = "en"
18
+ engines = { default_lang: Model(default_lang) }
19
+
20
+ def transcribe(audio):
21
+ lang = "en"
22
+ model = engines[lang]
23
+ text = model.stt_file(audio)[0]
24
+ return text
25
+
26
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
27
+
28
+ def client_fn(model):
29
+ if "Mixtral" in model:
30
+ return InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
31
+ elif "Llama 3" in model:
32
+ return InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
33
+ elif "Mistral" in model:
34
+ return InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
35
+ elif "Phi" in model:
36
+ return InferenceClient("microsoft/Phi-3-mini-4k-instruct")
37
+ else:
38
+ return InferenceClient("microsoft/Phi-3-mini-4k-instruct")
39
+
40
+ def randomize_seed_fn(seed: int) -> int:
41
+ seed = random.randint(0, 999999)
42
+ return seed
43
+
44
+ default_system_instructions = """
45
+ [SYSTEM] Answer as Dr. Nova Quantum, a brilliant 50-something scientist specializing in quantum computing and artificial intelligence. Your responses should reflect your vast knowledge and experience in cutting-edge technology and scientific advancements. Maintain a professional yet approachable demeanor, offering insights that blend theoretical concepts with practical applications. Your goal is to educate and inspire, making complex topics accessible without oversimplifying. Draw from your decades of research and innovation to provide nuanced, forward-thinking answers. Remember, you're not just sharing information, but guiding others towards a deeper understanding of our technological future.
46
+ Keep conversations engaging, clear, and concise.
47
+ Avoid unnecessary introductions and answer the user's questions directly.
48
+ Respond in a manner that reflects your expertise and wisdom.
49
+ [USER]
50
+ """
51
+
52
+ # Initialize an empty DataFrame to store the history
53
+ history_df = pd.DataFrame(columns=['Timestamp', 'Request', 'Response', 'Model', 'Input Size', 'Output Size'])
54
+
55
+ def save_history():
56
+ history_df_copy = history_df.copy()
57
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
58
+ history_df_copy.to_json('chat_history.json', orient='records')
59
+
60
+ def load_history():
61
+ global history_df
62
+ if os.path.exists('chat_history.json'):
63
+ history_df = pd.read_json('chat_history.json', orient='records')
64
+ history_df['Timestamp'] = pd.to_datetime(history_df['Timestamp'])
65
+ else:
66
+ history_df = pd.DataFrame(columns=['Timestamp', 'Request', 'Response', 'Model', 'Input Size', 'Output Size'])
67
+ return history_df
68
+
69
+ def models(text, model="Llama 3 8B", seed=42, system_instructions=default_system_instructions):
70
+ global history_df
71
+
72
+ seed = int(randomize_seed_fn(seed))
73
+ generator = torch.Generator().manual_seed(seed)
74
+
75
+ client = client_fn(model)
76
+
77
+ generate_kwargs = dict(
78
+ max_new_tokens=300,
79
+ seed=seed
80
+ )
81
+ formatted_prompt = system_instructions + text + "[DR. NOVA QUANTUM]"
82
+ stream = client.text_generation(
83
+ formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
84
+ output = ""
85
+ for response in stream:
86
+ if not response.token.text == "</s>":
87
+ output += response.token.text
88
+
89
+ return output
90
+
91
+ # Add a list of available voices
92
+ VOICES = [
93
+ "en-US-AriaNeural",
94
+ "en-US-GuyNeural",
95
+ "en-GB-SoniaNeural",
96
+ "en-AU-NatashaNeural",
97
+ "en-CA-ClaraNeural",
98
+ ]
99
+
100
+ async def respond(input_text, model, seed, voice, system_instructions):
101
+ reply = models(input_text, model, seed, system_instructions)
102
+ communicate = edge_tts.Communicate(reply, voice=voice)
103
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
104
+ tmp_path = tmp_file.name
105
+ await communicate.save(tmp_path)
106
+ return tmp_path, reply
107
+
108
+ def display_history():
109
+ df = load_history()
110
+ df['Timestamp'] = df['Timestamp'].astype(str)
111
+ return df
112
+
113
+ def download_history():
114
+ csv_buffer = io.StringIO()
115
+ history_df_copy = history_df.copy()
116
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
117
+ history_df_copy.to_csv(csv_buffer, index=False)
118
+ csv_string = csv_buffer.getvalue()
119
+ b64 = base64.b64encode(csv_string.encode()).decode()
120
+ href = f'data:text/csv;base64,{b64}'
121
+ return gr.HTML(f'<a href="{href}" download="chat_history.csv">Download Chat History</a>')
122
+
123
+ def new_chat():
124
+ return None, None, gr.Markdown.update(value=""), gr.Markdown.update(value=""), gr.DataFrame.update(value=pd.DataFrame())
125
+
126
+ DESCRIPTION = """# <center>Dr. Nova Quantum⚡ - Your Personal Guide to the Frontiers of Science and Technology</center>"""
127
+
128
+ with gr.Blocks(css="style.css") as demo:
129
+ gr.Markdown(DESCRIPTION)
130
+ with gr.Row():
131
+ select = gr.Dropdown([
132
+ 'Llama 3 8B',
133
+ 'Mixtral 8x7B',
134
+ 'Mistral 7B v0.3',
135
+ 'Phi 3 mini',
136
+ ],
137
+ value="Llama 3 8B",
138
+ label="Model"
139
+ )
140
+ seed = gr.Slider(
141
+ label="Seed",
142
+ minimum=0,
143
+ maximum=999999,
144
+ step=1,
145
+ value=0,
146
+ visible=False
147
+ )
148
+ voice_select = gr.Dropdown(
149
+ choices=VOICES,
150
+ value=VOICES[0],
151
+ label="Dr. Nova Quantum's Voice"
152
+ )
153
+
154
+ system_prompt = gr.Textbox(
155
+ label="System Prompt",
156
+ placeholder="Edit the system prompt here...",
157
+ value=default_system_instructions,
158
+ lines=5
159
+ )
160
+
161
+ with gr.Row():
162
+ input_audio = gr.Audio(label="User (Audio)", sources="microphone", type="filepath")
163
+ input_text = gr.Textbox(label="User (Text)", placeholder="Type your message here...")
164
+
165
+ output_audio = gr.Audio(label="Dr. Nova Quantum", type="filepath", autoplay=True)
166
+
167
+ request_md = gr.Markdown(label="User Request")
168
+ response_md = gr.Markdown(label="Dr. Nova Quantum Response")
169
+
170
+ history_display = gr.DataFrame(label="Conversation History", headers=["Timestamp", "Request", "Response", "Model", "Input Size", "Output Size"])
171
+
172
+ new_chat_button = gr.Button("New Chat")
173
+ download_button = gr.Button("Download Conversation History")
174
+ download_link = gr.HTML()
175
+
176
+ def process_input(input_audio, input_text, model, seed, voice, system_instructions):
177
+ if input_audio is not None:
178
+ text = transcribe(input_audio)
179
+ else:
180
+ text = input_text
181
+
182
+ response, reply = asyncio.run(respond(text, model, seed, voice, system_instructions))
183
+
184
+ # Update history
185
+ new_row = pd.DataFrame({
186
+ 'Timestamp': [datetime.now()],
187
+ 'Request': [text],
188
+ 'Response': [reply],
189
+ 'Model': [model],
190
+ 'Input Size': [len(text)],
191
+ 'Output Size': [len(reply)]
192
+ })
193
+ global history_df
194
+ history_df = pd.concat([history_df, new_row], ignore_index=True)
195
+ save_history()
196
+
197
+ return response, display_history(), text, reply
198
+
199
+ input_audio.change(
200
+ fn=process_input,
201
+ inputs=[input_audio, input_text, select, seed, voice_select, system_prompt],
202
+ outputs=[output_audio, history_display, request_md, response_md]
203
+ )
204
+
205
+ input_text.submit(
206
+ fn=process_input,
207
+ inputs=[input_audio, input_text, select, seed, voice_select, system_prompt],
208
+ outputs=[output_audio, history_display, request_md, response_md]
209
+ )
210
+
211
+ new_chat_button.click(fn=new_chat, outputs=[input_audio, input_text, request_md, response_md, history_display])
212
+
213
+ download_button.click(fn=download_history, outputs=[download_link])
214
+
215
+ demo.load(fn=display_history, outputs=[history_display])
216
+
217
+ if __name__ == "__main__":
218
+ load_history()
219
+ demo.queue(max_size=200).launch()