-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
194 lines (160 loc) · 7.25 KB
/
Copy pathapp.py
File metadata and controls
194 lines (160 loc) · 7.25 KB
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
import concurrent.futures
import random
import requests
from flask import Flask, jsonify, render_template, request
# Global initialization for Vercel
app = Flask(__name__)
# Configured backends
YOUTUBE_PROXY_API = "https://yt.chocolatemoo53.com"
# --- HELPER FUNCTIONS FOR SEARCH ROUTE ---
def get_youtube_data(endpoint):
try:
r = requests.get(f"{YOUTUBE_PROXY_API}/api/v1/{endpoint}", timeout=4)
if r.status_code == 200:
raw_data = r.json()
items = raw_data.get("textualResults", raw_data) if isinstance(raw_data, dict) else raw_data
parsed_videos = []
for item in items:
if item.get("type") == "video":
v_id = item.get("videoId")
if not v_id:
continue
thumbnails = item.get("videoThumbnails", [])
thumb_url = ""
if thumbnails:
thumb_url = next((t["url"] for t in thumbnails if t.get("quality") == "medium"), thumbnails[0]["url"])
if not thumb_url or thumb_url.startswith("/vi/") or not thumb_url.startswith("http"):
thumb_url = f"https://img.youtube.com/vi/{v_id}/0.jpg"
parsed_videos.append({
"id": v_id,
"title": item.get("title"),
"thumbnail": thumb_url,
"source": "youtube",
"deezer_meta": None
})
return parsed_videos[:8]
except Exception:
pass
return []
def get_dailymotion_data(url):
try:
r = requests.get(url, timeout=4)
if r.status_code == 200:
return [{
"id": v["id"],
"title": v["title"],
"thumbnail": v["thumbnail_360_url"],
"source": "dailymotion",
"deezer_meta": None
} for v in r.json().get("list", [])]
except Exception:
pass
return []
def check_deezer_music(query):
try:
r = requests.get(f"https://api.deezer.com/search?q={query}&limit=3", timeout=3)
if r.status_code == 200:
data = r.json().get("data", [])
if data:
return {
"track": data[0].get("title"),
"artist": data[0].get("artist", {}).get("name"),
"album_art": data[0].get("album", {}).get("cover_medium")
}
except Exception:
pass
return None
# --- APP ROUTES ---
@app.route('/')
def index():
return render_template("index.html")
@app.route('/api/search')
def search():
query = request.args.get('q', '')
if not query:
return jsonify([])
music_keywords = ["song", "music", "lyrics", "audio", "mv", "track", "remix"]
is_music_intent = any(k in query.lower() for k in music_keywords)
music_match = None
if is_music_intent:
music_match = check_deezer_music(query)
if music_match:
enhanced_query = f"{music_match['track']} {music_match['artist']}"
else:
enhanced_query = query
dm_url = f"https://api.dailymotion.com/videos?fields=id,title,thumbnail_360_url&search={enhanced_query}&limit=8"
with concurrent.futures.ThreadPoolExecutor() as executor:
future_yt = executor.submit(get_youtube_data, f"search?q={enhanced_query}&filter=videos")
future_dm = executor.submit(get_dailymotion_data, dm_url)
yt_results = future_yt.result()
dm_results = future_dm.result()
if music_match:
track_token = music_match["track"].lower()
artist_token = music_match["artist"].lower()
for item in (yt_results + dm_results):
title_lower = item["title"].lower()
if track_token in title_lower and artist_token in title_lower:
item["deezer_meta"] = music_match
if not item["thumbnail"]:
item["thumbnail"] = music_match["album_art"]
all_videos = yt_results + dm_results
sorted_videos = sorted(all_videos, key=lambda x: 0 if x.get("deezer_meta") else 1)
return jsonify(sorted_videos[:16])
@app.route('/api/trending')
def trending():
# 1. Broad pool of high-quality seeds across gaming, music, tech, and entertainment
seeds = [
"official music video", "gaming tournament", "speedrun history",
"live performance", "album mix", "lofi hip hop radio", "game soundtrack",
"esports grand finals", "indie game showcase", "tech review 2026",
"behind the scenes movie", "animation short", "music festival live",
"synthwave mix", "game dev log", "acoustic session", "modded playthrough",
"orchestral cover", "combo video compilation", "retro gaming retrospective"
]
chosen_seed = random.choice(seeds)
# 2. Fetch live search suggestions to find active topics on YouTube
suggestion_url = f"https://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q={chosen_seed}"
enhanced_query = chosen_seed # Fallback if suggestion engine fails
try:
r_suggest = requests.get(suggestion_url, timeout=3)
if r_suggest.status_code == 200:
suggestions = r_suggest.json()[1]
if suggestions:
enhanced_query = random.choice(suggestions)
except Exception:
pass
# 3. Query your working Invidious search engine with the dynamic topic
yt_search_endpoint = f"search?q={enhanced_query}&filter=videos"
try:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
r = requests.get(f"{YOUTUBE_PROXY_API}/api/v1/{yt_search_endpoint}", headers=headers, timeout=5)
if r.status_code == 200:
raw_data = r.json()
items = raw_data.get("textualResults", raw_data) if isinstance(raw_data, dict) else raw_data
parsed_videos = []
for item in items:
if item.get("type") == "video":
v_id = item.get("videoId")
if not v_id:
continue
thumbnails = item.get("videoThumbnails", [])
thumb_url = ""
if thumbnails:
thumb_url = next((t["url"] for t in thumbnails if t.get("quality") == "medium"), thumbnails[0]["url"])
if not thumb_url or thumb_url.startswith("/vi/") or not thumb_url.startswith("http"):
thumb_url = f"https://img.youtube.com/vi/{v_id}/0.jpg"
parsed_videos.append({
"id": v_id,
"title": item.get("title"),
"thumbnail": thumb_url,
"source": "youtube",
"deezer_meta": None
})
# Shuffle the results so the feed changes dynamically on every page load
random.shuffle(parsed_videos)
return jsonify(parsed_videos[:16])
except Exception:
pass
return jsonify([])
if __name__ == '__main__':
app.run(debug=True)