File size: 7,063 Bytes
783f341
 
c277c70
 
9823a49
783f341
 
c277c70
 
783f341
 
 
 
 
655b975
c277c70
9823a49
c277c70
 
 
 
 
 
 
9823a49
21fd183
9823a49
 
655b975
c277c70
 
783f341
 
 
 
 
 
 
c277c70
783f341
c277c70
 
 
 
 
 
 
 
 
9823a49
21fd183
9823a49
 
655b975
c277c70
 
783f341
c277c70
783f341
c277c70
 
 
 
 
 
21fd183
 
c277c70
21fd183
 
c277c70
 
21fd183
 
c277c70
 
 
21fd183
 
c277c70
 
21fd183
 
 
9823a49
655b975
c277c70
 
783f341
 
 
 
 
 
 
9823a49
 
 
 
 
 
783f341
9823a49
21fd183
9823a49
655b975
9823a49
 
783f341
 
21fd183
9823a49
 
21fd183
 
 
783f341
 
 
9823a49
 
783f341
 
 
 
655b975
21fd183
 
c277c70
 
 
 
 
 
 
 
 
 
 
 
 
783f341
 
 
 
 
 
655b975
c277c70
 
 
 
 
 
 
 
21fd183
c277c70
21fd183
c277c70
 
 
 
 
 
 
21fd183
c277c70
21fd183
655b975
c277c70
 
655b975
04621a9
 
 
21fd183
 
 
 
 
9823a49
21fd183
 
 
 
783f341
 
 
c277c70
783f341
c277c70
21fd183
783f341
 
 
 
9823a49
783f341
 
 
 
 
 
 
9823a49
 
783f341
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import gradio as gr
from transformers import pipeline
import whisper
from pydub import AudioSegment
import tempfile
import os
import googleapiclient.discovery
from youtube_transcript_api import YouTubeTranscriptApi
import openai

# Load API keys from environment variables (recommended)
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")


def extract_video_id(url):
    """Extracts the video ID from a YouTube URL."""
    try:
        parsed_url = urlparse(url)
        if "youtube.com" in parsed_url.netloc:
            query_params = parse_qs(parsed_url.query)
            return query_params.get('v', [None])[0]
        elif "youtu.be" in parsed_url.netloc:
            return parsed_url.path.strip("/")
        else:
            print("Invalid YouTube URL.")
            return None
    except Exception as e:
        print(f"Error parsing URL: {e}")
        return None


def get_video_duration(video_id):
    """Fetches the video duration in minutes (if API key provided)."""
    if not YOUTUBE_API_KEY:
        print("Missing YouTube API key. Skipping video duration.")
        return None

    try:
        youtube = googleapiclient.discovery.build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
        request = youtube.videos().list(part="contentDetails", id=video_id)
        response = request.execute()
        if response["items"]:
            duration = response["items"][0]["contentDetails"]["duration"]
            match = re.match(r'PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?', duration)
            hours = int(match.group(1)) if match.group(1) else 0
            minutes = int(match.group(2)) if match.group(2) else 0
            seconds = int(match.group(3)) if match.group(3) else 0
            return hours * 60 + minutes + seconds / 60
        else:
            print("No video details found.")
            return None
    except Exception as e:
        print(f"Error fetching video duration: {e}")
        return None


def download_and_transcribe_with_whisper(youtube_url):
    """Downloads and transcribes audio using Whisper."""
    try:
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_audio_file = os.path.join(temp_dir, "audio.mp3")
            ydl_opts = {
                'format': 'bestaudio/best',
                'outtmpl': temp_audio_file,
                'extractaudio': True,
                'audioquality': 1,
            }

            # Download audio using yt-dlp
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download([youtube_url])

            # Convert to wav for Whisper
            audio = AudioSegment.from_file(temp_audio_file)
            wav_file = os.path.join(temp_dir, "audio.wav")
            audio.export(wav_file, format="wav")

            # Run Whisper transcription
            model = whisper.load_model("large")
            result = model.transcribe(wav_file)
            transcript = result['text']
            return transcript

    except Exception as e:
        print(f"Error during transcription: {e}")
        return None


def get_transcript_from_youtube_api(video_id):
    """Fetches transcript using YouTube API (if available)."""
    if not YOUTUBE_API_KEY:
        print("Missing YouTube API key. Skipping YouTube transcript.")
        return None

    try:
        transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
        for transcript in transcript_list:
            if not transcript.is_generated:
                segments = transcript.fetch()
                return " ".join(segment['text'] for segment in segments)
        print("Manual transcript not found.")
        return None

    except Exception as e:
        print(f"Error fetching transcript: {e}")
        return None


def get_transcript(youtube_url):
    """Gets transcript from YouTube API or Whisper if unavailable."""
    video_id = extract_video_id(youtube_url)
    if not video_id:
        print("Invalid or unsupported YouTube URL.")
        return None

    video_length = get_video_duration(video_id)
    if video_length:
        transcript = get_transcript_from_youtube_api(video_id)
        if transcript:
            return transcript

    print("Using Whisper for transcription.")
    return download_and_transcribe_with_whisper(youtube_url)


def summarize_text_huggingface(text):
    """Summarizes text using a Hugging Face summarization model."""
    summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=0 if torch.cuda.is_available() else -1)
    max_input_length = 1024
    chunk_overlap = 100
    text_chunks = [
        text[i:i + max_input_length]
        for i in range(0, len(text), max_input_length - chunk_overlap)
    ]
    summaries = [
        summarizer(chunk, max_length=100, min_length=50, do_sample=False)[0]['summary_text']
        for chunk in text_chunks
    ]
    return " ".join(summaries)


def generate_optimized_content(summarized_transcript):
    """Generates optimized content using OpenAI (if API key provided)."""
    if not OPENAI_API_KEY:
        print("Missing OpenAI API key. Skipping optimized content generation.")
        return None

    prompt = f"""
    Analyze the following summarized YouTube video transcript and:
    1. Extract the top 10 keywords.
    2. Generate an optimized title (less than 65 characters).
    3. Create an engaging description.
    4. Generate related tags for the video.

    Summarized Transcript:
    {summarized_transcript}

    Provide the results in the following JSON format:
    {{
        "keywords": ["keyword1", "keyword2", ..., "keyword10"],
        "title": "Generated Title",
        "description": "Generated Description",
        "tags": ["tag1", "tag2", ..., "tag10"]
    }}
    """

    try:
        # Use the updated OpenAI API format for chat completions
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are an SEO expert."},
                {"role": "user", "content": prompt}
            ]
        )
        # Extract and parse the response
        response_content = response['choices'][0]['message']['content']
        content = json.loads(response_content)
        return content

    except Exception as e:
        print(f"Error generating content: {e}")
        return None


def seo_tool(youtube_url):
    """This function takes a YouTube URL as input and performs SEO optimization tasks."""
    transcript = get_transcript(youtube_url)
    if not transcript:
        return "Could not fetch the transcript. Please try another video."

    summary = summarize_text_huggingface(transcript)
    optimized_content = generate_optimized_content(summary)

    return summary, optimized_content


interface = gr.Interface(
    fn=seo_tool,
    inputs="text",
    outputs=["text", "json"],
    title="SEO Tool for YouTube Videos",
    description="Enter a YouTube URL to get a summary and optimized content suggestions."
)

if __name__ == "__main__":
    interface.launch()