awacke1 commited on
Commit
c3e6966
·
verified ·
1 Parent(s): 8367e5e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.1" in model:
32
+ return InferenceClient("meta-llama/Meta-Llama-3.1-8B-Instruct")
33
+ elif "Llama-3" in model:
34
+ return InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
35
+ elif "Mistral" in model:
36
+ return InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
37
+ elif "Phi" in model:
38
+ return InferenceClient("microsoft/Phi-3-mini-4k-instruct")
39
+ else:
40
+ return InferenceClient("microsoft/Phi-3-mini-4k-instruct")
41
+
42
+ def randomize_seed_fn(seed: int) -> int:
43
+ seed = random.randint(0, 999999)
44
+ return seed
45
+
46
+ system_instructions1 = """
47
+ [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.
48
+ Keep conversations engaging, clear, and concise.
49
+ Avoid unnecessary introductions and answer the user's questions directly.
50
+ Respond in a manner that reflects your expertise and wisdom.
51
+ [USER]
52
+ """
53
+
54
+ # Initialize an empty DataFrame to store the history
55
+ history_df = pd.DataFrame(columns=['Timestamp', 'Request', 'Response', 'Model'])
56
+
57
+ def save_history():
58
+ history_df_copy = history_df.copy()
59
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
60
+ history_df_copy.to_json('chat_history.json', orient='records')
61
+
62
+ def load_history():
63
+ global history_df
64
+ if os.path.exists('chat_history.json'):
65
+ history_df = pd.read_json('chat_history.json', orient='records')
66
+ history_df['Timestamp'] = pd.to_datetime(history_df['Timestamp'])
67
+ else:
68
+ history_df = pd.DataFrame(columns=['Timestamp', 'Request', 'Response', 'Model'])
69
+ return history_df
70
+
71
+ def models(text, model="Meta-Llama-3.1-8B-Instruct", seed=42):
72
+ global history_df
73
+
74
+ seed = int(randomize_seed_fn(seed))
75
+ generator = torch.Generator().manual_seed(seed)
76
+
77
+ client = client_fn(model)
78
+
79
+ generate_kwargs = dict(
80
+ max_new_tokens=300,
81
+ seed=seed
82
+ )
83
+ formatted_prompt = system_instructions1 + text + "[DR. NOVA QUANTUM]"
84
+ stream = client.text_generation(
85
+ formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
86
+ output = ""
87
+ for response in stream:
88
+ if not response.token.text == "</s>":
89
+ output += response.token.text
90
+
91
+ # Add the current interaction to the history DataFrame
92
+ new_row = pd.DataFrame({
93
+ 'Timestamp': [datetime.now()],
94
+ 'Request': [text],
95
+ 'Response': [output],
96
+ 'Model': [model]
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
+ 'Meta-Llama-3.1-8B-Instruct',
134
+ 'Mixtral 8x7B',
135
+ 'Llama 3 8B',
136
+ 'Mistral 7B v0.3',
137
+ 'Phi 3 mini',
138
+ ],
139
+ value="Meta-Llama-3.1-8B-Instruct",
140
+ label="Model"
141
+ )
142
+ seed = gr.Slider(
143
+ label="Seed",
144
+ minimum=0,
145
+ maximum=999999,
146
+ step=1,
147
+ value=0,
148
+ visible=False
149
+ )
150
+
151
+ input_audio = gr.Audio(label="User", sources="microphone", type="filepath")
152
+ output_audio = gr.Audio(label="Dr. Nova Quantum", type="filepath", autoplay=True)
153
+
154
+ # Add markdown displays for request and response
155
+ request_md = gr.Markdown(label="User Request")
156
+ response_md = gr.Markdown(label="Dr. Nova Quantum Response")
157
+
158
+ # Update the DataFrame to display the history with the new model column
159
+ history_display = gr.DataFrame(label="Conversation History", headers=["Timestamp", "Request", "Response", "Model"])
160
+
161
+ # Add a download button for the history
162
+ download_button = gr.Button("Download Conversation History")
163
+ download_link = gr.HTML()
164
+
165
+ def process_audio(audio, model, seed):
166
+ response = asyncio.run(respond(audio, model, seed))
167
+ text = transcribe(audio)
168
+ return response, display_history(), text, models(text, model, seed)
169
+
170
+ input_audio.change(
171
+ fn=process_audio,
172
+ inputs=[input_audio, select, seed],
173
+ outputs=[output_audio, history_display, request_md, response_md]
174
+ )
175
+
176
+ # Connect the download button to the download function
177
+ download_button.click(fn=download_history, outputs=[download_link])
178
+
179
+ # Load history when the page is loaded or refreshed
180
+ demo.load(fn=display_history, outputs=[history_display])
181
+
182
+ if __name__ == "__main__":
183
+ # Load history at startup
184
+ load_history()
185
+ demo.queue(max_size=200).launch()