File size: 3,890 Bytes
8eb7fd0
 
bb84391
 
4fde749
a6e9713
8eb7fd0
 
bb84391
0921abd
8eb7fd0
 
c963386
8eb7fd0
0921abd
8eb7fd0
 
 
 
0921abd
8eb7fd0
16e2e72
8eb7fd0
0921abd
8eb7fd0
0921abd
f869bf3
bb84391
8eb7fd0
bb84391
f869bf3
 
 
 
bb84391
8eb7fd0
f869bf3
8eb7fd0
 
 
 
 
 
 
 
f869bf3
16e2e72
8eb7fd0
 
 
 
 
 
 
bb84391
8eb7fd0
 
f869bf3
8eb7fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f869bf3
8eb7fd0
bb84391
8eb7fd0
 
 
 
f869bf3
8eb7fd0
 
 
 
 
 
f869bf3
8eb7fd0
 
 
f869bf3
8eb7fd0
 
bb84391
8eb7fd0
 
0921abd
8eb7fd0
 
 
0921abd
bb84391
0921abd
8eb7fd0
 
 
bb84391
8eb7fd0
 
 
bb84391
8eb7fd0
0921abd
16e2e72
bb84391
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
# βœ… Gemini-Based Stock Recommendation Extractor (No Audio, No Whisper)
# Uses video metadata (title + description) + Gemini Flash to extract stock info

import gradio as gr
import os
import tempfile
import json
import google.generativeai as genai
from yt_dlp import YoutubeDL

# βœ… Gemini Configuration
GEMINI_MODEL = None

def configure_gemini(api_key):
    try:
        genai.configure(api_key=api_key)
        global GEMINI_MODEL
        GEMINI_MODEL = genai.GenerativeModel("gemini-1.5-flash-latest")
        return "βœ… Gemini API key configured successfully."
    except Exception as e:
        return f"❌ Gemini configuration failed: {str(e)}"

# βœ… Extract video metadata only (no download)

def extract_metadata(url, cookies_file=None):
    try:
        ydl_opts = {
            'quiet': True,
            'skip_download': True,
            'noplaylist': True,
        }
        if cookies_file and os.path.exists(cookies_file):
            ydl_opts['cookiefile'] = cookies_file

        with YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)

        return {
            'title': info.get("title", ""),
            'description': info.get("description", ""),
            'duration': info.get("duration", 0),
            'uploader': info.get("uploader", ""),
            'view_count': info.get("view_count", 0),
            'upload_date': info.get("upload_date", "")
        }, "βœ… Video metadata extracted"

    except Exception as e:
        return None, f"❌ Metadata extraction failed: {str(e)}"

# βœ… Gemini Prompt for Stock Extraction

def query_gemini_stock_analysis(meta):
    if GEMINI_MODEL is None:
        return "❌ Gemini model is not initialized."

    prompt = f"""
    Analyze the following YouTube video metadata and extract any stock trading recommendations:

    Title: {meta['title']}
    Description: {meta['description']}

    Please extract:
    - Mentioned companies or stock symbols
    - Any price targets, buy/sell/hold recommendations
    - Bullish/bearish sentiments if expressed
    - If no stock info is present, clearly say "No financial or trading recommendations found."
    - Keep the output short and to the point
    """

    try:
        response = GEMINI_MODEL.generate_content(prompt)
        return response.text if response else "⚠️ No response from Gemini."
    except Exception as e:
        return f"❌ Gemini query failed: {str(e)}"

# βœ… Main Pipeline

def run_pipeline(api_key, url, cookies):
    status = configure_gemini(api_key)
    if not status.startswith("βœ…"):
        return status, ""

    # Save cookies if provided
    cookie_path = None
    if cookies:
        cookie_path = tempfile.mktemp(suffix=".txt")
        with open(cookie_path, "wb") as f:
            f.write(cookies.read())

    metadata, meta_status = extract_metadata(url, cookie_path)
    if not metadata:
        return meta_status, ""

    result = query_gemini_stock_analysis(metadata)
    return meta_status, result

# βœ… Gradio UI
with gr.Blocks(title="Gemini Stock Extractor") as demo:
    gr.Markdown("""
    # πŸ“ˆ Gemini-Based Stock Recommendation Extractor
    Paste a YouTube link and get stock-related insights using only the title + description.
    No audio, no transcription required. Fast and simple.
    """)

    with gr.Row():
        api_input = gr.Textbox(label="πŸ”‘ Gemini API Key", type="password")
        url_input = gr.Textbox(label="YouTube Video URL")
        cookies_input = gr.File(label="cookies.txt (optional)", file_types=[".txt"])

    go_btn = gr.Button("πŸš€ Analyze")
    status_box = gr.Textbox(label="Status", lines=1)
    output_box = gr.Textbox(label="Extracted Stock Insights", lines=12)

    go_btn.click(fn=run_pipeline, inputs=[api_input, url_input, cookies_input], outputs=[status_box, output_box])

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