Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,13 +5,15 @@ import logging
|
|
| 5 |
import ast
|
| 6 |
import openai
|
| 7 |
import os
|
| 8 |
-
import random
|
| 9 |
import re
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# ๋ก๊น
์ค์
|
| 12 |
logging.basicConfig(filename='youtube_script_extractor.log', level=logging.DEBUG,
|
| 13 |
format='%(asctime)s - %(levelname)s - %(message)s')
|
| 14 |
|
|
|
|
|
|
|
| 15 |
def parse_api_response(response):
|
| 16 |
try:
|
| 17 |
if isinstance(response, str):
|
|
@@ -24,32 +26,8 @@ def parse_api_response(response):
|
|
| 24 |
except Exception as e:
|
| 25 |
raise ValueError(f"API ์๋ต ํ์ฑ ์คํจ: {str(e)}")
|
| 26 |
|
| 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: # 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 |
-
# ์๋ํฌ์ธํธ๋ฅผ ์๋ก์ด ๊ฒ์ผ๋ก ๋ณ๊ฒฝ
|
| 53 |
client = Client("whispersound/YT_Ts_R")
|
| 54 |
|
| 55 |
try:
|
|
@@ -57,108 +35,136 @@ def get_youtube_script(url):
|
|
| 57 |
result = client.predict(youtube_url=url, api_name="/predict")
|
| 58 |
logging.debug("API ํธ์ถ ์๋ฃ")
|
| 59 |
|
| 60 |
-
# ์๋ต ํ์ฑ
|
| 61 |
parsed_result = parse_api_response(result)
|
| 62 |
|
| 63 |
title = parsed_result["data"][0]["title"]
|
| 64 |
transcription_text = parsed_result["data"][0]["transcriptionAsText"]
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
except Exception as e:
|
| 70 |
error_msg = f"์คํฌ๋ฆฝํธ ์ถ์ถ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
|
| 71 |
logging.exception(error_msg)
|
| 72 |
-
return "", ""
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
try:
|
| 80 |
response = openai.ChatCompletion.create(
|
| 81 |
-
model="gpt-4o-mini",
|
| 82 |
messages=[{"role": "user", "content": prompt}],
|
| 83 |
-
max_tokens=
|
| 84 |
-
temperature=
|
| 85 |
-
top_p=
|
| 86 |
)
|
| 87 |
return response['choices'][0]['message']['content']
|
| 88 |
-
except Exception as e:
|
| 89 |
-
logging.exception("LLM API ํธ์ถ ์ค ์ค๋ฅ ๋ฐ์")
|
| 90 |
-
return "์์ฝ์ ์์ฑํ๋ ๋์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ๋์ค์ ๋ค์ ์๋ํด ์ฃผ์ธ์."
|
| 91 |
-
|
| 92 |
-
# ํ
์คํธ ์์ฝ ํจ์
|
| 93 |
-
def summarize_text(text):
|
| 94 |
-
prompt = text # ํ๋กฌํํธ๋ฅผ ์๋ณธ ํ
์คํธ๋ก ์ค์ ํ์ฌ self-discover ๊ฐ๋ฅํ๋๋ก ํจ
|
| 95 |
-
|
| 96 |
-
try:
|
| 97 |
-
return call_api(prompt, max_tokens=2000, temperature=0.3, top_p=0.9)
|
| 98 |
except Exception as e:
|
| 99 |
logging.exception("์์ฝ ์์ฑ ์ค ์ค๋ฅ ๋ฐ์")
|
| 100 |
-
return "์์ฝ์ ์์ฑํ๋ ๋์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
# Gradio ์ธํฐํ์ด์ค ์ค์
|
| 103 |
with gr.Blocks() as demo:
|
| 104 |
gr.Markdown("## YouTube ์คํฌ๋ฆฝํธ ์ถ์ถ ๋ฐ ์์ฝ ๋๊ตฌ")
|
| 105 |
|
| 106 |
youtube_url_input = gr.Textbox(label="YouTube URL ์
๋ ฅ")
|
| 107 |
analyze_button = gr.Button("๋ถ์ํ๊ธฐ")
|
| 108 |
-
|
| 109 |
-
summary_output = gr.HTML(label="์์ฝ")
|
| 110 |
|
| 111 |
-
|
| 112 |
-
cached_data = gr.State({"url": "", "title": "", "script": ""})
|
| 113 |
-
|
| 114 |
-
def extract_and_cache(url, cache):
|
| 115 |
-
if url == cache["url"]:
|
| 116 |
-
return cache["title"], cache["script"], cache
|
| 117 |
-
|
| 118 |
-
title, script = get_youtube_script(url)
|
| 119 |
-
new_cache = {"url": url, "title": title, "script": script}
|
| 120 |
-
return title, script, new_cache
|
| 121 |
-
|
| 122 |
-
def display_script(title, script):
|
| 123 |
-
formatted_script = "\n".join(split_sentences(script))
|
| 124 |
-
script_html = f"""<h2 style='font-size:24px;'>{title}</h2>
|
| 125 |
-
<details>
|
| 126 |
-
<summary><h3>์๋ฌธ ์คํฌ๋ฆฝํธ (ํด๋ฆญํ์ฌ ํผ์น๊ธฐ)</h3></summary>
|
| 127 |
-
<div style="white-space: pre-wrap;">{formatted_script}</div>
|
| 128 |
-
</details>"""
|
| 129 |
-
return script_html
|
| 130 |
-
|
| 131 |
-
def generate_summary(script):
|
| 132 |
-
summary = summarize_text(script)
|
| 133 |
-
# ์์ฝ ๊ฒฐ๊ณผ๋ฅผ ์ ํ์ํ๊ธฐ ์ํด div ํ๊ทธ์ CSS ์คํ์ผ ์ ์ฉ
|
| 134 |
-
summary_html = f"""
|
| 135 |
-
<h3>์์ฝ:</h3>
|
| 136 |
-
<div style="white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
|
| 137 |
-
{summary}
|
| 138 |
-
</div>
|
| 139 |
-
"""
|
| 140 |
-
return summary_html
|
| 141 |
|
| 142 |
def analyze(url, cache):
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
return script_html, new_cache
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
return generate_summary(cache["script"])
|
| 151 |
|
| 152 |
-
# ๋ฒํผ ํด๋ฆญ ์ ์คํฌ๋ฆฝํธ ์ถ์ถ
|
| 153 |
analyze_button.click(
|
| 154 |
analyze,
|
| 155 |
inputs=[youtube_url_input, cached_data],
|
| 156 |
-
outputs=[
|
| 157 |
-
).then(
|
| 158 |
-
update_summary,
|
| 159 |
-
inputs=[cached_data],
|
| 160 |
-
outputs=summary_output
|
| 161 |
)
|
| 162 |
|
| 163 |
-
# ์ธํฐํ์ด์ค ์คํ
|
| 164 |
demo.launch(share=True)
|
|
|
|
| 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 |
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:
|
|
|
|
| 35 |
result = client.predict(youtube_url=url, api_name="/predict")
|
| 36 |
logging.debug("API ํธ์ถ ์๋ฃ")
|
| 37 |
|
|
|
|
| 38 |
parsed_result = parse_api_response(result)
|
| 39 |
|
| 40 |
title = parsed_result["data"][0]["title"]
|
| 41 |
transcription_text = parsed_result["data"][0]["transcriptionAsText"]
|
| 42 |
+
original_sections = parsed_result["data"][0]["sections"]
|
| 43 |
+
|
| 44 |
+
merged_sections = merge_sections(original_sections)
|
| 45 |
+
processed_sections = process_merged_sections_parallel(merged_sections)
|
| 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 |
+
def is_same_topic_tfidf(text1, text2, threshold=0.3):
|
| 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 merge_sections(sections, min_duration=60, max_duration=300):
|
| 62 |
+
merged_sections = []
|
| 63 |
+
current_section = sections[0].copy()
|
| 64 |
+
|
| 65 |
+
for section in sections[1:]:
|
| 66 |
+
duration = current_section['end_time'] - current_section['start_time']
|
| 67 |
+
|
| 68 |
+
if duration < min_duration:
|
| 69 |
+
current_section['end_time'] = section['end_time']
|
| 70 |
+
current_section['text'] += ' ' + section['text']
|
| 71 |
+
elif duration >= max_duration:
|
| 72 |
+
merged_sections.append(current_section)
|
| 73 |
+
current_section = section.copy()
|
| 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"""
|
| 87 |
+
๋ค์ ์ ํ๋ธ ๋๋ณธ ์น์
์ ํต์ฌ ๋ด์ฉ์ ๊ฐ๊ฒฐํ๊ฒ ์์ฝํ์ธ์:
|
| 88 |
+
1. ํ๊ธ๋ก ์์ฑํ์ธ์.
|
| 89 |
+
2. ์ฃผ์ ๋
ผ์ ๊ณผ ์ค์ํ ์ธ๋ถ์ฌํญ์ ํฌํจํ์ธ์.
|
| 90 |
+
3. ์์ฝ์ 2-3๋ฌธ์ฅ์ผ๋ก ์ ํํ์ธ์.
|
| 91 |
+
|
| 92 |
+
์น์
๋ด์ฉ:
|
| 93 |
+
{section_text}
|
| 94 |
+
"""
|
| 95 |
try:
|
| 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(processed_sections):
|
| 126 |
+
timeline_summary = ""
|
| 127 |
+
for i, section in enumerate(processed_sections, 1):
|
| 128 |
+
start_time = format_time(section['start_time'])
|
| 129 |
+
end_time = format_time(section['end_time'])
|
| 130 |
+
timeline_summary += f"{start_time} - {end_time} {i}. {section['summary']}\n\n"
|
| 131 |
+
return timeline_summary
|
| 132 |
+
|
| 133 |
+
def display_script_and_summary(title, script, processed_sections):
|
| 134 |
+
timeline_summary = generate_timeline_summary(processed_sections)
|
| 135 |
+
|
| 136 |
+
script_html = f"""<h2 style='font-size:24px;'>{title}</h2>
|
| 137 |
+
<h3>ํ์๋ผ์ธ ์์ฝ:</h3>
|
| 138 |
+
<div style="white-space: pre-wrap; max-height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
|
| 139 |
+
{timeline_summary}
|
| 140 |
+
</div>
|
| 141 |
+
<details>
|
| 142 |
+
<summary><h3>์๋ฌธ ์คํฌ๋ฆฝํธ (ํด๋ฆญํ์ฌ ํผ์น๊ธฐ)</h3></summary>
|
| 143 |
+
<div style="white-space: pre-wrap;">{script}</div>
|
| 144 |
+
</details>"""
|
| 145 |
+
return script_html
|
| 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 |
+
output = gr.HTML(label="๊ฒฐ๊ณผ")
|
|
|
|
| 153 |
|
| 154 |
+
cached_data = gr.State({"url": "", "title": "", "script": "", "processed_sections": []})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
def analyze(url, cache):
|
| 157 |
+
if url == cache["url"]:
|
| 158 |
+
return display_script_and_summary(cache["title"], cache["script"], cache["processed_sections"]), cache
|
|
|
|
| 159 |
|
| 160 |
+
title, script, processed_sections = get_youtube_script(url)
|
| 161 |
+
new_cache = {"url": url, "title": title, "script": script, "processed_sections": processed_sections}
|
| 162 |
+
return display_script_and_summary(title, script, processed_sections), new_cache
|
|
|
|
| 163 |
|
|
|
|
| 164 |
analyze_button.click(
|
| 165 |
analyze,
|
| 166 |
inputs=[youtube_url_input, cached_data],
|
| 167 |
+
outputs=[output, cached_data]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
|
|
|
|
| 170 |
demo.launch(share=True)
|