awacke1 commited on
Commit
eca81ab
1 Parent(s): 432742d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +373 -0
app.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 process text with selected model
134
+ def process_text(user_name, text_input, selected_model, temp_values):
135
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
136
+ st.session_state.messages.append({"user": user_name, "message": text_input, "timestamp": timestamp})
137
+
138
+ with st.chat_message(user_name):
139
+ st.markdown(f"{user_name} ({timestamp}): {text_input}")
140
+
141
+ with st.chat_message("Assistant"):
142
+ if selected_model == "GPT-4o":
143
+ completion = client.chat.completions.create(
144
+ model=GPT4O_MODEL,
145
+ messages=[
146
+ {"role": "user", "content": m["message"]}
147
+ for m in st.session_state.messages
148
+ ],
149
+ stream=True,
150
+ temperature=temp_values
151
+ )
152
+ return_text = st.write_stream(completion)
153
+ else:
154
+ try:
155
+ stream = hf_client.chat.completions.create(
156
+ model=model_links[selected_model],
157
+ messages=[
158
+ {"role": m["role"], "content": m["content"]}
159
+ for m in st.session_state.messages
160
+ ],
161
+ temperature=temp_values,
162
+ stream=True,
163
+ max_tokens=3000,
164
+ )
165
+ return_text = st.write_stream(stream)
166
+ except Exception as e:
167
+ return_text = f"Error: {str(e)}"
168
+ st.error(return_text)
169
+
170
+ st.markdown(f"Assistant ({timestamp}): {return_text}")
171
+ filename = generate_filename(text_input, "md")
172
+ create_file(filename, text_input, return_text, user_name, timestamp)
173
+ st.session_state.messages.append({"user": "Assistant", "message": return_text, "timestamp": timestamp})
174
+ save_data()
175
+
176
+ # Function to process image (using GPT-4o)
177
+ def process_image(user_name, image_input, user_prompt):
178
+ image = Image.open(BytesIO(image_input))
179
+ base64_image = base64.b64encode(image_input).decode("utf-8")
180
+
181
+ response = client.chat.completions.create(
182
+ model=GPT4O_MODEL,
183
+ messages=[
184
+ {"role": "system", "content": "You are a helpful assistant that responds in Markdown."},
185
+ {"role": "user", "content": [
186
+ {"type": "text", "text": user_prompt},
187
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
188
+ ]}
189
+ ],
190
+ temperature=0.0,
191
+ )
192
+ image_response = response.choices[0].message.content
193
+
194
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
195
+ st.session_state.messages.append({"user": user_name, "message": image_response, "timestamp": timestamp})
196
+
197
+ with st.chat_message(user_name):
198
+ st.image(image)
199
+ st.markdown(f"{user_name} ({timestamp}): {user_prompt}")
200
+
201
+ with st.chat_message("Assistant"):
202
+ st.markdown(image_response)
203
+
204
+ filename_md = generate_filename(user_prompt, "md")
205
+ create_file(filename_md, user_prompt, image_response, user_name, timestamp)
206
+ save_data()
207
+ return image_response
208
+
209
+ # Function to process audio (using GPT-4o for transcription)
210
+ def process_audio(user_name, audio_input, text_input):
211
+ if audio_input:
212
+ transcription = client.audio.transcriptions.create(
213
+ model="whisper-1",
214
+ file=audio_input,
215
+ )
216
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
217
+ st.session_state.messages.append({"user": user_name, "message": transcription.text, "timestamp": timestamp})
218
+ with st.chat_message(user_name):
219
+ st.markdown(f"{user_name} ({timestamp}): {transcription.text}")
220
+ with st.chat_message("Assistant"):
221
+ st.markdown(transcription.text)
222
+ filename = generate_filename(transcription.text, "wav")
223
+ create_file(filename, text_input, transcription.text, user_name, timestamp)
224
+ st.session_state.messages.append({"user": "Assistant", "message": transcription.text, "timestamp": timestamp})
225
+ save_data()
226
+
227
+ # Function to process video (using GPT-4o)
228
+ def process_video(user_name, video_input, user_prompt):
229
+ if isinstance(video_input, str):
230
+ with open(video_input, "rb") as video_file:
231
+ video_input = video_file.read()
232
+ base64Frames, audio_path = extract_video_frames(video_input)
233
+ transcript = process_audio_for_video(video_input)
234
+ response = client.chat.completions.create(
235
+ model=GPT4O_MODEL,
236
+ messages=[
237
+ {"role": "system", "content": "You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"},
238
+ {"role": "user", "content": [
239
+ "These are the frames from the video.",
240
+ *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
241
+ {"type": "text", "text": f"The audio transcription is: {transcript}"},
242
+ {"type": "text", "text": user_prompt}
243
+ ]}
244
+ ],
245
+ temperature=0,
246
+ )
247
+ video_response = response.choices[0].message.content
248
+ st.markdown(video_response)
249
+ timestamp = datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S %Z')
250
+ filename_md = generate_filename(user_prompt, "md")
251
+ create_file(filename_md, user_prompt, video_response, user_name, timestamp)
252
+ st.session_state.messages.append({"user": user_name, "message": video_response, "timestamp": timestamp})
253
+ save_data()
254
+ return video_response
255
+
256
+ # Main function for each column
257
+ def main_column(column_name):
258
+ st.markdown(f"##### {column_name}")
259
+ selected_model = st.selectbox(f"Select Model for {column_name}", list(model_links.keys()), key=f"{column_name}_model")
260
+ temp_values = st.slider(f'Select a temperature value for {column_name}', 0.0, 1.0, (0.5), key=f"{column_name}_temp")
261
+
262
+ option = st.selectbox(f"Select an option for {column_name}", ("Text", "Image", "Audio", "Video"), key=f"{column_name}_option")
263
+
264
+ if option == "Text":
265
+ text_input = st.text_input(f"Enter your text for {column_name}:", key=f"{column_name}_text")
266
+ if text_input:
267
+ process_text(st.session_state.current_user['name'], text_input, selected_model, temp_values)
268
+ elif option == "Image":
269
+ text_input = st.text_input(f"Enter text prompt to use with Image context for {column_name}:", key=f"{column_name}_image_text")
270
+ 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")
271
+ for image_input in uploaded_files:
272
+ image_bytes = image_input.read()
273
+ process_
274
+
275
+
276
+
277
+
278
+ process_image(st.session_state.current_user['name'], image_bytes, text_input)
279
+ elif option == "Audio":
280
+ text_input = st.text_input(f"Enter text prompt to use with Audio context for {column_name}:", key=f"{column_name}_audio_text")
281
+ 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")
282
+ for audio_input in uploaded_files:
283
+ process_audio(st.session_state.current_user['name'], audio_input, text_input)
284
+ elif option == "Video":
285
+ video_input = st.file_uploader(f"Upload a video file for {column_name}", type=["mp4"], key=f"{column_name}_video_upload")
286
+ text_input = st.text_input(f"Enter text prompt to use with Video context for {column_name}:", key=f"{column_name}_video_text")
287
+ if video_input and text_input:
288
+ process_video(st.session_state.current_user['name'], video_input, text_input)
289
+
290
+ # Main Streamlit app
291
+ st.title("Personalized Real-Time Chat")
292
+
293
+ # Sidebar
294
+ with st.sidebar:
295
+ st.title("User Info")
296
+ st.write(f"Current User: {st.session_state.current_user['name']}")
297
+ st.write(f"Browser: {st.session_state.current_user['browser']}")
298
+
299
+ new_name = st.text_input("Change your name:")
300
+ if st.button("Update Name"):
301
+ if new_name:
302
+ for user in st.session_state.users:
303
+ if user['id'] == st.session_state.current_user['id']:
304
+ user['name'] = new_name
305
+ st.session_state.current_user['name'] = new_name
306
+ save_data()
307
+ st.success(f"Name updated to {new_name}")
308
+ break
309
+
310
+ st.title("Active Users")
311
+ for user in st.session_state.users:
312
+ st.write(f"{user['name']} ({user['browser']})")
313
+
314
+ if st.button('Reset Chat'):
315
+ reset_conversation()
316
+
317
+ # Create two columns
318
+ col1, col2 = st.columns(2)
319
+
320
+ # Run main function for each column
321
+ with col1:
322
+ main_column("Column 1")
323
+
324
+ with col2:
325
+ main_column("Column 2")
326
+
327
+ # Function to generate filenames
328
+ def generate_filename(prompt, file_type):
329
+ central = pytz.timezone('US/Central')
330
+ safe_date_time = datetime.now(central).strftime("%m%d_%H%M")
331
+ replaced_prompt = prompt.replace(" ", "_").replace("\n", "_")
332
+ safe_prompt = "".join(x for x in replaced_prompt if x.isalnum() or x == "_")[:90]
333
+ return f"{safe_date_time}_{safe_prompt}.{file_type}"
334
+
335
+ # Function to create files
336
+ def create_file(filename, prompt, response, user_name, timestamp):
337
+ with open(filename, "w", encoding="utf-8") as f:
338
+ f.write(f"User: {user_name}\nTimestamp: {timestamp}\n\nPrompt:\n{prompt}\n\nResponse:\n{response}")
339
+
340
+ # Function to extract video frames
341
+ def extract_video_frames(video_path, seconds_per_frame=2):
342
+ base64Frames = []
343
+ video = cv2.VideoCapture(video_path)
344
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
345
+ fps = video.get(cv2.CAP_PROP_FPS)
346
+ frames_to_skip = int(fps * seconds_per_frame)
347
+ curr_frame = 0
348
+ while curr_frame < total_frames - 1:
349
+ video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
350
+ success, frame = video.read()
351
+ if not success:
352
+ break
353
+ _, buffer = cv2.imencode(".jpg", frame)
354
+ base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
355
+ curr_frame += frames_to_skip
356
+ video.release()
357
+ return base64Frames, None
358
+
359
+ # Function to process audio for video
360
+ def process_audio_for_video(video_input):
361
+ try:
362
+ transcription = client.audio.transcriptions.create(
363
+ model="whisper-1",
364
+ file=video_input,
365
+ )
366
+ return transcription.text
367
+ except:
368
+ return ''
369
+
370
+ # Run the Streamlit app
371
+ if __name__ == "__main__":
372
+ st.markdown("*Generated content may be inaccurate or false.*")
373
+ st.markdown("\n...")