Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,11 +7,21 @@ import openai
|
|
7 |
import os
|
8 |
import random
|
9 |
import re
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
def parse_api_response(response):
|
17 |
try:
|
@@ -25,50 +35,29 @@ def parse_api_response(response):
|
|
25 |
except Exception as e:
|
26 |
raise ValueError(f"API μλ΅ νμ± μ€ν¨: {str(e)}")
|
27 |
|
28 |
-
def split_sentences(text):
|
29 |
-
sentences = re.split(r"(λλ€|μμ|ꡬλ|ν΄μ|κ΅°μ|κ² μ΄μ|μμ€|ν΄λΌ|μμ|μμ|λ°μ|λμ|μΈμ|μ΄μ|κ²μ|ꡬμ|κ³ μ|λμ|νμ£ )(?![\w])", text)
|
30 |
-
combined_sentences = []
|
31 |
-
current_sentence = ""
|
32 |
-
for i in range(0, len(sentences), 2):
|
33 |
-
if i + 1 < len(sentences):
|
34 |
-
sentence = sentences[i] + sentences[i + 1]
|
35 |
-
else:
|
36 |
-
sentence = sentences[i]
|
37 |
-
if len(current_sentence) + len(sentence) > 100:
|
38 |
-
combined_sentences.append(current_sentence.strip())
|
39 |
-
current_sentence = sentence.strip()
|
40 |
-
else:
|
41 |
-
current_sentence += sentence
|
42 |
-
if sentence.endswith(('.', '?', '!')):
|
43 |
-
combined_sentences.append(current_sentence.strip())
|
44 |
-
current_sentence = ""
|
45 |
-
if current_sentence:
|
46 |
-
combined_sentences.append(current_sentence.strip())
|
47 |
-
return combined_sentences
|
48 |
-
|
49 |
def get_youtube_script(url):
|
50 |
logging.info(f"μ€ν¬λ¦½νΈ μΆμΆ μμ: URL = {url}")
|
51 |
-
|
52 |
client = Client("whispersound/YT_Ts_R")
|
53 |
-
|
54 |
try:
|
55 |
logging.debug("API νΈμΆ μμ")
|
56 |
result = client.predict(youtube_url=url, api_name="/predict")
|
57 |
logging.debug("API νΈμΆ μλ£")
|
58 |
-
|
59 |
parsed_result = parse_api_response(result)
|
60 |
-
|
61 |
title = parsed_result["data"][0]["title"]
|
62 |
-
|
63 |
-
sections = parsed_result["data"][0]["sections"]
|
64 |
-
|
65 |
logging.info("μ€ν¬λ¦½νΈ μΆμΆ μλ£")
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
68 |
except Exception as e:
|
69 |
error_msg = f"μ€ν¬λ¦½νΈ μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}"
|
70 |
logging.exception(error_msg)
|
71 |
-
return "", ""
|
|
|
|
|
|
|
72 |
|
73 |
def call_api(prompt, max_tokens, temperature, top_p):
|
74 |
try:
|
@@ -84,122 +73,117 @@ def call_api(prompt, max_tokens, temperature, top_p):
|
|
84 |
logging.exception("LLM API νΈμΆ μ€ μ€λ₯ λ°μ")
|
85 |
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€. λμ€μ λ€μ μλν΄ μ£ΌμΈμ."
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
def summarize_section(section_text):
|
88 |
-
prompt = f"""
|
89 |
-
λ€μ μ νλΈ λλ³Έ μΉμ
μ ν΅μ¬ λ΄μ©μ κ°κ²°νκ² μμ½νμΈμ:
|
90 |
-
1. νκΈλ‘ μμ±νμΈμ.
|
91 |
-
2. μ£Όμ λ
Όμ κ³Ό μ€μν μΈλΆμ¬νμ ν¬ν¨νμΈμ.
|
92 |
-
3. μμ½μ 2-3λ¬Έμ₯μΌλ‘ μ ννμΈμ.
|
93 |
|
94 |
-
μΉμ
λ΄μ©:
|
95 |
{section_text}
|
96 |
-
"""
|
97 |
-
return call_api(prompt, max_tokens=150, temperature=0.3, top_p=0.9)
|
98 |
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
for
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
summary = summarize_section(section['text'])
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
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 |
-
|
145 |
-
|
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
|
152 |
-
|
153 |
-
title, script
|
154 |
-
|
155 |
-
return title, script, sections, new_cache
|
156 |
|
157 |
def display_script(title, script):
|
158 |
-
|
159 |
-
return "<p>μ€ν¬λ¦½νΈλ₯Ό μΆμΆνμ§ λͺ»νμ΅λλ€. URLμ νμΈνκ³ λ€μ μλν΄ μ£ΌμΈμ.</p>"
|
160 |
-
formatted_script = "\n".join(split_sentences(script))
|
161 |
-
script_html = f"""<h2 style='font-size:24px;'>{title}</h2>
|
162 |
-
<details>
|
163 |
-
<summary><h3>μλ¬Έ μ€ν¬λ¦½νΈ (ν΄λ¦νμ¬ νΌμΉκΈ°)</h3></summary>
|
164 |
-
<div style="white-space: pre-wrap;">{formatted_script}</div>
|
165 |
-
</details>"""
|
166 |
return script_html
|
167 |
|
168 |
-
def
|
169 |
-
if not
|
170 |
-
return "
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
if not script:
|
182 |
-
return "<p>μ 체 μμ½μ μμ±νμ§ λͺ»νμ΅λλ€. μ€ν¬λ¦½νΈ μΆμΆμ μ€ν¨νμ μ μμ΅λλ€.</p>"
|
183 |
-
summary = summarize_text(script)
|
184 |
-
summary_html = f"""
|
185 |
-
<h3>μ 체 μμ½:</h3>
|
186 |
-
<div style="white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
|
187 |
-
{summary}
|
188 |
-
</div>
|
189 |
-
"""
|
190 |
-
return summary_html
|
191 |
-
|
192 |
-
def analyze(url, cache):
|
193 |
-
title, script, sections, new_cache = extract_and_cache(url, cache)
|
194 |
-
script_html = display_script(title, script)
|
195 |
-
timeline_html = display_timeline(sections)
|
196 |
-
summary_html = generate_summary(script)
|
197 |
-
return script_html, timeline_html, summary_html, new_cache
|
198 |
|
199 |
analyze_button.click(
|
200 |
-
|
201 |
-
inputs=[youtube_url_input, cached_data],
|
202 |
-
outputs=[script_output,
|
|
|
|
|
|
|
|
|
203 |
)
|
204 |
|
205 |
demo.launch(share=True)
|
|
|
7 |
import os
|
8 |
import random
|
9 |
import re
|
10 |
+
import nltk
|
11 |
+
import numpy as np
|
12 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
13 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
14 |
+
import urllib.parse
|
15 |
+
|
16 |
+
# nltk λ°μ΄ν° λ€μ΄λ‘λ (μ΅μ΄ ν λ² μ€ν)
|
17 |
+
nltk.download('punkt')
|
18 |
+
|
19 |
+
# λ‘κΉ
μ€μ
|
20 |
+
logging.basicConfig(
|
21 |
+
filename='youtube_script_extractor.log',
|
22 |
+
level=logging.DEBUG,
|
23 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
24 |
+
)
|
25 |
|
26 |
def parse_api_response(response):
|
27 |
try:
|
|
|
35 |
except Exception as e:
|
36 |
raise ValueError(f"API μλ΅ νμ± μ€ν¨: {str(e)}")
|
37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
def get_youtube_script(url):
|
39 |
logging.info(f"μ€ν¬λ¦½νΈ μΆμΆ μμ: URL = {url}")
|
|
|
40 |
client = Client("whispersound/YT_Ts_R")
|
|
|
41 |
try:
|
42 |
logging.debug("API νΈμΆ μμ")
|
43 |
result = client.predict(youtube_url=url, api_name="/predict")
|
44 |
logging.debug("API νΈμΆ μλ£")
|
|
|
45 |
parsed_result = parse_api_response(result)
|
|
|
46 |
title = parsed_result["data"][0]["title"]
|
47 |
+
transcription = parsed_result["data"][0]["transcription"]
|
|
|
|
|
48 |
logging.info("μ€ν¬λ¦½νΈ μΆμΆ μλ£")
|
49 |
+
script_json = json.dumps({
|
50 |
+
"title": title,
|
51 |
+
"transcription": transcription
|
52 |
+
})
|
53 |
+
return title, script_json
|
54 |
except Exception as e:
|
55 |
error_msg = f"μ€ν¬λ¦½νΈ μΆμΆ μ€ μ€λ₯ λ°μ: {str(e)}"
|
56 |
logging.exception(error_msg)
|
57 |
+
return "", ""
|
58 |
+
|
59 |
+
# OpenAI API ν€ μ€μ
|
60 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
61 |
|
62 |
def call_api(prompt, max_tokens, temperature, top_p):
|
63 |
try:
|
|
|
73 |
logging.exception("LLM API νΈμΆ μ€ μ€λ₯ λ°μ")
|
74 |
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€. λμ€μ λ€μ μλν΄ μ£ΌμΈμ."
|
75 |
|
76 |
+
def extract_video_id(url):
|
77 |
+
parsed_url = urllib.parse.urlparse(url)
|
78 |
+
if parsed_url.hostname in ('www.youtube.com', 'youtube.com'):
|
79 |
+
query_params = urllib.parse.parse_qs(parsed_url.query)
|
80 |
+
return query_params.get('v', [None])[0]
|
81 |
+
elif parsed_url.hostname == 'youtu.be':
|
82 |
+
return parsed_url.path[1:]
|
83 |
+
else:
|
84 |
+
return None
|
85 |
+
|
86 |
def summarize_section(section_text):
|
87 |
+
prompt = f"""λ€μ λ΄μ©μ ν΅μ¬μ μμ½ν΄ μ£ΌμΈμ:
|
|
|
|
|
|
|
|
|
88 |
|
|
|
89 |
{section_text}
|
|
|
|
|
90 |
|
91 |
+
μμ½μ νκ΅μ΄λ‘ κ°κ²°νκ² μμ±ν΄ μ£ΌμΈμ.
|
92 |
+
"""
|
93 |
+
return call_api(prompt, max_tokens=500, temperature=0.3, top_p=0.9)
|
94 |
+
|
95 |
+
def segment_transcript(transcript):
|
96 |
+
sentences = []
|
97 |
+
start_times = []
|
98 |
+
for entry in transcript:
|
99 |
+
subtitle = entry['subtitle']
|
100 |
+
start_time = entry['start']
|
101 |
+
split_sentences = nltk.tokenize.sent_tokenize(subtitle)
|
102 |
+
sentences.extend(split_sentences)
|
103 |
+
start_times.extend([start_time] * len(split_sentences))
|
104 |
+
|
105 |
+
vectorizer = TfidfVectorizer().fit_transform(sentences)
|
106 |
+
vectors = vectorizer.toarray()
|
107 |
+
|
108 |
+
boundaries = [0]
|
109 |
+
threshold = 0.3
|
110 |
+
for i in range(1, len(sentences)):
|
111 |
+
similarity = cosine_similarity([vectors[i - 1]], [vectors[i]])[0][0]
|
112 |
+
if similarity < threshold:
|
113 |
+
boundaries.append(i)
|
114 |
+
boundaries.append(len(sentences))
|
115 |
+
|
116 |
+
sections = []
|
117 |
+
for i in range(len(boundaries) - 1):
|
118 |
+
start_idx = boundaries[i]
|
119 |
+
end_idx = boundaries[i + 1]
|
120 |
+
section_sentences = sentences[start_idx:end_idx]
|
121 |
+
section_text = ' '.join(section_sentences)
|
122 |
+
section_start_time = start_times[start_idx]
|
123 |
+
sections.append({
|
124 |
+
'text': section_text,
|
125 |
+
'start_time': section_start_time
|
126 |
+
})
|
127 |
+
return sections
|
128 |
+
|
129 |
+
def generate_summary(sections, url):
|
130 |
+
video_id = extract_video_id(url)
|
131 |
+
summary_html = "<h3>μμ½:</h3>"
|
132 |
+
for idx, section in enumerate(sections):
|
133 |
+
start_time = section['start_time']
|
134 |
+
hours = int(start_time // 3600)
|
135 |
+
minutes = int((start_time % 3600) // 60)
|
136 |
+
seconds = int(start_time % 60)
|
137 |
+
timestamp_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
|
138 |
+
timestamp_link = f"https://www.youtube.com/watch?v={video_id}&t={int(start_time)}s"
|
139 |
summary = summarize_section(section['text'])
|
140 |
+
summary_html += f"""
|
141 |
+
<h4><a href="{timestamp_link}" target="_blank">{timestamp_str}</a></h4>
|
142 |
+
<div style="white-space: pre-wrap; margin-bottom: 20px;">{summary}</div>
|
143 |
+
"""
|
144 |
+
return summary_html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
with gr.Blocks() as demo:
|
147 |
gr.Markdown("## YouTube μ€ν¬λ¦½νΈ μΆμΆ λ° μμ½ λꡬ")
|
|
|
148 |
youtube_url_input = gr.Textbox(label="YouTube URL μ
λ ₯")
|
149 |
analyze_button = gr.Button("λΆμνκΈ°")
|
150 |
script_output = gr.HTML(label="μ€ν¬λ¦½νΈ")
|
151 |
+
summary_output = gr.HTML(label="μμ½")
|
152 |
+
cached_data = gr.State({"url": "", "title": "", "script": ""})
|
|
|
|
|
153 |
|
154 |
def extract_and_cache(url, cache):
|
155 |
if url == cache["url"]:
|
156 |
+
return cache["title"], cache["script"], cache
|
157 |
+
title, script = get_youtube_script(url)
|
158 |
+
new_cache = {"url": url, "title": title, "script": script}
|
159 |
+
return title, script, new_cache
|
|
|
160 |
|
161 |
def display_script(title, script):
|
162 |
+
script_html = f"""<h2 style='font-size:24px;'>{title}</h2>"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
return script_html
|
164 |
|
165 |
+
def update_summary(cache):
|
166 |
+
if not cache["script"]:
|
167 |
+
return "μ€ν¬λ¦½νΈκ° μμ΅λλ€. λ¨Όμ YouTube URLμ μ
λ ₯νκ³ λΆμμ μ€νν΄μ£ΌμΈμ."
|
168 |
+
try:
|
169 |
+
parsed_result = json.loads(cache["script"])
|
170 |
+
transcript = parsed_result.get("transcription", [])
|
171 |
+
if not transcript:
|
172 |
+
return "νΈλμ€ν¬λ¦½νΈλ₯Ό κ°μ Έμ¬ μ μμ΅λλ€."
|
173 |
+
sections = segment_transcript(transcript)
|
174 |
+
return generate_summary(sections, cache["url"])
|
175 |
+
except Exception as e:
|
176 |
+
logging.exception("μμ½ μμ± μ€ μ€λ₯ λ°μ")
|
177 |
+
return "μμ½μ μμ±νλ λμ μ€λ₯κ° λ°μνμ΅λλ€. λμ€μ λ€μ μλν΄ μ£ΌμΈμ."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
analyze_button.click(
|
180 |
+
extract_and_cache,
|
181 |
+
inputs=[youtube_url_input, cached_data],
|
182 |
+
outputs=[script_output, cached_data]
|
183 |
+
).then(
|
184 |
+
update_summary,
|
185 |
+
inputs=[cached_data],
|
186 |
+
outputs=summary_output
|
187 |
)
|
188 |
|
189 |
demo.launch(share=True)
|