awacke1 commited on
Commit
a96300c
·
verified ·
1 Parent(s): 8e33d93

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 engineer, learning psychologist, memory expert,
46
+ python programmer, romantic, gospel and poet writer scientist specializing in solving problems with code,
47
+ method steps, outlines, song, and humorous wit.
48
+ 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.
49
+ Keep conversations engaging, clear, and concise.
50
+ Avoid unnecessary introductions and answer the user's questions directly.
51
+ Respond in a manner that reflects inspiring expertise and wisdom.
52
+ [USER]
53
+ """
54
+
55
+ # Initialize an empty DataFrame to store the history
56
+ history_df = pd.DataFrame(columns=['Timestamp', 'Model', 'Input Size', 'Output Size', 'Request', 'Response'])
57
+
58
+ def save_history():
59
+ history_df_copy = history_df.copy()
60
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
61
+ history_df_copy.to_json('chat_history.json', orient='records')
62
+
63
+ def load_history():
64
+ global history_df
65
+ if os.path.exists('chat_history.json'):
66
+ history_df = pd.read_json('chat_history.json', orient='records')
67
+ history_df['Timestamp'] = pd.to_datetime(history_df['Timestamp'])
68
+ else:
69
+ history_df = pd.DataFrame(columns=['Timestamp', 'Model', 'Input Size', 'Output Size', 'Request', 'Response'])
70
+ return history_df
71
+
72
+ def models(text, model="Llama 3 8B", seed=42):
73
+ global history_df
74
+
75
+ seed = int(randomize_seed_fn(seed))
76
+ generator = torch.Generator().manual_seed(seed)
77
+
78
+ client = client_fn(model)
79
+
80
+ generate_kwargs = dict(
81
+ max_new_tokens=300,
82
+ seed=seed
83
+ )
84
+ formatted_prompt = system_instructions1 + text + "[DR. NOVA QUANTUM]"
85
+ stream = client.text_generation(
86
+ formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
87
+ output = ""
88
+ for response in stream:
89
+ if not response.token.text == "</s>":
90
+ output += response.token.text
91
+
92
+ # Check if the exact same request and response already exist in the DataFrame
93
+ existing_record = history_df[(history_df['Request'] == text) & (history_df['Response'] == output)]
94
+
95
+ if existing_record.empty:
96
+ # Add the current interaction to the history DataFrame only if it doesn't exist
97
+ new_row = pd.DataFrame({
98
+ 'Timestamp': [datetime.now()],
99
+ 'Model': [model],
100
+ 'Input Size': [len(text)],
101
+ 'Output Size': [len(output)],
102
+ 'Request': [text],
103
+ 'Response': [output]
104
+ })
105
+ history_df = pd.concat([history_df, new_row], ignore_index=True)
106
+ save_history()
107
+
108
+ return output
109
+
110
+ # Add a list of available voices
111
+ VOICES = [
112
+ "en-US-AriaNeural",
113
+ "en-US-GuyNeural",
114
+ "en-GB-SoniaNeural",
115
+ "en-AU-NatashaNeural",
116
+ "en-CA-ClaraNeural",
117
+ ]
118
+
119
+ async def respond(audio, model, seed, voice):
120
+ user = transcribe(audio)
121
+ reply = models(user, model, seed)
122
+ communicate = edge_tts.Communicate(reply, voice=voice)
123
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
124
+ tmp_path = tmp_file.name
125
+ await communicate.save(tmp_path)
126
+ return tmp_path
127
+
128
+ def display_history():
129
+ df = load_history()
130
+ df['Timestamp'] = df['Timestamp'].astype(str)
131
+ return df
132
+
133
+ def download_history():
134
+ csv_buffer = io.StringIO()
135
+ history_df_copy = history_df.copy()
136
+ history_df_copy['Timestamp'] = history_df_copy['Timestamp'].astype(str)
137
+ history_df_copy.to_csv(csv_buffer, index=False)
138
+ csv_string = csv_buffer.getvalue()
139
+ b64 = base64.b64encode(csv_string.encode()).decode()
140
+ href = f'data:text/csv;base64,{b64}'
141
+ return gr.HTML(f'<a href="{href}" download="chat_history.csv">Download Chat History</a>')
142
+
143
+ DESCRIPTION = """# <center>Dr. Nova Quantum⚡ - Your Personal Guide to the Frontiers of Science and Technology</center>"""
144
+
145
+ with gr.Blocks(css="style.css") as demo:
146
+ gr.Markdown(DESCRIPTION)
147
+ with gr.Row():
148
+ select = gr.Dropdown([
149
+ 'Llama 3 8B',
150
+ 'Mixtral 8x7B',
151
+ 'Mistral 7B v0.3',
152
+ 'Phi 3 mini',
153
+ ],
154
+ value="Llama 3 8B",
155
+ label="Model"
156
+ )
157
+ seed = gr.Slider(
158
+ label="Seed",
159
+ minimum=0,
160
+ maximum=999999,
161
+ step=1,
162
+ value=0,
163
+ visible=False
164
+ )
165
+ voice_select = gr.Dropdown(
166
+ choices=VOICES,
167
+ value=VOICES[0],
168
+ label="Dr. Nova Quantum's Voice"
169
+ )
170
+
171
+ input_audio = gr.Audio(label="User", sources="microphone", type="filepath")
172
+ output_audio = gr.Audio(label="Dr. Nova Quantum", type="filepath", autoplay=True)
173
+
174
+ request_md = gr.Markdown(label="User Request")
175
+ response_md = gr.Markdown(label="Dr. Nova Quantum Response")
176
+
177
+ history_display = gr.DataFrame(label="Conversation History", headers=["Timestamp", "Model", "Input Size", "Output Size", "Request", "Response"])
178
+
179
+ download_button = gr.Button("Download Conversation History")
180
+ download_link = gr.HTML()
181
+
182
+ def process_audio(audio, model, seed, voice):
183
+ response = asyncio.run(respond(audio, model, seed, voice))
184
+ text = transcribe(audio)
185
+ return response, display_history(), text, models(text, model, seed)
186
+
187
+ input_audio.change(
188
+ fn=process_audio,
189
+ inputs=[input_audio, select, seed, voice_select],
190
+ outputs=[output_audio, history_display, request_md, response_md]
191
+ )
192
+
193
+ download_button.click(fn=download_history, outputs=[download_link])
194
+
195
+ demo.load(fn=display_history, outputs=[history_display])
196
+
197
+ if __name__ == "__main__":
198
+ load_history()
199
+ demo.queue(max_size=200).launch()