awacke1 commited on
Commit
7b093fe
·
verified ·
1 Parent(s): b4452d9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ async def respond(audio, model, seed):
104
+ user = transcribe(audio)
105
+ reply = models(user, model, seed)
106
+ communicate = edge_tts.Communicate(reply)
107
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
108
+ tmp_path = tmp_file.name
109
+ await communicate.save(tmp_path)
110
+ return tmp_path
111
+
112
+ def display_history():
113
+ df = load_history()
114
+ df['Timestamp'] = df['Timestamp'].astype(str)
115
+ return df
116
+
117
+ def download_history():
118
+ csv_buffer = io.StringIO()
119
+ history_df_copy = history_df.copy()
120
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
121
+ history_df_copy.to_csv(csv_buffer, index=False)
122
+ csv_string = csv_buffer.getvalue()
123
+ b64 = base64.b64encode(csv_string.encode()).decode()
124
+ href = f'data:text/csv;base64,{b64}'
125
+ return gr.HTML(f'<a href="{href}" download="chat_history.csv">Download Chat History</a>')
126
+
127
+ DESCRIPTION = """# <center>Dr. Nova Quantum⚡ - Your Personal Guide to the Frontiers of Science and Technology</center>"""
128
+
129
+ with gr.Blocks(css="style.css") as demo:
130
+ gr.Markdown(DESCRIPTION)
131
+ with gr.Row():
132
+ select = gr.Dropdown([
133
+ 'Llama 3 8B',
134
+ 'Mixtral 8x7B',
135
+ 'Mistral 7B v0.3',
136
+ 'Phi 3 mini',
137
+ ],
138
+ value="Llama 3 8B",
139
+ label="Model"
140
+ )
141
+ seed = gr.Slider(
142
+ label="Seed",
143
+ minimum=0,
144
+ maximum=999999,
145
+ step=1,
146
+ value=0,
147
+ visible=False
148
+ )
149
+
150
+ input_audio = gr.Audio(label="User", sources="microphone", type="filepath")
151
+ output_audio = gr.Audio(label="Dr. Nova Quantum", type="filepath", autoplay=True)
152
+
153
+ # Add markdown displays for request and response
154
+ request_md = gr.Markdown(label="User Request")
155
+ response_md = gr.Markdown(label="Dr. Nova Quantum Response")
156
+
157
+ # Update the DataFrame to display the history with the new order
158
+ history_display = gr.DataFrame(label="Conversation History", headers=["Timestamp", "Model", "Input Size", "Output Size", "Request", "Response"])
159
+
160
+ # Add a download button for the history
161
+ download_button = gr.Button("Download Conversation History")
162
+ download_link = gr.HTML()
163
+
164
+ def process_audio(audio, model, seed):
165
+ response = asyncio.run(respond(audio, model, seed))
166
+ text = transcribe(audio)
167
+ return response, display_history(), text, models(text, model, seed)
168
+
169
+ input_audio.change(
170
+ fn=process_audio,
171
+ inputs=[input_audio, select, seed],
172
+ outputs=[output_audio, history_display, request_md, response_md]
173
+ )
174
+
175
+ # Connect the download button to the download function
176
+ download_button.click(fn=download_history, outputs=[download_link])
177
+
178
+ # Load history when the page is loaded or refreshed
179
+ demo.load(fn=display_history, outputs=[history_display])
180
+
181
+ if __name__ == "__main__":
182
+ # Load history at startup
183
+ load_history()
184
+ demo.queue(max_size=200).launch()