awacke1 commited on
Commit
a7e805d
·
verified ·
1 Parent(s): cc396fc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -0
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ system_instructions1 = """
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', 'Model', 'Input Size', 'Output Size', 'Request', 'Response'])
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', 'Model', 'Input Size', 'Output Size', 'Request', 'Response'])
67
+ return history_df
68
+
69
+ def models(text, model="Llama 3 8B", seed=42):
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_instructions1 + 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
+ # Add the current interaction to the history DataFrame
90
+ new_row = pd.DataFrame({
91
+ 'Timestamp': [datetime.now()],
92
+ 'Model': [model],
93
+ 'Input Size': [len(text)],
94
+ 'Output Size': [len(output)],
95
+ 'Request': [text],
96
+ 'Response': [output]
97
+ })
98
+ history_df = pd.concat([history_df, new_row], ignore_index=True)
99
+ save_history()
100
+
101
+ return output
102
+
103
+ # Add a list of available voices
104
+ VOICES = [
105
+ "en-US-AriaNeural",
106
+ "en-US-GuyNeural",
107
+ "en-GB-SoniaNeural",
108
+ "en-AU-NatashaNeural",
109
+ "en-CA-ClaraNeural",
110
+ ]
111
+
112
+ async def respond(audio, model, seed, voice):
113
+ user = transcribe(audio)
114
+ reply = models(user, model, seed)
115
+ communicate = edge_tts.Communicate(reply, voice=voice)
116
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
117
+ tmp_path = tmp_file.name
118
+ await communicate.save(tmp_path)
119
+ return tmp_path
120
+
121
+ def display_history():
122
+ df = load_history()
123
+ df['Timestamp'] = df['Timestamp'].astype(str)
124
+ return df
125
+
126
+ def download_history():
127
+ csv_buffer = io.StringIO()
128
+ history_df_copy = history_df.copy()
129
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
130
+ history_df_copy.to_csv(csv_buffer, index=False)
131
+ csv_string = csv_buffer.getvalue()
132
+ b64 = base64.b64encode(csv_string.encode()).decode()
133
+ href = f'data:text/csv;base64,{b64}'
134
+ return gr.HTML(f'<a href="{href}" download="chat_history.csv">Download Chat History</a>')
135
+
136
+ DESCRIPTION = """# <center>Dr. Nova Quantum⚡ - Your Personal Guide to the Frontiers of Science and Technology</center>"""
137
+
138
+ with gr.Blocks(css="style.css") as demo:
139
+ gr.Markdown(DESCRIPTION)
140
+ with gr.Row():
141
+ select = gr.Dropdown([
142
+ 'Llama 3 8B',
143
+ 'Mixtral 8x7B',
144
+ 'Mistral 7B v0.3',
145
+ 'Phi 3 mini',
146
+ ],
147
+ value="Llama 3 8B",
148
+ label="Model"
149
+ )
150
+ seed = gr.Slider(
151
+ label="Seed",
152
+ minimum=0,
153
+ maximum=999999,
154
+ step=1,
155
+ value=0,
156
+ visible=False
157
+ )
158
+ voice_select = gr.Dropdown(
159
+ choices=VOICES,
160
+ value=VOICES[0],
161
+ label="Dr. Nova Quantum's Voice"
162
+ )
163
+
164
+ input_audio = gr.Audio(label="User", sources="microphone", type="filepath")
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", "Model", "Input Size", "Output Size", "Request", "Response"])
171
+
172
+ download_button = gr.Button("Download Conversation History")
173
+ download_link = gr.HTML()
174
+
175
+ def process_audio(audio, model, seed, voice):
176
+ response = asyncio.run(respond(audio, model, seed, voice))
177
+ text = transcribe(audio)
178
+ return response, display_history(), text, models(text, model, seed)
179
+
180
+ input_audio.change(
181
+ fn=process_audio,
182
+ inputs=[input_audio, select, seed, voice_select],
183
+ outputs=[output_audio, history_display, request_md, response_md]
184
+ )
185
+
186
+ download_button.click(fn=download_history, outputs=[download_link])
187
+
188
+ demo.load(fn=display_history, outputs=[history_display])
189
+
190
+ if __name__ == "__main__":
191
+ load_history()
192
+ demo.queue(max_size=200).launch()