-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
268 lines (214 loc) · 8.19 KB
/
main.py
File metadata and controls
268 lines (214 loc) · 8.19 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
import os
import json
import requests
import subprocess
from pathlib import Path
from typing import Optional
from datetime import datetime, timedelta
# Load config
CONFIG_FILE = Path("config.json")
with open(CONFIG_FILE) as f:
CONFIG = json.load(f)
# Load tokens from ~/Tokens
TOKENS_DIR = Path.home() / "Tokens"
TWITCH_CLIENT_ID = (TOKENS_DIR / "TWITCH_CLIENT_ID.txt").read_text().strip()
TWITCH_CLIENT_SECRET = (TOKENS_DIR / "TWITCH_TOKEN.txt").read_text().strip()
# Get access token via client credentials flow
def get_access_token():
resp = requests.post(
"https://id.twitch.tv/oauth2/token",
data={
"client_id": TWITCH_CLIENT_ID,
"client_secret": TWITCH_CLIENT_SECRET,
"grant_type": "client_credentials"
}
)
resp.raise_for_status()
return resp.json()["access_token"]
TWITCH_TOKEN = get_access_token()
TWITCH_USER_TOKEN = (TOKENS_DIR / "TWITCH_USER_TOKEN.txt").read_text().strip()
# Use config values
BROADCASTER_ID = CONFIG["broadcaster_id"]
LOGO_PATH = Path(CONFIG["logo_path"])
OUTPUT_DIR = Path(CONFIG["output_dir"])
HASHTAGS = CONFIG["hashtags"]
HASHTAG_SUGGESTIONS = CONFIG["hashtag_suggestions"]
TIKTOK_CONFIG = CONFIG["tiktok"]
OUTPUT_DIR.mkdir(exist_ok=True)
BASE_URL = "https://api.twitch.tv/helix"
HEADERS = {
"Client-ID": TWITCH_CLIENT_ID,
"Authorization": f"Bearer {TWITCH_TOKEN}",
}
USER_HEADERS = {
"Client-ID": TWITCH_CLIENT_ID,
"Authorization": f"Bearer {TWITCH_USER_TOKEN}",
}
def get_clips(broadcaster_id: str, limit: int = 10, days: int = 7) -> list:
"""Fetch clips for broadcaster from the last N days."""
now = datetime.utcnow()
start_date = now - timedelta(days=days)
params = {
"broadcaster_id": broadcaster_id,
"first": limit,
"started_at": start_date.isoformat() + "Z",
"ended_at": now.isoformat() + "Z",
}
resp = requests.get(f"{BASE_URL}/clips", headers=HEADERS, params=params)
resp.raise_for_status()
return resp.json()["data"]
def get_clip_urls(broadcaster_id: str, editor_id: str, clip_ids: list) -> dict:
"""Fetch download URLs from Get Clips Download endpoint (beta)."""
# Returns portrait URLs if available, falls back to landscape
# API limits to 10 clip_ids per request
urls = {}
for i in range(0, len(clip_ids), 10):
batch = clip_ids[i:i+10]
query_string = f"broadcaster_id={broadcaster_id}&editor_id={editor_id}"
for clip_id in batch:
query_string += f"&clip_id={clip_id}"
resp = requests.get(f"{BASE_URL}/clips/downloads?{query_string}", headers=USER_HEADERS)
resp.raise_for_status()
for item in resp.json()["data"]:
# Use portrait URL if available, otherwise use landscape
url = item.get("portrait_download_url") or item.get("landscape_download_url")
urls[item["clip_id"]] = url
return urls
def download_video(url: str, output_path: Path) -> None:
"""Download video from URL."""
print(f"Downloading {url}...")
resp = requests.get(url, stream=True)
resp.raise_for_status()
with open(output_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Saved to {output_path}")
def overlay_logo(input_video: Path, output_video: Path, logo_path: Path) -> None:
"""Crop to portrait (9:16), overlay logo at top center (no resize)."""
print(f"Processing {input_video.name}...")
# Get video dimensions
probe_cmd = [
"ffprobe", "-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=width,height",
"-of", "json",
str(input_video)
]
probe_result = subprocess.run(probe_cmd, capture_output=True, text=True)
probe_data = json.loads(probe_result.stdout)
orig_width = probe_data["streams"][0]["width"]
orig_height = probe_data["streams"][0]["height"]
# Get logo dimensions
logo_probe_cmd = [
"ffprobe", "-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=width,height",
"-of", "json",
str(logo_path)
]
logo_probe_result = subprocess.run(logo_probe_cmd, capture_output=True, text=True)
logo_probe_data = json.loads(logo_probe_result.stdout)
logo_width = logo_probe_data["streams"][0]["width"]
logo_height = logo_probe_data["streams"][0]["height"]
# Crop to 9:16 (portrait) aspect ratio
target_ratio = 9 / 16
current_ratio = orig_width / orig_height
if current_ratio > target_ratio:
# Too wide, crop width
crop_width = int(orig_height * target_ratio)
crop_height = orig_height
else:
# Too tall, crop height
crop_width = orig_width
crop_height = int(orig_width / target_ratio)
crop_x = (orig_width - crop_width) // 2
crop_y = (orig_height - crop_height) // 2
# Center logo horizontally at top
x_pos = (crop_width - logo_width) // 2
y_pos = 10
# FFmpeg: crop + overlay logo (no scaling)
filter_complex = f"[0]crop={crop_width}:{crop_height}:{crop_x}:{crop_y}[v];[v][1]overlay={x_pos}:{y_pos}"
cmd = [
"ffmpeg",
"-i", str(input_video),
"-i", str(logo_path),
"-filter_complex", filter_complex,
"-c:v", "libx264",
"-c:a", "aac",
"-preset", "fast",
str(output_video)
]
subprocess.run(cmd, check=True)
print(f" ✓ Saved to {output_video}")
def play_clip_and_get_caption(clip_path: Path, clip_title: str) -> Optional[str]:
"""Play clip with mpv and get caption from user."""
while True:
# Display options
suggestions = " ".join(HASHTAG_SUGGESTIONS[:3])
print(f"\nPlaying: {clip_title}")
print(f"Suggested hashtags: {suggestions}")
# Play clip
subprocess.run(["mpv", str(clip_path)], check=False)
# Get caption
caption = input("\nCaption (or 'r' to replay): ").strip()
if caption.lower() == "r":
continue
elif caption:
# Append hashtags
final_caption = caption + " " + " ".join(HASHTAGS)
return final_caption
else:
print(" Skipping clip...")
return None
def upload_to_tiktok(video_path: Path, caption: str) -> bool:
"""Upload video to TikTok via API."""
print(f" Uploading to TikTok: {video_path.name}")
# TODO: Implement TikTok upload
# For now, just print what would be uploaded
print(f" Caption: {caption}")
print(f" (TikTok upload not yet implemented)")
return True
def main():
print("Fetching clips...")
clips = get_clips(BROADCASTER_ID)
print(f"Found {len(clips)} clips")
if not clips:
print("No clips found.")
return
# Get clip IDs
clip_ids = [clip["id"] for clip in clips]
print("\nFetching download URLs...")
# Using broadcaster_id as editor_id (assumes you're the broadcaster)
clip_urls = get_clip_urls(BROADCASTER_ID, BROADCASTER_ID, clip_ids)
print(f"Retrieved {len(clip_urls)} clip URLs")
for i, clip in enumerate(clips, 1):
clip_id = clip["id"]
final_video = OUTPUT_DIR / f"{clip_id}_with_logo.mp4"
# Skip if already processed
if final_video.exists():
print(f"[{i}/{len(clips)}] {clip['title']} (already exists)")
# But still prompt for caption/upload if not already done
caption = play_clip_and_get_caption(final_video, clip["title"])
if caption:
upload_to_tiktok(final_video, caption)
continue
print(f"\n[{i}/{len(clips)}] {clip['title']}")
# Get video URL
video_url = clip_urls.get(clip_id)
if not video_url:
print(f" ⚠️ No URL found, skipping...")
continue
# Download portrait clip
temp_video = OUTPUT_DIR / f"{clip_id}_temp.mp4"
download_video(video_url, temp_video)
# Overlay logo
overlay_logo(temp_video, final_video, LOGO_PATH)
# Clean up temp
temp_video.unlink()
# Get caption and upload
caption = play_clip_and_get_caption(final_video, clip["title"])
if caption:
upload_to_tiktok(final_video, caption)
if __name__ == "__main__":
main()