File size: 5,270 Bytes
27d303c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8320ecc
 
 
27d303c
 
8320ecc
 
 
 
 
 
27d303c
8320ecc
 
27d303c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import google.generativeai as genai
import os
import re
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import TranscriptsDisabled, NoTranscriptFound

# --- Configuration ---
KEY_FROM_ENV = os.environ.get("GEMINI_API_KEY")

def extract_video_id(url):
    """Extracts video ID from various YouTube URL formats."""
    patterns = [
        r'(?:v=|\/)([0-9A-Za-z_-]{11}).*',
        r'(?:youtu\.be\/)([0-9A-Za-z_-]{11})',
    ]
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    return None

def get_transcript(video_id):
    """
    Fetches the transcript using YouTube's built-in captions.
    This does NOT require downloading audio!
    """
    try:
        # Try to get transcript - will try available languages automatically
        # First try Turkish, then English, then any
        languages_to_try = ['tr', 'en']
        
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=languages_to_try)
            lang_code = 'tr/en'
        except:
            # Fallback: get any available transcript
            transcript = YouTubeTranscriptApi.get_transcript(video_id)
            lang_code = 'auto'
        
        full_text = " ".join([item['text'] for item in transcript])
        return full_text, lang_code
            
    except TranscriptsDisabled:
        raise Exception("Bu videoda altyazılar devre dışı bırakılmış.")
    except Exception as e:
        raise Exception(f"Altyazı alınamadı: {str(e)}")

def analyze_video(url, api_key_input):
    """Main pipeline function."""
    api_key = KEY_FROM_ENV if KEY_FROM_ENV else api_key_input
    
    try:
        if not api_key:
            return "HATA: API anahtarı bulunamadı. Lütfen ayarlardan ekleyin veya kutucuğa girin."
        
        if not url:
            return "HATA: Lütfen bir YouTube linki girin."

        # 1. Extract Video ID
        video_id = extract_video_id(url)
        if not video_id:
            return "HATA: Geçersiz YouTube linki. Lütfen kontrol edin."
        
        print(f"Video ID: {video_id}")

        # 2. Get Transcript (NO AUDIO DOWNLOAD NEEDED!)
        print("Fetching transcript...")
        transcript_text, lang_code = get_transcript(video_id)
        
        if not transcript_text:
            return "HATA: Bu video için altyazı bulunamadı. Lütfen altyazısı olan bir video deneyin."
        
        print(f"Transcript fetched ({lang_code}): {len(transcript_text)} chars")

        # 3. Intelligence (Gemini)
        print("Analyzing with Gemini...")
        genai.configure(api_key=api_key)
        
        generation_config = {
          "temperature": 0.7,
          "top_p": 0.95,
          "top_k": 64,
          "max_output_tokens": 8192,
        }
        safety_settings = [
          {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
          {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
          {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
          {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
        ]
        
        gemini_model = genai.GenerativeModel(model_name="gemini-1.5-flash",
                                      generation_config=generation_config,
                                      safety_settings=safety_settings)

        prompt = f"""
Sen uzman bir video analistisin. Aşağıdaki metni (ki bu bir video altyazısıdır) analiz et.
Bana şunları ver:
1) Videonun kısa bir özeti
2) Ana fikirler (Madde madde)
3) Videonun tonu ve amacı

Yanıtın tamamen TÜRKÇE olsun. Eğer altyazı başka bir dildeyse, önce Türkçeye çevir sonra analiz et.

ALTYAZI METNİ:
{transcript_text}
"""
        response = gemini_model.generate_content(prompt)
        return response.text

    except Exception as e:
        return f"BİR HATA OLUŞTU:\n{str(e)}"

# --- Gradio UI ---
with gr.Blocks() as demo:
    gr.Markdown(
        """
        # 🎥 YouTube Yapay Zeka Analisti
        **Videonun özetini ve ana fikirlerini saniyeler içinde çıkarın.**
        
        *Not: Bu uygulama YouTube'un mevcut altyazılarını kullanır. Altyazısı olmayan videolar analiz edilemez.*
        """
    )
    
    with gr.Row():
        with gr.Column():
            url_input = gr.Textbox(label="YouTube Video Linki", placeholder="https://www.youtube.com/watch?v=...")
            
            if KEY_FROM_ENV:
                api_key_input = gr.Textbox(label="Gemini API Anahtarı", value="Sistemde Tanımlı ✅", interactive=False)
            else:
                api_key_input = gr.Textbox(label="Gemini API Anahtarı", type="password", placeholder="Anahtarınızı girin")
                
            analyze_btn = gr.Button("Analiz Et 🚀", variant="primary")
        
        with gr.Column():
            output_area = gr.Markdown(label="Analiz Sonucu")
    
    analyze_btn.click(
        fn=analyze_video,
        inputs=[url_input, api_key_input],
        outputs=output_area,
        show_progress=True
    )

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