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