springwater's picture
Update app.py
6000f8f verified
raw
history blame
3.47 kB
from youtubesearchpython import VideosSearch, Transcript # Changed import statement
import gradio as gr
import openai
import os
import requests
# openai.api_key = os.getenv('O_API_KEY')
def search_youtube_videos(keyword):
videos_search = VideosSearch(keyword, limit=5)
results = videos_search.result()
video_urls = [video['link'] for video in results['result']]
return video_urls
def get_transcript(urls):
contents = ''
for url in urls:
data = Transcript.get(url)
text = ""
for segment in data['segments']:
text += segment['text']
contents += text
return contents
def summarize_text(contents, OPENAI_API_KEY):
API_URL = "https://api.openai.com/v1/chat/completions"
payload = {
"model": "gpt-4-0125-preview", # λͺ¨λΈ 이름 확인 ν•„μš”
"messages": [{
"role": "system",
"content": "당신은 λ‚΄μš©μ„ μš”μ•½ν•˜λŠ” μ±—λ΄‡μž…λ‹ˆλ‹€."
}, {
"role": "user",
"content": f"유튜브 λ‚΄μš©μΈ '{contents}'에 λŒ€ν•΄ μš”μ•½ν•΄μ£Όμ„Έμš”."
}],
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}"
}
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code == 200:
data = response.json()
return data["choices"][0]["message"]["content"]
else:
# 였λ₯˜ λ©”μ‹œμ§€ κ°œμ„ 
return f"였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μƒνƒœ μ½”λ“œ: {response.status_code}, λ©”μ‹œμ§€: {response.json().get('error', {}).get('message', 'Unknown error')}", ""
# def summarize_text(contents, OPENAI_API_KEY):
# response = openai.ChatCompletion.create(
# model="gpt-4-turbo-preview",
# messages=[
# {"role": "system", "content": "You are a helpful assistant."},
# {"role": "user", "content": f"Summarize this: {contents}"}
# ],
# headers={
# "Content-Type": "application/json",
# "Authorization": f"Bearer {OPENAI_API_KEY}"
# }
# )
# return response.choices[0].message['content'].strip()
# def summarize_text(contents):
# response = openai.ChatCompletion.create(
# engine="gpt-3.5-turbo",
# prompt=f"μš”μ•½: {contents}",
# max_tokens=150
# )
# return response.choices[0].text.strip()
# Function to integrate all the functionalities
# def summarize_youtube_videos(keyword, OPENAI_API_KEY):
# urls = search_youtube_videos(keyword)
# contents = get_transcript(urls)
# summary, _ = summarize_text(contents,OPENAI_API_KEY)
# return summary,""
def summarize_youtube_videos(keyword, OPENAI_API_KEY):
urls = search_youtube_videos(keyword)
contents = get_transcript(urls)
summary = summarize_text(contents, OPENAI_API_KEY)
return summary
with gr.Blocks(css="footer {visibility: hidden;}") as demo:
with gr.Tab():
keyword = gr.Textbox(label="keyword", placeholder='ν‚€μ›Œλ“œλ₯Ό μž…λ ₯ν•˜μ„Έμš”. (예.λΉ„νŠΈμ½”μΈ)')
OPENAI_API_KEY = gr.Textbox(label="OpenAI API ν‚€", placeholder="OpenAI API ν‚€λ₯Ό μž…λ ₯ν•˜μ„Έμš”")
analysis_result = gr.HTML()
analysis_btn = gr.Button("submit")
analysis_btn.click(
fn=summarize_youtube_videos,
inputs=[keyword, OPENAI_API_KEY],
outputs=[analysis_result]
)
demo.launch()