RCaz's picture
Update app.py
e9af851 verified
raw
history blame
2.29 kB
import os
import tempfile
import gradio as gr
from pytube import YouTube
from moviepy.editor import VideoFileClip
import whisper
from textblob import TextBlob
# Step 1: Transcribe video
def transcribe_video_from_url(url: str) -> str:
with tempfile.TemporaryDirectory() as tmpdir:
video_path = os.path.join(tmpdir, "video.mp4")
audio_path = os.path.join(tmpdir, "audio.wav")
# Download the video
yt = YouTube(url)
stream = yt.streams.filter(file_extension='mp4', only_video=False).first()
stream.download(output_path=tmpdir, filename="video.mp4")
# Extract audio
video_clip = VideoFileClip(video_path)
video_clip.audio.write_audiofile(audio_path, logger=None)
video_clip.close()
# Transcribe with Whisper
model = whisper.load_model("base")
result = model.transcribe(audio_path)
return result["text"]
# Step 2: Analyze sentiment
def sentiment_analysis(text: str) -> dict:
blob = TextBlob(text)
sentiment = blob.sentiment
return {
"polarity": round(sentiment.polarity, 2),
"subjectivity": round(sentiment.subjectivity, 2),
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
}
# Step 3: Main function for Gradio
def analyze_sentiment_from_video(url: str) -> dict:
"""
Transcribe audio from a video URL and analyze sentiment.
"""
transcription = transcribe_video_from_url(url)
sentiment = sentiment_analysis(transcription)
sentiment["transcription"] = transcription
return sentiment
# Gradio interface
demo = gr.Interface(
fn=analyze_sentiment_from_video,
inputs=gr.Textbox(label="YouTube Video URL"),
outputs={
"assessment": gr.Textbox(label="Sentiment"),
"polarity": gr.Number(label="Polarity"),
"subjectivity": gr.Number(label="Subjectivity"),
"transcription": gr.Textbox(label="Transcribed Text", lines=10),
},
title="🎥 Sentiment Analysis from YouTube Video",
description="Enter a YouTube video URL. The app will transcribe its audio and analyze the sentiment of the spoken content."
)
# Launch for Hugging Face Space
if __name__ == "__main__":
demo.launch(mcp_server=True)