Spaces:
Sleeping
Sleeping
The Mediterranean commited on
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""YouTube Clip Analyzer - Identifies viral/interesting timestamps in videosusing Hugging Face models for AI processing."""import gradio as grfrom pytube import YouTubefrom moviepy.editor import VideoFileClipimport osimport loggingimport timeimport requestsimport jsonimport torchimport whisperfrom transformers import pipeline# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# Initialize modelstry:logger.info("Initializing models")whisper_model = whisper.load_model("tiny")sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")summarizer = pipeline("summarization", model="facebook/bart-large-cnn")except Exception as e:logger.error(f"Failed to initialize models: {str(e)}")whisper_model = Nonesentiment_analyzer = Nonesummarizer = Nonedef download_youtube_audio(youtube_url):"""Download audio from YouTube video"""try:yt = YouTube(youtube_url)audio_stream = yt.streams.filter(only_audio=True).first()audio_path = "temp_audio.mp4"audio_stream.download(filename=audio_path)# Convert to WAV for better compatibility with speech recognitionvideo = VideoFileClip(audio_path)wav_path = "temp_audio.wav"video.audio.write_audiofile(wav_path, ffmpeg_params=["-ac", "1", "-ar", "16000"])video.close()os.remove(audio_path)return wav_path, yt.titleexcept Exception as e:logger.error(f"Error downloading YouTube audio: {str(e)}")raisedef analyze_youtube(youtube_url, progress=gr.Progress()):"""Main function to analyze YouTube video"""try:progress(0.1, desc="Downloading YouTube audio...")# Download audiowav_path, video_title = download_youtube_audio(youtube_url)progress(0.3, desc="Transcribing audio...")# Transcribe audioresult = whisper_model.transcribe(wav_path, fp16=False)segments = result["segments"]progress(0.5, desc="Processing transcript...")# Find clipsclips = []for i in range(len(segments)):start_time = segments[i]["start"]for j in range(i, min(i + 10, len(segments))):end_time = segments[j]["end"]duration = end_time - start_timeif 30 <= duration <= 60:text = " ".join([seg["text"] for seg in segments[i:j+1]])if text.strip():# Analyze sentimentsentiment_result = sentiment_analyzer(text)[0]score = sentiment_result["score"]# Generate summary if text is long enoughsummary = textif len(text) > 100:try:summary_result = summarizer(text, max_length=100, min_length=30, do_sample=False)summary = summary_result[0]["summary_text"]except Exception as e:logger.error(f"Summarization error: {str(e)}")clips.append({"start": start_time,"end": end_time,"score": score,"text": text,"summary": summary})progress(0.9, desc="Finalizing results...")# Clean upif os.path.exists(wav_path):os.remove(wav_path)# Sort and format resultsclips.sort(key=lambda x: x["score"], reverse=True)top_clips = clips[:3]output = f"## Analysis Results for: {video_title}\n\n"for i, clip in enumerate(top_clips, 1):start_time_fmt = f"{int(clip['start']//60):02d}:{int(clip['start']%60):02d}"end_time_fmt = f"{int(clip['end']//60):02d}:{int(clip['end']%60):02d}"output += f"### Clip {i}\n"output += f"โฑ๏ธ Time: {start_time_fmt} - {end_time_fmt}\n"output += f"๐ Interest Score: {clip['score']:.2f}\n"output += f"๐ฌ Summary: {clip['summary']}\n\n"# Add direct link to timestampvideo_id = youtube_url.split("v=")[1].split("&")[0] if "v=" in youtube_url else ""if video_id:timestamp_seconds = int(clip["start"])output += f"๐ [Watch this segment](https://youtu.be/{video_id}?t={timestamp_seconds})\n\n"progress(1.0, desc="Done!")return youtube_url, outputexcept Exception as e:logger.error(f"Error: {str(e)}")return None, f"Error processing video: {str(e)}"# Create Gradio interfacedemo = gr.Interface(fn=analyze_youtube,inputs=gr.Textbox(label="YouTube URL",placeholder="Enter YouTube URL (e.g., https://www.youtube.com/watch?v=dQw4w9WgXcQ)"),outputs=[gr.Video(label="Video"),gr.Markdown(label="Analysis Results")],title="YouTube Viral Clip Analyzer",description="Identify the most interesting timestamps in YouTube videos using AI analysis.",examples=[["https://www.youtube.com/watch?v=Yf_1w00qIKc"],["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]])# Launch the appif __name__ == "__main__":try:demo.launch(server_port=7861)except Exception as e:logger.error(f"Failed to launch on port 7861: {str(e)}")# Try with different settingsdemo.launch(share=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import gradio as grimport pytubefrom transformers import pipelinefrom textblob import TextBlob# Initialize sentiment analysis pipelinesentiment_analyzer = pipeline("sentiment-analysis")def analyze_youtube_content(youtube_url, transcript_text=""):"""Main function to analyze YouTube content"""results = {}# If URL is provided, get video infoif youtube_url:try:# Create a YouTube objectyt = pytube.YouTube(youtube_url)results["video_info"] = {"title": yt.title,"status": "success"}except Exception as e:results["video_info"] = {"status": "error","message": str(e)}# If transcript is provided, analyze itif transcript_text:# Analyze sentiment with TextBlobblob = TextBlob(transcript_text)textblob_sentiment = blob.sentiment# Analyze sentiment with Hugging Facehf_result = sentiment_analyzer(transcript_text[:512])[0]results["sentiment"] = {"textblob": {"polarity": round(textblob_sentiment.polarity, 2),"assessment": "positive" if textblob_sentiment.polarity > 0 else "negative" if textblob_sentiment.polarity < 0 else "neutral"},"huggingface": {"label": hf_result["label"],"score": round(hf_result["score"], 4)}}return results# Create Gradio interfacedemo = gr.Interface(fn=analyze_youtube_content,inputs=[gr.Textbox(label="YouTube URL"),gr.Textbox(label="Transcript Text", lines=10)],outputs=gr.JSON(label="Analysis Results"),title="YouTube Viral Moment Analyzer",description="Analyze viral moments from YouTube videos using ML models")# Launch the app with MCP server enabledif __name__ == "__main__":demo.launch(mcp_server=True)
app.py+51-142