awacke1 commited on
Commit
3434741
1 Parent(s): 74cdfaf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +393 -0
app.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import time
3
+ import random
4
+ import json
5
+ from datetime import datetime
6
+ import pytz
7
+ import platform
8
+ import uuid
9
+ import extra_streamlit_components as stx
10
+ from io import BytesIO
11
+ from PIL import Image
12
+ import base64
13
+ import cv2
14
+ import requests
15
+ from moviepy.editor import VideoFileClip
16
+ from gradio_client import Client
17
+ from openai import OpenAI
18
+ import openai
19
+ import os
20
+ from collections import deque
21
+ import numpy as np
22
+ from dotenv import load_dotenv
23
+
24
+ # Load environment variables
25
+ load_dotenv()
26
+
27
+ # Set page config
28
+ st.set_page_config(page_title="Personalized Real-Time Chat", page_icon="💬", layout="wide")
29
+
30
+ # Initialize cookie manager
31
+ cookie_manager = stx.CookieManager()
32
+
33
+ # File to store chat history and user data
34
+ CHAT_FILE = "chat_history.txt"
35
+
36
+ # Function to save chat history and user data to file
37
+ def save_data():
38
+ with open(CHAT_FILE, 'w') as f:
39
+ json.dump({
40
+ 'messages': st.session_state.messages,
41
+ 'users': st.session_state.users
42
+ }, f)
43
+
44
+ # Function to load chat history and user data from file
45
+ def load_data():
46
+ try:
47
+ with open(CHAT_FILE, 'r') as f:
48
+ data = json.load(f)
49
+ st.session_state.messages = data['messages']
50
+ st.session_state.users = data['users']
51
+ except FileNotFoundError:
52
+ st.session_state.messages = []
53
+ st.session_state.users = []
54
+
55
+ # Load data at the start
56
+ load_data()
57
+
58
+ # Function to get or create user
59
+ def get_or_create_user():
60
+ user_id = cookie_manager.get(cookie='user_id')
61
+ if not user_id:
62
+ user_id = str(uuid.uuid4())
63
+ cookie_manager.set('user_id', user_id)
64
+
65
+ user = next((u for u in st.session_state.users if u['id'] == user_id), None)
66
+ if not user:
67
+ user = {
68
+ 'id': user_id,
69
+ 'name': random.choice(['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Henry']),
70
+ 'browser': f"{platform.system()} - {st.session_state.get('browser_info', 'Unknown')}"
71
+ }
72
+ st.session_state.users.append(user)
73
+ save_data()
74
+
75
+ return user
76
+
77
+ # Initialize session state
78
+ if 'messages' not in st.session_state:
79
+ st.session_state.messages = []
80
+ if 'users' not in st.session_state:
81
+ st.session_state.users = []
82
+ if 'current_user' not in st.session_state:
83
+ st.session_state.current_user = get_or_create_user()
84
+
85
+ # Initialize OpenAI client
86
+ openai.api_key = os.getenv('OPENAI_API_KEY')
87
+ openai.organization = os.getenv('OPENAI_ORG_ID')
88
+ client = OpenAI(api_key=openai.api_key, organization=openai.organization)
89
+ GPT4O_MODEL = "gpt-4o-2024-05-13"
90
+
91
+ # Initialize HuggingFace client
92
+ hf_client = OpenAI(
93
+ base_url="https://api-inference.huggingface.co/v1",
94
+ api_key=os.environ.get('API_KEY')
95
+ )
96
+
97
+ # Create supported models
98
+ model_links = {
99
+ "GPT-4o": GPT4O_MODEL,
100
+ "Meta-Llama-3.1-70B-Instruct": "meta-llama/Meta-Llama-3.1-70B-Instruct",
101
+ "Meta-Llama-3.1-405B-Instruct-FP8": "meta-llama/Meta-Llama-3.1-405B-Instruct-FP8",
102
+ "Meta-Llama-3.1-405B-Instruct": "meta-llama/Meta-Llama-3.1-405B-Instruct",
103
+ "Meta-Llama-3.1-8B-Instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct",
104
+ "Meta-Llama-3-70B-Instruct": "meta-llama/Meta-Llama-3-70B-Instruct",
105
+ "Meta-Llama-3-8B-Instruct": "meta-llama/Meta-Llama-3-8B-Instruct",
106
+ "C4ai-command-r-plus": "CohereForAI/c4ai-command-r-plus",
107
+ "Aya-23-35B": "CohereForAI/aya-23-35B",
108
+ "Zephyr-orpo-141b-A35b-v0.1": "HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
109
+ "Mixtral-8x7B-Instruct-v0.1": "mistralai/Mixtral-8x7B-Instruct-v0.1",
110
+ "Codestral-22B-v0.1": "mistralai/Codestral-22B-v0.1",
111
+ "Nous-Hermes-2-Mixtral-8x7B-DPO": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
112
+ "Yi-1.5-34B-Chat": "01-ai/Yi-1.5-34B-Chat",
113
+ "Gemma-2-27b-it": "google/gemma-2-27b-it",
114
+ "Meta-Llama-2-70B-Chat-HF": "meta-llama/Llama-2-70b-chat-hf",
115
+ "Meta-Llama-2-7B-Chat-HF": "meta-llama/Llama-2-7b-chat-hf",
116
+ "Meta-Llama-2-13B-Chat-HF": "meta-llama/Llama-2-13b-chat-hf",
117
+ "Mistral-7B-Instruct-v0.1": "mistralai/Mistral-7B-Instruct-v0.1",
118
+ "Mistral-7B-Instruct-v0.2": "mistralai/Mistral-7B-Instruct-v0.2",
119
+ "Mistral-7B-Instruct-v0.3": "mistralai/Mistral-7B-Instruct-v0.3",
120
+ "Gemma-1.1-7b-it": "google/gemma-1.1-7b-it",
121
+ "Gemma-1.1-2b-it": "google/gemma-1.1-2b-it",
122
+ "Zephyr-7B-Beta": "HuggingFaceH4/zephyr-7b-beta",
123
+ "Zephyr-7B-Alpha": "HuggingFaceH4/zephyr-7b-alpha",
124
+ "Phi-3-mini-128k-instruct": "microsoft/Phi-3-mini-128k-instruct",
125
+ "Phi-3-mini-4k-instruct": "microsoft/Phi-3-mini-4k-instruct",
126
+ }
127
+
128
+ # Function to reset conversation
129
+ def reset_conversation():
130
+ st.session_state.conversation = []
131
+ st.session_state.messages = []
132
+
133
+ # Function to generate filenames
134
+ def generate_filename(prompt, file_type):
135
+ central = pytz.timezone('US/Central')
136
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
137
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
138
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
139
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
140
+
141
+ # Function to create files
142
+ def create_file(filename, prompt, response, user_name, timestamp):
143
+ with open(filename, "w", encoding="utf-8") as f:
144
+ f.write(f"User: {user_name}\nTimestamp: {timestamp}\n\nPrompt:\n{prompt}\n\nResponse:\n{response}")
145
+
146
+ # Function to extract video frames
147
+ def extract_video_frames(video_path, seconds_per_frame=2):
148
+ base64Frames = []
149
+ video = cv2.VideoCapture(video_path)
150
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
151
+ fps = video.get(cv2.CAP_PROP_FPS)
152
+ frames_to_skip = int(fps * seconds_per_frame)
153
+ curr_frame = 0
154
+ while curr_frame < total_frames - 1:
155
+ video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
156
+ success, frame = video.read()
157
+ if not success:
158
+ break
159
+ _, buffer = cv2.imencode(".jpg", frame)
160
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
161
+ curr_frame += frames_to_skip
162
+ video.release()
163
+ return base64Frames, None
164
+
165
+ # Function to process audio for video
166
+ def process_audio_for_video(video_input):
167
+ try:
168
+ transcription = client.audio.transcriptions.create(
169
+ model="whisper-1",
170
+ file=video_input,
171
+ )
172
+ return transcription.text
173
+ except:
174
+ return ''
175
+
176
+ # Function to process text with selected model
177
+ def process_text(user_name, text_input, selected_model, temp_values):
178
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
179
+ st.session_state.messages.append({"user": user_name, "message": text_input, "timestamp": timestamp})
180
+
181
+ with st.chat_message(user_name):
182
+ st.markdown(f"{user_name} ({timestamp}): {text_input}")
183
+
184
+ with st.chat_message("Assistant"):
185
+ try:
186
+ if selected_model == "GPT-4o":
187
+ completion = client.chat.completions.create(
188
+ model=GPT4O_MODEL,
189
+ messages=[
190
+ {"role": "user", "content": m["message"]}
191
+ for m in st.session_state.messages
192
+ ],
193
+ stream=True,
194
+ temperature=temp_values
195
+ )
196
+ return_text = st.write_stream(completion)
197
+ else:
198
+ messages = [
199
+ {"content": m["message"]}
200
+ for m in st.session_state.messages
201
+ ]
202
+ stream = hf_client.chat.completions.create(
203
+ model=model_links[selected_model],
204
+ messages=messages,
205
+ temperature=temp_values,
206
+ stream=True,
207
+ max_tokens=3000,
208
+ )
209
+ return_text = st.write_stream(stream)
210
+ except openai.APIError as e:
211
+ return_text = f"OpenAI API Error: {str(e)}"
212
+ st.error(return_text)
213
+ except requests.exceptions.RequestException as e:
214
+ return_text = f"Network Error: {str(e)}"
215
+ st.error(return_text)
216
+ except Exception as e:
217
+ return_text = f"Unexpected Error: {str(e)}"
218
+ st.error(return_text)
219
+
220
+ if not return_text.startswith("Error:"):
221
+ st.markdown(f"Assistant ({timestamp}): {return_text}")
222
+ filename = generate_filename(text_input, "md")
223
+ create_file(filename, text_input, return_text, user_name, timestamp)
224
+ st.session_state.messages.append({"user": "Assistant", "message": return_text, "timestamp": timestamp})
225
+ save_data()
226
+
227
+ return return_text
228
+
229
+ # Function to process image (using GPT-4o)
230
+ def process_image(user_name, image_input, user_prompt):
231
+ image = Image.open(BytesIO(image_input))
232
+ base64_image = base64.b64encode(image_input).decode("utf-8")
233
+
234
+ response = client.chat.completions.create(
235
+ model=GPT4O_MODEL,
236
+ messages=[
237
+ {"role": "system", "content": "You are a helpful assistant that responds in Markdown."},
238
+ {"role": "user", "content": [
239
+ {"type": "text", "text": user_prompt},
240
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
241
+ ]}
242
+ ],
243
+ temperature=0.0,
244
+ )
245
+ image_response = response.choices[0].message.content
246
+
247
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
248
+ st.session_state.messages.append({"user": user_name, "message": image_response, "timestamp": timestamp})
249
+
250
+ with st.chat_message(user_name):
251
+ st.image(image)
252
+ st.markdown(f"{user_name} ({timestamp}): {user_prompt}")
253
+
254
+ with st.chat_message("Assistant"):
255
+ st.markdown(image_response)
256
+
257
+ filename_md = generate_filename(user_prompt, "md")
258
+ create_file(filename_md, user_prompt, image_response, user_name, timestamp)
259
+ save_data()
260
+ return image_response
261
+
262
+ # Function to process audio (using GPT-4o for transcription)
263
+ def process_audio(user_name, audio_input, text_input):
264
+ if audio_input:
265
+ transcription = client.audio.transcriptions.create(
266
+ model="whisper-1",
267
+ file=audio_input,
268
+ )
269
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
270
+ st.session_state.messages.append({"user": user_name, "message": transcription.text, "timestamp": timestamp})
271
+ with st.chat_message(user_name):
272
+ st.markdown(f"{user_name} ({timestamp}): {transcription.text}")
273
+ with st.chat_message("Assistant"):
274
+ st.markdown(transcription.text)
275
+ filename = generate_filename(transcription.text, "wav")
276
+ create_file(filename, text_input, transcription.text, user_name, timestamp)
277
+ st.session_state.messages.append({"user": "Assistant", "message": transcription.text, "timestamp": timestamp})
278
+ save_data()
279
+ return transcription.text
280
+
281
+ # Function to process video (using GPT-4o)
282
+ def process_video(user_name, video_input, user_prompt):
283
+ if isinstance(video_input, str):
284
+ with open(video_input, "rb") as video_file:
285
+ video_input = video_file.read()
286
+ base64Frames, audio_path = extract_video_frames(video_input)
287
+ transcript = process_audio_for_video(video_input)
288
+ response = client.chat.completions.create(
289
+ model=GPT4O_MODEL,
290
+ messages=[
291
+ {"role": "system", "content": "You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"},
292
+ {"role": "user", "content": [
293
+ "These are the frames from the video.",
294
+ *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
295
+ {"type": "text", "text": f"The audio transcription is: {transcript}"},
296
+ {"type": "text", "text": user_prompt}
297
+ ]}
298
+ ],
299
+ temperature=0,
300
+ )
301
+ video_response = response.choices[0].message.content
302
+ st.markdown(video_response)
303
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
304
+ filename_md = generate_filename(user_prompt, "md")
305
+ create_file(filename_md, user_prompt, video_response, user_name, timestamp)
306
+ st.session_state.messages.append({"user": user_name, "message": video_response, "timestamp": timestamp})
307
+ save_data()
308
+ return video_response
309
+
310
+ # Main function for each column
311
+ def main_column(column_name):
312
+ st.markdown(f"##### {column_name}")
313
+ selected_model = st.selectbox(f"Select Model for {column_name}", list(model_links.keys()), key=f"{column_name}_model")
314
+ temp_values = st.slider(f'Select a temperature value for {column_name}', 0.0, 1.0, (0.5), key=f"{column_name}_temp")
315
+
316
+ option = st.selectbox(f"Select an option for {column_name}", ("Text", "Image", "Audio", "Video"), key=f"{column_name}_option")
317
+
318
+ if option == "Text":
319
+ text_input = st.text_input(f"Enter your text for {column_name}:", key=f"{column_name}_text")
320
+ if st.button(f"Process Text for {column_name}"):
321
+ if text_input:
322
+ process_text(st.session_state.current_user['name'], text_input, selected_model, temp_values)
323
+ # Clear the input after processing
324
+ st.session_state[f"{column_name}_text"] = ""
325
+ elif option == "Image":
326
+ text_input = st.text_input(f"Enter text prompt to use with Image context for {column_name}:", key=f"{column_name}_image_text")
327
+ uploaded_files = st.file_uploader(f"Upload images for {column_name}", type=["png", "jpg", "jpeg"], accept_multiple_files=True, key=f"{column_name}_image_upload")
328
+ if st.button(f"Process Image for {column_name}"):
329
+ for image_input in uploaded_files:
330
+ image_bytes = image_input.read()
331
+ process_image(st.session_state.current_user['name'], image_bytes, text_input)
332
+ # Clear the inputs after processing
333
+ st.session_state[f"{column_name}_image_text"] = ""
334
+ st.session_state[f"{column_name}_image_upload"] = None
335
+ elif option == "Audio":
336
+ text_input = st.text_input(f"Enter text prompt to use with Audio context for {column_name}:", key=f"{column_name}_audio_text")
337
+ uploaded_files = st.file_uploader(f"Upload an audio file for {column_name}", type=["mp3", "wav"], accept_multiple_files=True, key=f"{column_name}_audio_upload")
338
+ if st.button(f"Process Audio for {column_name}"):
339
+ for audio_input in uploaded_files:
340
+ process_audio(st.session_state.current_user['name'], audio_input, text_input)
341
+ # Clear the inputs after processing
342
+ st.session_state[f"{column_name}_audio_text"] = ""
343
+ st.session_state[f"{column_name}_audio_upload"] = None
344
+ elif option == "Video":
345
+ video_input = st.file_uploader(f"Upload a video file for {column_name}", type=["mp4"], key=f"{column_name}_video_upload")
346
+ text_input = st.text_input(f"Enter text prompt to use with Video context for {column_name}:", key=f"{column_name}_video_text")
347
+ if st.button(f"Process Video for {column_name}"):
348
+ if video_input and text_input:
349
+ process_video(st.session_state.current_user['name'], video_input, text_input)
350
+ # Clear the inputs after processing
351
+ st.session_state[f"{column_name}_video_text"] = ""
352
+ st.session_state[f"{column_name}_video_upload"] = None
353
+
354
+ # Main Streamlit app
355
+ st.title("Personalized Real-Time Chat")
356
+
357
+ # Sidebar
358
+ with st.sidebar:
359
+ st.title("User Info")
360
+ st.write(f"Current User: {st.session_state.current_user['name']}")
361
+ st.write(f"Browser: {st.session_state.current_user['browser']}")
362
+
363
+ new_name = st.text_input("Change your name:")
364
+ if st.button("Update Name"):
365
+ if new_name:
366
+ for user in st.session_state.users:
367
+ if user['id'] == st.session_state.current_user['id']:
368
+ user['name'] = new_name
369
+ st.session_state.current_user['name'] = new_name
370
+ save_data()
371
+ st.success(f"Name updated to {new_name}")
372
+ break
373
+
374
+ st.title("Active Users")
375
+ for user in st.session_state.users:
376
+ st.write(f"{user['name']} ({user['browser']})")
377
+
378
+ if st.button('Reset Chat'):
379
+ reset_conversation()
380
+
381
+ # Create two columns
382
+ col1, col2 = st.columns(2)
383
+
384
+ # Run main function for each column
385
+ with col1:
386
+ main_column("Column 1")
387
+
388
+ with col2:
389
+ main_column("Column 2")
390
+
391
+ # Run the Streamlit app
392
+ if __name__ == "__main__":
393
+ st.markdown("\n[by Aaron Wacker](https://huggingface.co/spaces/awacke1/).")