-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
277 lines (206 loc) · 10.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import streamlit as st
import streamlit.components.v1 as components
import os
import re
from emotion import GET_EMOTION
from backend import generate_transcript, get_intervals, get_text_from_gpt, get_clippings_from_intervals, get_summary_and_title_from_gpt
# from tlabs import transcript, get_transcript
from constants import *
from video import GET_TRIMMED_VIDEO
import moviepy.editor as mp
from st_social_media_links import SocialMediaIcons
from feedback import FEEDBACK
from openai import OpenAI
# Initialize session state variable if it doesn't exist
if 'refresh' not in st.session_state:
st.session_state.refresh = 0
# Function to increment the state
def refresh_state():
st.session_state.refresh += 1
def centered_spinner(text):
text_placeholder = st.empty()
return text_placeholder.markdown(
f"""
<div style="display: flex; justify-content: center; align-items: center; height: 200px;">
<div>
<h2 style="text-align: center;">{text}</h2>
<div style="display: flex; justify-content: center;">
<div class="loader"></div>
</div>
</div>
</div>
<style>
.loader {{
border: 8px solid #f3f3f3; /* Light grey */
border-top: 8px solid #3498db; /* Blue */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 2s linear infinite;
}}
@keyframes spin {{
0% {{ transform: rotate(0deg); }}
100% {{ transform: rotate(360deg); }}
}}
</style>
""",
unsafe_allow_html=True,
)
st.set_page_config(page_title="AISR", page_icon="🏀")
col1, col2 = st.columns([1, 6]) # Adjust the ratio as needed
# Add the image in the first column
with col1:
st.image('sports_logo.png', width=100) # Adjust width as needed
# Add the title in the second column
with col2:
st.title('AI Sports Recap')
# Create a text input field for the URL
url_input = st.text_input('Enter a URL:', '')
st.write('OR')
selected_option = st.selectbox('Select an option:', video_names)
# # Create a text area for additional text input
# text_input = st.text_area('Enter Your Question:')
# # Create a submit button
# submit_button = st.button('Submit')
st.write(" ")
st.write(" ")
value = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=value)
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-4o"
if "messages" not in st.session_state:
st.session_state.messages = []
for message in st.session_state.messages:
with st.chat_message(message["role"]):
A = st.markdown(message["content"], unsafe_allow_html=True)
if prompt := st.chat_input("What is up?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
B = st.markdown(prompt, unsafe_allow_html=True)
with st.chat_message("assistant"):
idx = video_names.index(selected_option)
video_id = video_details[idx]["video_id"]
index_id = os.environ.get("INDEX_ID")
transcript_string = generate_transcript(index_id, video_id)
# gpt_content = get_text_from_gpt(prompt, transcript_string)
# final_clippings = get_intervals(gpt_content)
try:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are the best sports editor who understands all sports very intricately. You are capable of summarizing text by picking the right sentences from a list of sentences of interviews. You pick sentences so that the resultant block answers the question asked. You will be given a transcript containing a list of sentences followed by the start time (start=) and end time (end=) of when it occurs in a video. For a selected sentence, also check whether the next sentence in combination with current selected sentence adds more value and context to the answer. If yes, pick both individually."},
{"role": "system", "content": "Each line in your output should be strictly in this format: '<Sentence> | start= | end= \n'."},
{"role": "system", "content": "Just give answer."},
{"role": "system", "content": "DO NOT GET RID OF THE | SYMBOLS AND TIMESTAMPS AT ANY COST."},
{"role": "user", "content": f'''{prompt}
{transcript_string}'''}
],
stream=False,
)
response = stream.choices[0].message.content
final_clippings = get_intervals(response)
except:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are the best sports editor who understands all sports very intricately. You are capable of summarizing text by picking the right sentences from a list of sentences of interviews. You pick sentences so that the resultant block answers the question asked. You will be given a transcript containing a list of sentences followed by the start time (start=) and end time (end=) of when it occurs in a video. For a selected sentence, also check whether the next sentence in combination with current selected sentence adds more value and context to the answer. If yes, pick both individually."},
{"role": "system", "content": "Each line in your output should be strictly in this format: '<Sentence> | start= | end= \n'."},
{"role": "system", "content": "Just give answer."},
{"role": "system", "content": "DO NOT GET RID OF THE | SYMBOLS AT ANY COST."},
{"role": "user", "content": f'''{prompt}
{transcript_string}'''}
],
stream=False,
)
response = stream.choices[0].message.content
final_clippings = get_intervals(response)
clipped_video = get_clippings_from_intervals(video_details[idx]["video_url"], final_clippings)
summarized_content = get_summary_and_title_from_gpt(prompt, transcript_string, video_details[idx]["video_name"])
video_file = open('combined_video.mp4', 'rb')
video_bytes = video_file.read()
C = st.markdown(summarized_content, unsafe_allow_html=True)
D = st.markdown("<h3>Highlights</h3>", unsafe_allow_html=True)
st.video(video_bytes)
def striphtml(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
social_media_links = [
"""
http://www.facebook.com/dialog/feed?
app_id=123050457758183&
link=http://developers.facebook.com/&
caption=Reference%20Documentation&
description=Andy Murray Hints at Retirement Possibilities but Stays Focused on the Present Wimbledon&
message=Andy Murray Hints at Retirement Possibilities but Stays Focused on the Present Wimbledon&
""",
# "https://www.instagram.com/ThisIsAnExampleLink",
f"http://twitter.com/share?text={video_details[idx]['video_name']}&url=http://url goes here&hashtags=hashtag1,hashtag2,hashtag3",
]
social_media_icons = SocialMediaIcons(social_media_links)
social_media_icons.render()
# if st.button('Refresh'):
# A.empty()
# B.empty()
# C.empty()
# D.empty()
# # st.experimental_rerun()
# if st.button('Hard Refresh'):
# # JavaScript to reload the page
# st.write('<script>location.reload()</script>', unsafe_allow_html=True)
st.session_state.messages.append({"role": "assistant", "content": summarized_content})
exit()
# Handle the submit button click
if submit_button:
load_circle = centered_spinner('Please wait... 🕰️👀')
idx = video_names.index(selected_option)
video_id = video_details[idx]["video_id"]
index_id = os.environ.get("INDEX_ID")
transcript_string = generate_transcript(index_id, video_id)
# st.write(transcript_string)
gpt_content = get_text_from_gpt(text_input, transcript_string)
# st.write(gpt_content)
final_clippings = get_intervals(gpt_content)
clipped_video = get_clippings_from_intervals(video_details[idx]["video_url"], final_clippings)
summarized_content = get_summary_and_title_from_gpt(text_input, transcript_string, video_details[idx]["video_name"])
# for i in range(len(transcription_list)):
# st.write(f"Transcription: {transcription_list[i]}")
# st.write(f"Start Time: {start_points[i]}")
# st.write(f"End Time: {end_points[i]}")
# st.write("")
# video = GET_TRIMMED_VIDEO()
# clip = mp.VideoFileClip("Donut (15-Second Ad).mp4")
# clip.audio.write_audiofile("theaudio.mp3")
# clip.close()
# clip = mp.VideoFileClip("combined_video.mp4")
# clip.audio.write_audiofile("theaudio.mp3")
# clip.close()
# emotion = GET_EMOTION()
# st.write(f"Emotion: {emotion}")
load_circle.empty()
video_file = open('combined_video.mp4', 'rb')
video_bytes = video_file.read()
# st.text_area("Summary", value=summarized_content, height=200)
st.markdown("<h3>Summary</h3>", unsafe_allow_html=True)
st.markdown(summarized_content, unsafe_allow_html=True)
# text_to_copy = st.markdown(summarized_content, unsafe_allow_html=True)
# hosted_html_file = "https://everydayswag.org/files/copy.html"
# iframe_url = f"{hosted_html_file}?copy={text_to_copy}"
# st.markdown(f'<iframe src="{iframe_url}"></iframe>', unsafe_allow_html=True)
st.markdown("<h3>Highlights</h3>", unsafe_allow_html=True)
st.video(video_bytes)
social_media_links = [
"""
http://www.facebook.com/dialog/feed?
app_id=123050457758183&
link=http://developers.facebook.com/&
caption=Reference%20Documentation&
description=Andy Murray Hints at Retirement Possibilities but Stays Focused on the Present Wimbledon&
message=Andy Murray Hints at Retirement Possibilities but Stays Focused on the Present Wimbledon&
""",
# "https://www.instagram.com/ThisIsAnExampleLink",
f"http://twitter.com/share?text={gpt_content}&hashtags=hashtag1,hashtag2,hashtag3",
]
social_media_icons = SocialMediaIcons(social_media_links)
social_media_icons.render()
exit()
transcript(index_id, url_input)