Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -5,15 +5,12 @@ import logging
|
|
5 |
import ast
|
6 |
import openai
|
7 |
import os
|
|
|
8 |
import re
|
9 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
10 |
-
from multiprocessing import Pool, cpu_count
|
11 |
|
12 |
logging.basicConfig(filename='youtube_script_extractor.log', level=logging.DEBUG,
|
13 |
format='%(asctime)s - %(levelname)s - %(message)s')
|
14 |
|
15 |
-
openai.api_key = os.getenv("OPENAI_API_KEY")
|
16 |
-
|
17 |
def parse_api_response(response):
|
18 |
try:
|
19 |
if isinstance(response, str):
|
@@ -26,8 +23,30 @@ def parse_api_response(response):
|
|
26 |
except Exception as e:
|
27 |
raise ValueError(f"API μλ΅ νμ± μ€ν¨: {str(e)}")
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
def get_youtube_script(url):
|
30 |
logging.info(f"μ€ν¬λ¦½νΈ μΆμΆ μμ: URL = {url}")
|
|
|
31 |
client = Client("whispersound/YT_Ts_R")
|
32 |
|
33 |
try:
|
@@ -39,48 +58,31 @@ def get_youtube_script(url):
|
|
39 |
|
40 |
title = parsed_result["data"][0]["title"]
|
41 |
transcription_text = parsed_result["data"][0]["transcriptionAsText"]
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
logging.info("μ€ν¬λ¦½νΈ μΆμΆ λ° μ²λ¦¬ μλ£")
|
48 |
-
return title, transcription_text, processed_sections
|
49 |
|
50 |
except Exception as e:
|
51 |
error_msg = f"μ€ν¬λ¦½νΈ μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}"
|
52 |
logging.exception(error_msg)
|
53 |
return "", "", []
|
54 |
|
55 |
-
|
56 |
-
vectorizer = TfidfVectorizer().fit([text1, text2])
|
57 |
-
vectors = vectorizer.transform([text1, text2])
|
58 |
-
similarity = (vectors[0] * vectors[1].T).A[0][0]
|
59 |
-
return similarity > threshold
|
60 |
|
61 |
-
def
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
else:
|
75 |
-
if is_same_topic_tfidf(current_section['text'], section['text']):
|
76 |
-
current_section['end_time'] = section['end_time']
|
77 |
-
current_section['text'] += ' ' + section['text']
|
78 |
-
else:
|
79 |
-
merged_sections.append(current_section)
|
80 |
-
current_section = section.copy()
|
81 |
-
|
82 |
-
merged_sections.append(current_section)
|
83 |
-
return merged_sections
|
84 |
|
85 |
def summarize_section(section_text):
|
86 |
prompt = f"""
|
@@ -92,79 +94,114 @@ def summarize_section(section_text):
|
|
92 |
μΉμ
λ΄μ©:
|
93 |
{section_text}
|
94 |
"""
|
95 |
-
|
96 |
-
response = openai.ChatCompletion.create(
|
97 |
-
model="gpt-4o-mini",
|
98 |
-
messages=[{"role": "user", "content": prompt}],
|
99 |
-
max_tokens=150,
|
100 |
-
temperature=0.3,
|
101 |
-
top_p=0.9
|
102 |
-
)
|
103 |
-
return response['choices'][0]['message']['content']
|
104 |
-
except Exception as e:
|
105 |
-
logging.exception("μμ½ μμ± μ€ μ€λ₯ λ°μ")
|
106 |
-
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€."
|
107 |
-
|
108 |
-
def process_section(section):
|
109 |
-
summary = summarize_section(section['text'])
|
110 |
-
return {
|
111 |
-
'start_time': section['start_time'],
|
112 |
-
'end_time': section['end_time'],
|
113 |
-
'summary': summary
|
114 |
-
}
|
115 |
-
|
116 |
-
def process_merged_sections_parallel(merged_sections):
|
117 |
-
with Pool(processes=cpu_count()) as pool:
|
118 |
-
return pool.map(process_section, merged_sections)
|
119 |
|
120 |
def format_time(seconds):
|
121 |
minutes, seconds = divmod(seconds, 60)
|
122 |
hours, minutes = divmod(minutes, 60)
|
123 |
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
|
124 |
|
125 |
-
def generate_timeline_summary(
|
126 |
timeline_summary = ""
|
127 |
-
for i, section in enumerate(
|
128 |
start_time = format_time(section['start_time'])
|
129 |
-
|
130 |
-
timeline_summary += f"{start_time}
|
131 |
return timeline_summary
|
132 |
|
133 |
-
def
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
with gr.Blocks() as demo:
|
148 |
gr.Markdown("## YouTube μ€ν¬λ¦½νΈ μΆμΆ λ° μμ½ λꡬ")
|
149 |
|
150 |
youtube_url_input = gr.Textbox(label="YouTube URL μ
λ ₯")
|
151 |
analyze_button = gr.Button("λΆμνκΈ°")
|
152 |
-
|
|
|
|
|
153 |
|
154 |
-
cached_data = gr.State({"url": "", "title": "", "script": "", "
|
155 |
|
156 |
-
def
|
157 |
if url == cache["url"]:
|
158 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
163 |
|
164 |
analyze_button.click(
|
165 |
analyze,
|
166 |
inputs=[youtube_url_input, cached_data],
|
167 |
-
outputs=[
|
|
|
|
|
|
|
|
|
168 |
)
|
169 |
|
170 |
demo.launch(share=True)
|
|
|
5 |
import ast
|
6 |
import openai
|
7 |
import os
|
8 |
+
import random
|
9 |
import re
|
|
|
|
|
10 |
|
11 |
logging.basicConfig(filename='youtube_script_extractor.log', level=logging.DEBUG,
|
12 |
format='%(asctime)s - %(levelname)s - %(message)s')
|
13 |
|
|
|
|
|
14 |
def parse_api_response(response):
|
15 |
try:
|
16 |
if isinstance(response, str):
|
|
|
23 |
except Exception as e:
|
24 |
raise ValueError(f"API μλ΅ νμ± μ€ν¨: {str(e)}")
|
25 |
|
26 |
+
def split_sentences(text):
|
27 |
+
sentences = re.split(r"(λλ€|μμ|ꡬλ|ν΄μ|κ΅°μ|κ² μ΄μ|μμ€|ν΄λΌ|μμ|μμ|λ°μ|λμ|μΈμ|μ΄μ|κ²μ|ꡬμ|κ³ μ|λμ|νμ£ )(?![\w])", text)
|
28 |
+
combined_sentences = []
|
29 |
+
current_sentence = ""
|
30 |
+
for i in range(0, len(sentences), 2):
|
31 |
+
if i + 1 < len(sentences):
|
32 |
+
sentence = sentences[i] + sentences[i + 1]
|
33 |
+
else:
|
34 |
+
sentence = sentences[i]
|
35 |
+
if len(current_sentence) + len(sentence) > 100:
|
36 |
+
combined_sentences.append(current_sentence.strip())
|
37 |
+
current_sentence = sentence.strip()
|
38 |
+
else:
|
39 |
+
current_sentence += sentence
|
40 |
+
if sentence.endswith(('.', '?', '!')):
|
41 |
+
combined_sentences.append(current_sentence.strip())
|
42 |
+
current_sentence = ""
|
43 |
+
if current_sentence:
|
44 |
+
combined_sentences.append(current_sentence.strip())
|
45 |
+
return combined_sentences
|
46 |
+
|
47 |
def get_youtube_script(url):
|
48 |
logging.info(f"μ€ν¬λ¦½νΈ μΆμΆ μμ: URL = {url}")
|
49 |
+
|
50 |
client = Client("whispersound/YT_Ts_R")
|
51 |
|
52 |
try:
|
|
|
58 |
|
59 |
title = parsed_result["data"][0]["title"]
|
60 |
transcription_text = parsed_result["data"][0]["transcriptionAsText"]
|
61 |
+
sections = parsed_result["data"][0]["sections"]
|
62 |
+
|
63 |
+
logging.info("μ€ν¬λ¦½νΈ μΆμΆ μλ£")
|
64 |
+
return title, transcription_text, sections
|
|
|
|
|
|
|
65 |
|
66 |
except Exception as e:
|
67 |
error_msg = f"μ€ν¬λ¦½νΈ μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}"
|
68 |
logging.exception(error_msg)
|
69 |
return "", "", []
|
70 |
|
71 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
|
|
|
72 |
|
73 |
+
def call_api(prompt, max_tokens, temperature, top_p):
|
74 |
+
try:
|
75 |
+
response = openai.ChatCompletion.create(
|
76 |
+
model="gpt-4o-mini",
|
77 |
+
messages=[{"role": "user", "content": prompt}],
|
78 |
+
max_tokens=max_tokens,
|
79 |
+
temperature=temperature,
|
80 |
+
top_p=top_p
|
81 |
+
)
|
82 |
+
return response['choices'][0]['message']['content']
|
83 |
+
except Exception as e:
|
84 |
+
logging.exception("LLM API νΈμΆ μ€ μ€λ₯ λ°μ")
|
85 |
+
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€. λμ€μ λ€μ μλν΄ μ£ΌμΈμ."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
def summarize_section(section_text):
|
88 |
prompt = f"""
|
|
|
94 |
μΉμ
λ΄μ©:
|
95 |
{section_text}
|
96 |
"""
|
97 |
+
return call_api(prompt, max_tokens=150, temperature=0.3, top_p=0.9)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
|
99 |
def format_time(seconds):
|
100 |
minutes, seconds = divmod(seconds, 60)
|
101 |
hours, minutes = divmod(minutes, 60)
|
102 |
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
|
103 |
|
104 |
+
def generate_timeline_summary(sections):
|
105 |
timeline_summary = ""
|
106 |
+
for i, section in enumerate(sections, 1):
|
107 |
start_time = format_time(section['start_time'])
|
108 |
+
summary = summarize_section(section['text'])
|
109 |
+
timeline_summary += f"{start_time} {i}. {summary}\n\n"
|
110 |
return timeline_summary
|
111 |
|
112 |
+
def summarize_text(text):
|
113 |
+
prompt = f"""
|
114 |
+
1. λ€μ μ£Όμ΄μ§λ μ νλΈ λλ³Έμ ν΅μ¬ μ£Όμ μ λͺ¨λ μ£Όμ λ΄μ©μ μμΈνκ² μμ½νλΌ
|
115 |
+
2. λ°λμ νκΈλ‘ μμ±νλΌ
|
116 |
+
3. μμ½λ¬Έλ§μΌλ‘λ μμμ μ§μ μμ²ν κ²κ³Ό λμΌν μμ€μΌλ‘ λ΄μ©μ μ΄ν΄ν μ μλλ‘ μμΈν μμ±
|
117 |
+
4. κΈμ λ무 μμΆνκ±°λ ν¨μΆνμ§ λ§κ³ , μ€μν λ΄μ©κ³Ό μΈλΆμ¬νμ λͺ¨λ ν¬ν¨
|
118 |
+
5. λ°λμ λλ³Έμ νλ¦κ³Ό λ
Όλ¦¬ ꡬ쑰λ₯Ό μ μ§
|
119 |
+
6. λ°λμ μκ° μμλ μ¬κ±΄μ μ κ° κ³Όμ μ λͺ
ννκ² λ°μ
|
120 |
+
7. λ±μ₯μΈλ¬Ό, μ₯μ, μ¬κ±΄ λ± μ€μν μμλ₯Ό μ ννκ² μμ±
|
121 |
+
8. λλ³Έμμ μ λ¬νλ κ°μ μ΄λ λΆμκΈ°λ ν¬ν¨
|
122 |
+
9. λ°λμ κΈ°μ μ μ©μ΄λ μ λ¬Έ μ©μ΄κ° μμ κ²½μ°, μ΄λ₯Ό μ ννκ² μ¬μ©
|
123 |
+
10. λλ³Έμ λͺ©μ μ΄λ μλλ₯Ό νμ
νκ³ , μ΄λ₯Ό μμ½μ λ°λμ λ°μ
|
124 |
+
11. μ 체κΈμ 보κ³
|
125 |
+
|
126 |
+
---
|
127 |
+
|
128 |
+
μ΄ ν둬ννΈκ° λμμ΄ λμκΈΈ λ°λλλ€.
|
129 |
+
\n\n
|
130 |
+
{text}"""
|
131 |
+
|
132 |
+
try:
|
133 |
+
return call_api(prompt, max_tokens=10000, temperature=0.3, top_p=0.9)
|
134 |
+
except Exception as e:
|
135 |
+
logging.exception("μμ½ μμ± μ€ μ€λ₯ λ°μ")
|
136 |
+
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€. λμ€μ λ€μ μλν΄ μ£ΌμΈμ."
|
137 |
|
138 |
with gr.Blocks() as demo:
|
139 |
gr.Markdown("## YouTube μ€ν¬λ¦½νΈ μΆμΆ λ° μμ½ λꡬ")
|
140 |
|
141 |
youtube_url_input = gr.Textbox(label="YouTube URL μ
λ ₯")
|
142 |
analyze_button = gr.Button("λΆμνκΈ°")
|
143 |
+
script_output = gr.HTML(label="μ€ν¬λ¦½νΈ")
|
144 |
+
timeline_output = gr.HTML(label="νμλΌμΈ μμ½")
|
145 |
+
summary_output = gr.HTML(label="μ 체 μμ½")
|
146 |
|
147 |
+
cached_data = gr.State({"url": "", "title": "", "script": "", "sections": []})
|
148 |
|
149 |
+
def extract_and_cache(url, cache):
|
150 |
if url == cache["url"]:
|
151 |
+
return cache["title"], cache["script"], cache["sections"], cache
|
152 |
+
|
153 |
+
title, script, sections = get_youtube_script(url)
|
154 |
+
new_cache = {"url": url, "title": title, "script": script, "sections": sections}
|
155 |
+
return title, script, sections, new_cache
|
156 |
+
|
157 |
+
def display_script(title, script):
|
158 |
+
formatted_script = "\n".join(split_sentences(script))
|
159 |
+
script_html = f"""<h2 style='font-size:24px;'>{title}</h2>
|
160 |
+
<details>
|
161 |
+
<summary><h3>μλ¬Έ μ€ν¬λ¦½νΈ (ν΄λ¦νμ¬ νΌμΉκΈ°)</h3></summary>
|
162 |
+
<div style="white-space: pre-wrap;">{formatted_script}</div>
|
163 |
+
</details>"""
|
164 |
+
return script_html
|
165 |
+
|
166 |
+
def display_timeline(sections):
|
167 |
+
timeline_summary = generate_timeline_summary(sections)
|
168 |
+
timeline_html = f"""
|
169 |
+
<h3>νμλΌμΈ μμ½:</h3>
|
170 |
+
<div style="white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
|
171 |
+
{timeline_summary}
|
172 |
+
</div>
|
173 |
+
"""
|
174 |
+
return timeline_html
|
175 |
+
|
176 |
+
def generate_summary(script):
|
177 |
+
summary = summarize_text(script)
|
178 |
+
summary_html = f"""
|
179 |
+
<h3>μ 체 μμ½:</h3>
|
180 |
+
<div style="white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
|
181 |
+
{summary}
|
182 |
+
</div>
|
183 |
+
"""
|
184 |
+
return summary_html
|
185 |
+
|
186 |
+
def analyze(url, cache):
|
187 |
+
title, script, sections, new_cache = extract_and_cache(url, cache)
|
188 |
+
script_html = display_script(title, script)
|
189 |
+
timeline_html = display_timeline(sections)
|
190 |
+
return script_html, timeline_html, new_cache
|
191 |
|
192 |
+
def update_summary(cache):
|
193 |
+
if not cache["script"]:
|
194 |
+
return "μ€ν¬λ¦½νΈκ° μμ΅λλ€. λ¨Όμ YouTube URLμ μ
λ ₯νκ³ λΆμμ μ€νν΄μ£ΌμΈμ."
|
195 |
+
return generate_summary(cache["script"])
|
196 |
|
197 |
analyze_button.click(
|
198 |
analyze,
|
199 |
inputs=[youtube_url_input, cached_data],
|
200 |
+
outputs=[script_output, timeline_output, cached_data]
|
201 |
+
).then(
|
202 |
+
update_summary,
|
203 |
+
inputs=[cached_data],
|
204 |
+
outputs=summary_output
|
205 |
)
|
206 |
|
207 |
demo.launch(share=True)
|