Gofiles
Browse files- Dockerfile +1 -0
- app.py +369 -305
- templates/index.html +59 -9
Dockerfile
CHANGED
|
@@ -27,6 +27,7 @@ EXPOSE 7860
|
|
| 27 |
ENV FLASK_APP=app.py
|
| 28 |
ENV PYTHONUNBUFFERED=1
|
| 29 |
ENV PIXELDRAIN_API_KEY="0998113c-27f0-4d6b-ae06-b5ab00297dae"
|
|
|
|
| 30 |
|
| 31 |
# Run the application
|
| 32 |
CMD ["python", "app.py"]
|
|
|
|
| 27 |
ENV FLASK_APP=app.py
|
| 28 |
ENV PYTHONUNBUFFERED=1
|
| 29 |
ENV PIXELDRAIN_API_KEY="0998113c-27f0-4d6b-ae06-b5ab00297dae"
|
| 30 |
+
ENV GOFILE_TOKEN="wMNJfMhsTSKYbE9w6lKlRR9tAEydBYC9"
|
| 31 |
|
| 32 |
# Run the application
|
| 33 |
CMD ["python", "app.py"]
|
app.py
CHANGED
|
@@ -16,22 +16,20 @@ from datetime import datetime
|
|
| 16 |
import threading
|
| 17 |
|
| 18 |
app = Flask(__name__)
|
| 19 |
-
app.config[
|
| 20 |
-
app.config[
|
| 21 |
-
app.config[
|
| 22 |
|
| 23 |
# Startup logging
|
| 24 |
print("=" * 60)
|
| 25 |
print("Sinhala Subtitle Hardcoder - Flask Server Starting")
|
| 26 |
print("=" * 60)
|
| 27 |
|
| 28 |
-
|
| 29 |
# Initialize database
|
| 30 |
def init_db():
|
| 31 |
-
conn = sqlite3.connect(app.config[
|
| 32 |
c = conn.cursor()
|
| 33 |
-
c.execute(
|
| 34 |
-
"""
|
| 35 |
CREATE TABLE IF NOT EXISTS jobs (
|
| 36 |
id TEXT PRIMARY KEY,
|
| 37 |
status TEXT,
|
|
@@ -45,19 +43,15 @@ def init_db():
|
|
| 45 |
updated_at TIMESTAMP,
|
| 46 |
error TEXT
|
| 47 |
)
|
| 48 |
-
|
| 49 |
-
)
|
| 50 |
conn.commit()
|
| 51 |
conn.close()
|
| 52 |
|
| 53 |
-
|
| 54 |
init_db()
|
| 55 |
|
| 56 |
# Check FFmpeg
|
| 57 |
try:
|
| 58 |
-
result = subprocess.run(
|
| 59 |
-
["ffmpeg", "-version"], capture_output=True, text=True, timeout=5
|
| 60 |
-
)
|
| 61 |
if result.returncode == 0:
|
| 62 |
print(f"β
FFmpeg found: {result.stdout.split()[2]}")
|
| 63 |
except FileNotFoundError:
|
|
@@ -67,15 +61,13 @@ except Exception as e:
|
|
| 67 |
|
| 68 |
print("=" * 60)
|
| 69 |
|
| 70 |
-
|
| 71 |
class JobLogger:
|
| 72 |
"""Thread-safe job logger with database persistence"""
|
| 73 |
-
|
| 74 |
def __init__(self, job_id):
|
| 75 |
self.job_id = job_id
|
| 76 |
self.logs = []
|
| 77 |
self.lock = threading.Lock()
|
| 78 |
-
|
| 79 |
def log(self, message):
|
| 80 |
"""Add log message"""
|
| 81 |
with self.lock:
|
|
@@ -84,439 +76,512 @@ class JobLogger:
|
|
| 84 |
self.logs.append(log_entry)
|
| 85 |
print(f"Job {self.job_id}: {message}")
|
| 86 |
self.save_to_db()
|
| 87 |
-
|
| 88 |
def save_to_db(self):
|
| 89 |
"""Save logs to database"""
|
| 90 |
try:
|
| 91 |
-
conn = sqlite3.connect(app.config[
|
| 92 |
c = conn.cursor()
|
| 93 |
logs_json = json.dumps(self.logs)
|
| 94 |
-
c.execute(
|
| 95 |
-
|
| 96 |
-
(logs_json, datetime.now(), self.job_id),
|
| 97 |
-
)
|
| 98 |
conn.commit()
|
| 99 |
conn.close()
|
| 100 |
except Exception as e:
|
| 101 |
print(f"Error saving logs: {e}")
|
| 102 |
|
| 103 |
-
|
| 104 |
class JobStatus:
|
| 105 |
"""Manage job status in database"""
|
| 106 |
-
|
| 107 |
@staticmethod
|
| 108 |
def create(job_id, total_videos):
|
| 109 |
-
conn = sqlite3.connect(app.config[
|
| 110 |
c = conn.cursor()
|
| 111 |
-
c.execute(
|
| 112 |
-
"""
|
| 113 |
INSERT INTO jobs (id, status, current_step, progress, total_videos,
|
| 114 |
processed_videos, logs, results, created_at, updated_at)
|
| 115 |
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
job_id,
|
| 119 |
-
"queued",
|
| 120 |
-
"Initializing...",
|
| 121 |
-
0,
|
| 122 |
-
total_videos,
|
| 123 |
-
0,
|
| 124 |
-
"[]",
|
| 125 |
-
"[]",
|
| 126 |
-
datetime.now(),
|
| 127 |
-
datetime.now(),
|
| 128 |
-
),
|
| 129 |
-
)
|
| 130 |
conn.commit()
|
| 131 |
conn.close()
|
| 132 |
-
|
| 133 |
@staticmethod
|
| 134 |
-
def update(
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
current_step=None,
|
| 138 |
-
progress=None,
|
| 139 |
-
processed_videos=None,
|
| 140 |
-
error=None,
|
| 141 |
-
):
|
| 142 |
-
conn = sqlite3.connect(app.config["DATABASE"])
|
| 143 |
c = conn.cursor()
|
| 144 |
-
|
| 145 |
updates = []
|
| 146 |
params = []
|
| 147 |
-
|
| 148 |
if status:
|
| 149 |
-
updates.append(
|
| 150 |
params.append(status)
|
| 151 |
if current_step:
|
| 152 |
-
updates.append(
|
| 153 |
params.append(current_step)
|
| 154 |
if progress is not None:
|
| 155 |
-
updates.append(
|
| 156 |
params.append(progress)
|
| 157 |
if processed_videos is not None:
|
| 158 |
-
updates.append(
|
| 159 |
params.append(processed_videos)
|
| 160 |
if error:
|
| 161 |
-
updates.append(
|
| 162 |
params.append(error)
|
| 163 |
-
|
| 164 |
-
updates.append(
|
| 165 |
params.append(datetime.now())
|
| 166 |
params.append(job_id)
|
| 167 |
-
|
| 168 |
query = f"UPDATE jobs SET {', '.join(updates)} WHERE id = ?"
|
| 169 |
c.execute(query, params)
|
| 170 |
conn.commit()
|
| 171 |
conn.close()
|
| 172 |
-
|
| 173 |
@staticmethod
|
| 174 |
def set_results(job_id, results):
|
| 175 |
-
conn = sqlite3.connect(app.config[
|
| 176 |
c = conn.cursor()
|
| 177 |
-
c.execute(
|
| 178 |
-
|
| 179 |
-
(json.dumps(results), datetime.now(), job_id),
|
| 180 |
-
)
|
| 181 |
conn.commit()
|
| 182 |
conn.close()
|
| 183 |
-
|
| 184 |
@staticmethod
|
| 185 |
def get(job_id):
|
| 186 |
-
conn = sqlite3.connect(app.config[
|
| 187 |
c = conn.cursor()
|
| 188 |
-
c.execute(
|
| 189 |
row = c.fetchone()
|
| 190 |
conn.close()
|
| 191 |
-
|
| 192 |
if row:
|
| 193 |
return {
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
}
|
| 206 |
return None
|
| 207 |
-
|
| 208 |
@staticmethod
|
| 209 |
def get_all():
|
| 210 |
-
conn = sqlite3.connect(app.config[
|
| 211 |
c = conn.cursor()
|
| 212 |
-
c.execute(
|
| 213 |
rows = c.fetchall()
|
| 214 |
conn.close()
|
| 215 |
-
|
| 216 |
jobs = []
|
| 217 |
for row in rows:
|
| 218 |
-
jobs.append(
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
}
|
| 229 |
-
)
|
| 230 |
return jobs
|
| 231 |
|
| 232 |
-
|
| 233 |
class VideoSubtitleProcessor:
|
| 234 |
def __init__(self, job_id, logger):
|
| 235 |
self.temp_dir = tempfile.mkdtemp()
|
| 236 |
self.job_id = job_id
|
| 237 |
self.logger = logger
|
| 238 |
-
|
| 239 |
def download_video(self, url, index, total):
|
| 240 |
"""Download video with progress tracking"""
|
| 241 |
try:
|
| 242 |
self.logger.log(f"Downloading video {index}/{total}: {url[:50]}...")
|
| 243 |
-
JobStatus.update(
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
if "pixeldrain.com" in url:
|
| 250 |
-
match = re.search(r
|
| 251 |
if match:
|
| 252 |
file_id = match.group(1)
|
| 253 |
-
|
|
|
|
|
|
|
| 254 |
else:
|
| 255 |
download_url = url
|
| 256 |
else:
|
| 257 |
download_url = url
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
response.raise_for_status()
|
| 261 |
-
|
| 262 |
filename = "video.mp4"
|
| 263 |
-
if
|
| 264 |
-
cd = response.headers[
|
| 265 |
-
if
|
| 266 |
-
filename = cd.split(
|
| 267 |
-
|
| 268 |
-
filename = re.sub(r'[<>:"/\\|?*]',
|
| 269 |
-
if not filename.endswith((
|
| 270 |
-
filename +=
|
| 271 |
-
|
| 272 |
filepath = os.path.join(self.temp_dir, filename)
|
| 273 |
-
|
| 274 |
-
total_size = int(response.headers.get(
|
| 275 |
downloaded = 0
|
| 276 |
-
|
| 277 |
-
with open(filepath,
|
| 278 |
for chunk in response.iter_content(chunk_size=8192):
|
| 279 |
if chunk:
|
| 280 |
f.write(chunk)
|
| 281 |
downloaded += len(chunk)
|
| 282 |
-
|
| 283 |
-
self.logger.log(
|
| 284 |
-
f"β
Downloaded: {filename} ({downloaded/1024/1024:.1f} MB)"
|
| 285 |
-
)
|
| 286 |
return filepath
|
| 287 |
-
|
| 288 |
except Exception as e:
|
| 289 |
self.logger.log(f"β Download failed: {str(e)}")
|
| 290 |
raise Exception(f"Download failed: {str(e)}")
|
| 291 |
-
|
| 292 |
def fix_subtitle_encoding(self, subtitle_file):
|
| 293 |
"""Fix Sinhala subtitle encoding"""
|
| 294 |
try:
|
| 295 |
self.logger.log("Fixing subtitle encoding...")
|
| 296 |
-
|
| 297 |
-
encodings = [
|
| 298 |
content = None
|
| 299 |
-
|
| 300 |
for encoding in encodings:
|
| 301 |
try:
|
| 302 |
-
with open(subtitle_file,
|
| 303 |
content = f.read()
|
| 304 |
break
|
| 305 |
except:
|
| 306 |
continue
|
| 307 |
-
|
| 308 |
if content is None:
|
| 309 |
-
with open(subtitle_file,
|
| 310 |
-
content = f.read().decode(
|
| 311 |
-
|
| 312 |
-
cleaned_content =
|
| 313 |
for char in content:
|
| 314 |
code = ord(char)
|
| 315 |
-
if (
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
or 0x00A0 <= code <= 0x00FF
|
| 320 |
-
):
|
| 321 |
cleaned_content += char
|
| 322 |
elif code > 0x007F:
|
| 323 |
cleaned_content += char
|
| 324 |
-
|
| 325 |
-
fixed_file = subtitle_file +
|
| 326 |
-
with open(fixed_file,
|
| 327 |
f.write(cleaned_content)
|
| 328 |
-
|
| 329 |
self.logger.log("β
Subtitle encoding fixed")
|
| 330 |
return fixed_file
|
| 331 |
-
|
| 332 |
except Exception as e:
|
| 333 |
self.logger.log(f"β Subtitle fix failed: {str(e)}")
|
| 334 |
raise Exception(f"Subtitle encoding fix failed: {str(e)}")
|
| 335 |
-
|
| 336 |
-
def hardcode_subtitle_single(
|
| 337 |
-
self, video_path, subtitle_path, output_path, index, total
|
| 338 |
-
):
|
| 339 |
"""Hardcode subtitle with progress tracking"""
|
| 340 |
try:
|
| 341 |
-
self.logger.log(
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
current_step=f"Hardcoding subtitles {index}/{total}",
|
| 347 |
-
progress=30 + int((index - 1) / total * 50),
|
| 348 |
-
)
|
| 349 |
-
|
| 350 |
fixed_subtitle = self.fix_subtitle_encoding(subtitle_path)
|
| 351 |
-
|
| 352 |
-
temp_sub = os.path.join(
|
| 353 |
-
self.temp_dir, f"temp_sub_{os.getpid()}_{index}.srt"
|
| 354 |
-
)
|
| 355 |
shutil.copy(fixed_subtitle, temp_sub)
|
| 356 |
-
|
| 357 |
-
if os.name ==
|
| 358 |
-
subtitle_escaped = temp_sub.replace(
|
| 359 |
else:
|
| 360 |
-
subtitle_escaped = temp_sub.replace(
|
| 361 |
-
|
| 362 |
cmd = [
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
"-preset",
|
| 373 |
-
"ultrafast",
|
| 374 |
-
"-crf",
|
| 375 |
-
"23",
|
| 376 |
-
"-y",
|
| 377 |
-
output_path,
|
| 378 |
]
|
| 379 |
-
|
| 380 |
process = subprocess.Popen(
|
| 381 |
cmd,
|
| 382 |
stdout=subprocess.PIPE,
|
| 383 |
stderr=subprocess.PIPE,
|
| 384 |
-
universal_newlines=True
|
| 385 |
)
|
| 386 |
-
|
| 387 |
process.wait()
|
| 388 |
-
|
| 389 |
for f in [fixed_subtitle, temp_sub]:
|
| 390 |
if os.path.exists(f):
|
| 391 |
try:
|
| 392 |
os.remove(f)
|
| 393 |
except:
|
| 394 |
pass
|
| 395 |
-
|
| 396 |
if process.returncode != 0:
|
| 397 |
raise Exception(f"FFmpeg failed")
|
| 398 |
-
|
| 399 |
if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
|
| 400 |
raise Exception("Output video not created")
|
| 401 |
-
|
| 402 |
self.logger.log(f"β
Processed: {os.path.basename(output_path)}")
|
| 403 |
JobStatus.update(self.job_id, processed_videos=index)
|
| 404 |
return output_path
|
| 405 |
-
|
| 406 |
except Exception as e:
|
| 407 |
self.logger.log(f"β Processing failed: {str(e)}")
|
| 408 |
raise Exception(f"Hardcoding failed: {str(e)}")
|
| 409 |
-
|
| 410 |
def upload_to_pixeldrain(self, filepath, api_key, index, total):
|
| 411 |
-
"""Upload with progress tracking"""
|
| 412 |
try:
|
| 413 |
self.logger.log(f"Uploading {index}/{total} to PixelDrain...")
|
| 414 |
-
JobStatus.update(
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
)
|
| 419 |
-
|
| 420 |
url = "https://pixeldrain.com/api/file"
|
| 421 |
filename = os.path.basename(filepath)
|
| 422 |
-
|
| 423 |
headers = {}
|
| 424 |
if api_key:
|
| 425 |
-
headers[
|
| 426 |
-
|
| 427 |
-
with open(filepath,
|
| 428 |
-
files = {
|
| 429 |
-
|
| 430 |
if api_key:
|
| 431 |
-
response = requests.post(
|
| 432 |
-
url, files=files, headers=headers, timeout=600
|
| 433 |
-
)
|
| 434 |
else:
|
| 435 |
response = requests.post(url, files=files, timeout=600)
|
| 436 |
-
|
| 437 |
response.raise_for_status()
|
| 438 |
-
|
| 439 |
result = response.json()
|
| 440 |
-
file_id = result.get(
|
| 441 |
-
|
| 442 |
if file_id:
|
| 443 |
download_link = f"https://pixeldrain.com/u/{file_id}"
|
| 444 |
-
self.logger.log(f"β
Uploaded: {download_link}")
|
| 445 |
return download_link
|
| 446 |
else:
|
| 447 |
raise Exception("No file ID returned")
|
| 448 |
-
|
| 449 |
except Exception as e:
|
| 450 |
-
self.logger.log(f"
|
| 451 |
-
raise Exception(f"
|
| 452 |
-
|
| 453 |
-
def
|
| 454 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
results = []
|
| 456 |
video_paths = []
|
| 457 |
-
|
| 458 |
try:
|
| 459 |
-
JobStatus.update(self.job_id, status=
|
| 460 |
-
|
| 461 |
# Download all videos
|
| 462 |
total = len(video_urls)
|
| 463 |
for i, url in enumerate(video_urls, 1):
|
| 464 |
video_path = self.download_video(url, i, total)
|
| 465 |
video_paths.append(video_path)
|
| 466 |
-
|
| 467 |
-
JobStatus.update(self.job_id, status=
|
| 468 |
-
|
| 469 |
# Process in parallel
|
| 470 |
output_paths = []
|
| 471 |
-
|
| 472 |
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 473 |
futures = []
|
| 474 |
for i, video_path in enumerate(video_paths, 1):
|
| 475 |
output_name = f"output_{i}_{Path(video_path).stem}_subbed.mp4"
|
| 476 |
output_path = os.path.join(self.temp_dir, output_name)
|
| 477 |
output_paths.append(output_path)
|
| 478 |
-
|
| 479 |
future = executor.submit(
|
| 480 |
self.hardcode_subtitle_single,
|
| 481 |
video_path,
|
| 482 |
subtitle_path,
|
| 483 |
output_path,
|
| 484 |
i,
|
| 485 |
-
total
|
| 486 |
)
|
| 487 |
futures.append(future)
|
| 488 |
-
|
| 489 |
for future in futures:
|
| 490 |
try:
|
| 491 |
result = future.result()
|
| 492 |
results.append(result)
|
| 493 |
except Exception as e:
|
| 494 |
raise
|
| 495 |
-
|
| 496 |
-
JobStatus.update(self.job_id, status=
|
| 497 |
-
|
| 498 |
-
# Upload to PixelDrain
|
| 499 |
uploaded_links = []
|
| 500 |
for i, output_path in enumerate(results, 1):
|
| 501 |
if os.path.exists(output_path):
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 510 |
JobStatus.set_results(self.job_id, uploaded_links)
|
| 511 |
self.logger.log(f"π All {len(uploaded_links)} videos completed!")
|
| 512 |
-
|
| 513 |
return uploaded_links, results
|
| 514 |
-
|
| 515 |
except Exception as e:
|
| 516 |
-
JobStatus.update(self.job_id, status=
|
| 517 |
self.logger.log(f"β Job failed: {str(e)}")
|
| 518 |
raise Exception(f"Processing failed: {str(e)}")
|
| 519 |
-
|
| 520 |
def cleanup(self):
|
| 521 |
"""Clean up temporary files"""
|
| 522 |
try:
|
|
@@ -525,109 +590,108 @@ class VideoSubtitleProcessor:
|
|
| 525 |
except:
|
| 526 |
pass
|
| 527 |
|
| 528 |
-
|
| 529 |
-
def process_job_background(job_id, video_urls, subtitle_path, api_key):
|
| 530 |
"""Background job processor"""
|
| 531 |
logger = JobLogger(job_id)
|
| 532 |
processor = VideoSubtitleProcessor(job_id, logger)
|
| 533 |
-
|
| 534 |
try:
|
| 535 |
uploaded_links, output_paths = processor.process_multiple_videos(
|
| 536 |
-
video_urls,
|
|
|
|
|
|
|
|
|
|
| 537 |
)
|
| 538 |
finally:
|
| 539 |
processor.cleanup()
|
| 540 |
if os.path.exists(subtitle_path):
|
| 541 |
os.remove(subtitle_path)
|
| 542 |
|
| 543 |
-
|
| 544 |
# Flask routes
|
| 545 |
-
@app.route(
|
| 546 |
def index():
|
| 547 |
-
return render_template(
|
| 548 |
|
| 549 |
-
|
| 550 |
-
@app.route("/jobs")
|
| 551 |
def jobs_list():
|
| 552 |
"""Get all jobs"""
|
| 553 |
jobs = JobStatus.get_all()
|
| 554 |
-
return jsonify({
|
| 555 |
-
|
| 556 |
|
| 557 |
-
@app.route(
|
| 558 |
def job_status(job_id):
|
| 559 |
"""Get job status"""
|
| 560 |
job = JobStatus.get(job_id)
|
| 561 |
if job:
|
| 562 |
return jsonify(job)
|
| 563 |
-
return jsonify({
|
| 564 |
|
| 565 |
-
|
| 566 |
-
@app.route("/process", methods=["POST"])
|
| 567 |
def process_videos():
|
| 568 |
try:
|
| 569 |
-
video_urls_text = request.form.get(
|
| 570 |
-
subtitle_file = request.files.get(
|
| 571 |
-
pixeldrain_api_key = request.form.get(
|
| 572 |
-
|
|
|
|
|
|
|
| 573 |
if not pixeldrain_api_key:
|
| 574 |
-
pixeldrain_api_key = os.environ.get(
|
| 575 |
-
|
|
|
|
|
|
|
|
|
|
| 576 |
if not video_urls_text or not video_urls_text.strip():
|
| 577 |
-
return jsonify({
|
| 578 |
-
|
| 579 |
if not subtitle_file:
|
| 580 |
-
return jsonify({
|
| 581 |
-
|
| 582 |
-
video_urls = [url.strip() for url in video_urls_text.split(
|
| 583 |
-
|
| 584 |
if not video_urls:
|
| 585 |
-
return jsonify({
|
| 586 |
-
|
| 587 |
# Create job
|
| 588 |
job_id = str(uuid.uuid4())
|
| 589 |
JobStatus.create(job_id, len(video_urls))
|
| 590 |
-
|
| 591 |
# Small delay to ensure database write completes
|
| 592 |
time.sleep(0.1)
|
| 593 |
-
|
| 594 |
# Save subtitle file
|
| 595 |
subtitle_filename = secure_filename(subtitle_file.filename)
|
| 596 |
-
subtitle_path = os.path.join(
|
| 597 |
-
app.config["UPLOAD_FOLDER"], f"{job_id}_{subtitle_filename}"
|
| 598 |
-
)
|
| 599 |
subtitle_file.save(subtitle_path)
|
| 600 |
-
|
| 601 |
-
# Start background processing
|
| 602 |
-
|
|
|
|
|
|
|
| 603 |
thread = threading.Thread(
|
| 604 |
target=process_job_background,
|
| 605 |
-
args=(job_id, video_urls, subtitle_path,
|
| 606 |
)
|
| 607 |
thread.daemon = True
|
| 608 |
thread.start()
|
| 609 |
-
|
| 610 |
-
return jsonify(
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
)
|
| 617 |
-
|
| 618 |
except Exception as e:
|
| 619 |
print(f"Error: {e}")
|
| 620 |
import traceback
|
| 621 |
-
|
| 622 |
traceback.print_exc()
|
| 623 |
-
return jsonify({
|
| 624 |
-
|
| 625 |
|
| 626 |
-
@app.route(
|
| 627 |
def health():
|
| 628 |
-
return jsonify({
|
| 629 |
-
|
| 630 |
|
| 631 |
-
if __name__ ==
|
| 632 |
-
os.makedirs(
|
| 633 |
-
app.run(host=
|
|
|
|
| 16 |
import threading
|
| 17 |
|
| 18 |
app = Flask(__name__)
|
| 19 |
+
app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # 500MB max
|
| 20 |
+
app.config['UPLOAD_FOLDER'] = tempfile.mkdtemp()
|
| 21 |
+
app.config['DATABASE'] = 'jobs.db'
|
| 22 |
|
| 23 |
# Startup logging
|
| 24 |
print("=" * 60)
|
| 25 |
print("Sinhala Subtitle Hardcoder - Flask Server Starting")
|
| 26 |
print("=" * 60)
|
| 27 |
|
|
|
|
| 28 |
# Initialize database
|
| 29 |
def init_db():
|
| 30 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 31 |
c = conn.cursor()
|
| 32 |
+
c.execute('''
|
|
|
|
| 33 |
CREATE TABLE IF NOT EXISTS jobs (
|
| 34 |
id TEXT PRIMARY KEY,
|
| 35 |
status TEXT,
|
|
|
|
| 43 |
updated_at TIMESTAMP,
|
| 44 |
error TEXT
|
| 45 |
)
|
| 46 |
+
''')
|
|
|
|
| 47 |
conn.commit()
|
| 48 |
conn.close()
|
| 49 |
|
|
|
|
| 50 |
init_db()
|
| 51 |
|
| 52 |
# Check FFmpeg
|
| 53 |
try:
|
| 54 |
+
result = subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True, timeout=5)
|
|
|
|
|
|
|
| 55 |
if result.returncode == 0:
|
| 56 |
print(f"β
FFmpeg found: {result.stdout.split()[2]}")
|
| 57 |
except FileNotFoundError:
|
|
|
|
| 61 |
|
| 62 |
print("=" * 60)
|
| 63 |
|
|
|
|
| 64 |
class JobLogger:
|
| 65 |
"""Thread-safe job logger with database persistence"""
|
|
|
|
| 66 |
def __init__(self, job_id):
|
| 67 |
self.job_id = job_id
|
| 68 |
self.logs = []
|
| 69 |
self.lock = threading.Lock()
|
| 70 |
+
|
| 71 |
def log(self, message):
|
| 72 |
"""Add log message"""
|
| 73 |
with self.lock:
|
|
|
|
| 76 |
self.logs.append(log_entry)
|
| 77 |
print(f"Job {self.job_id}: {message}")
|
| 78 |
self.save_to_db()
|
| 79 |
+
|
| 80 |
def save_to_db(self):
|
| 81 |
"""Save logs to database"""
|
| 82 |
try:
|
| 83 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 84 |
c = conn.cursor()
|
| 85 |
logs_json = json.dumps(self.logs)
|
| 86 |
+
c.execute('UPDATE jobs SET logs = ?, updated_at = ? WHERE id = ?',
|
| 87 |
+
(logs_json, datetime.now(), self.job_id))
|
|
|
|
|
|
|
| 88 |
conn.commit()
|
| 89 |
conn.close()
|
| 90 |
except Exception as e:
|
| 91 |
print(f"Error saving logs: {e}")
|
| 92 |
|
|
|
|
| 93 |
class JobStatus:
|
| 94 |
"""Manage job status in database"""
|
|
|
|
| 95 |
@staticmethod
|
| 96 |
def create(job_id, total_videos):
|
| 97 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 98 |
c = conn.cursor()
|
| 99 |
+
c.execute('''
|
|
|
|
| 100 |
INSERT INTO jobs (id, status, current_step, progress, total_videos,
|
| 101 |
processed_videos, logs, results, created_at, updated_at)
|
| 102 |
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 103 |
+
''', (job_id, 'queued', 'Initializing...', 0, total_videos, 0,
|
| 104 |
+
'[]', '[]', datetime.now(), datetime.now()))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
conn.commit()
|
| 106 |
conn.close()
|
| 107 |
+
|
| 108 |
@staticmethod
|
| 109 |
+
def update(job_id, status=None, current_step=None, progress=None,
|
| 110 |
+
processed_videos=None, error=None):
|
| 111 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
c = conn.cursor()
|
| 113 |
+
|
| 114 |
updates = []
|
| 115 |
params = []
|
| 116 |
+
|
| 117 |
if status:
|
| 118 |
+
updates.append('status = ?')
|
| 119 |
params.append(status)
|
| 120 |
if current_step:
|
| 121 |
+
updates.append('current_step = ?')
|
| 122 |
params.append(current_step)
|
| 123 |
if progress is not None:
|
| 124 |
+
updates.append('progress = ?')
|
| 125 |
params.append(progress)
|
| 126 |
if processed_videos is not None:
|
| 127 |
+
updates.append('processed_videos = ?')
|
| 128 |
params.append(processed_videos)
|
| 129 |
if error:
|
| 130 |
+
updates.append('error = ?')
|
| 131 |
params.append(error)
|
| 132 |
+
|
| 133 |
+
updates.append('updated_at = ?')
|
| 134 |
params.append(datetime.now())
|
| 135 |
params.append(job_id)
|
| 136 |
+
|
| 137 |
query = f"UPDATE jobs SET {', '.join(updates)} WHERE id = ?"
|
| 138 |
c.execute(query, params)
|
| 139 |
conn.commit()
|
| 140 |
conn.close()
|
| 141 |
+
|
| 142 |
@staticmethod
|
| 143 |
def set_results(job_id, results):
|
| 144 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 145 |
c = conn.cursor()
|
| 146 |
+
c.execute('UPDATE jobs SET results = ?, updated_at = ? WHERE id = ?',
|
| 147 |
+
(json.dumps(results), datetime.now(), job_id))
|
|
|
|
|
|
|
| 148 |
conn.commit()
|
| 149 |
conn.close()
|
| 150 |
+
|
| 151 |
@staticmethod
|
| 152 |
def get(job_id):
|
| 153 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 154 |
c = conn.cursor()
|
| 155 |
+
c.execute('SELECT * FROM jobs WHERE id = ?', (job_id,))
|
| 156 |
row = c.fetchone()
|
| 157 |
conn.close()
|
| 158 |
+
|
| 159 |
if row:
|
| 160 |
return {
|
| 161 |
+
'id': row[0],
|
| 162 |
+
'status': row[1],
|
| 163 |
+
'current_step': row[2],
|
| 164 |
+
'progress': row[3],
|
| 165 |
+
'total_videos': row[4],
|
| 166 |
+
'processed_videos': row[5],
|
| 167 |
+
'logs': json.loads(row[6]) if row[6] else [],
|
| 168 |
+
'results': json.loads(row[7]) if row[7] else [],
|
| 169 |
+
'created_at': row[8],
|
| 170 |
+
'updated_at': row[9],
|
| 171 |
+
'error': row[10]
|
| 172 |
}
|
| 173 |
return None
|
| 174 |
+
|
| 175 |
@staticmethod
|
| 176 |
def get_all():
|
| 177 |
+
conn = sqlite3.connect(app.config['DATABASE'])
|
| 178 |
c = conn.cursor()
|
| 179 |
+
c.execute('SELECT * FROM jobs ORDER BY created_at DESC LIMIT 50')
|
| 180 |
rows = c.fetchall()
|
| 181 |
conn.close()
|
| 182 |
+
|
| 183 |
jobs = []
|
| 184 |
for row in rows:
|
| 185 |
+
jobs.append({
|
| 186 |
+
'id': row[0],
|
| 187 |
+
'status': row[1],
|
| 188 |
+
'current_step': row[2],
|
| 189 |
+
'progress': row[3],
|
| 190 |
+
'total_videos': row[4],
|
| 191 |
+
'processed_videos': row[5],
|
| 192 |
+
'created_at': row[8],
|
| 193 |
+
'updated_at': row[9]
|
| 194 |
+
})
|
|
|
|
|
|
|
| 195 |
return jobs
|
| 196 |
|
|
|
|
| 197 |
class VideoSubtitleProcessor:
|
| 198 |
def __init__(self, job_id, logger):
|
| 199 |
self.temp_dir = tempfile.mkdtemp()
|
| 200 |
self.job_id = job_id
|
| 201 |
self.logger = logger
|
| 202 |
+
|
| 203 |
def download_video(self, url, index, total):
|
| 204 |
"""Download video with progress tracking"""
|
| 205 |
try:
|
| 206 |
self.logger.log(f"Downloading video {index}/{total}: {url[:50]}...")
|
| 207 |
+
JobStatus.update(self.job_id,
|
| 208 |
+
current_step=f"Downloading video {index}/{total}",
|
| 209 |
+
progress=int((index-1)/total * 30))
|
| 210 |
+
|
| 211 |
+
# Handle PixelDrain URLs
|
|
|
|
| 212 |
if "pixeldrain.com" in url:
|
| 213 |
+
match = re.search(r'/u/([a-zA-Z0-9_-]+)', url)
|
| 214 |
if match:
|
| 215 |
file_id = match.group(1)
|
| 216 |
+
# Use direct API endpoint with download parameter
|
| 217 |
+
download_url = f"https://pixeldrain.com/api/file/{file_id}?download"
|
| 218 |
+
self.logger.log(f"PixelDrain file ID: {file_id}")
|
| 219 |
else:
|
| 220 |
download_url = url
|
| 221 |
else:
|
| 222 |
download_url = url
|
| 223 |
+
|
| 224 |
+
# Add headers to avoid connection issues
|
| 225 |
+
headers = {
|
| 226 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
response = requests.get(download_url, stream=True, headers=headers, timeout=120)
|
| 230 |
response.raise_for_status()
|
| 231 |
+
|
| 232 |
filename = "video.mp4"
|
| 233 |
+
if 'Content-Disposition' in response.headers:
|
| 234 |
+
cd = response.headers['Content-Disposition']
|
| 235 |
+
if 'filename=' in cd:
|
| 236 |
+
filename = cd.split('filename=')[1].strip('"\'')
|
| 237 |
+
|
| 238 |
+
filename = re.sub(r'[<>:"/\\|?*]', '_', filename)
|
| 239 |
+
if not filename.endswith(('.mp4', '.mkv', '.avi', '.mov', '.webm')):
|
| 240 |
+
filename += '.mp4'
|
| 241 |
+
|
| 242 |
filepath = os.path.join(self.temp_dir, filename)
|
| 243 |
+
|
| 244 |
+
total_size = int(response.headers.get('content-length', 0))
|
| 245 |
downloaded = 0
|
| 246 |
+
|
| 247 |
+
with open(filepath, 'wb') as f:
|
| 248 |
for chunk in response.iter_content(chunk_size=8192):
|
| 249 |
if chunk:
|
| 250 |
f.write(chunk)
|
| 251 |
downloaded += len(chunk)
|
| 252 |
+
|
| 253 |
+
self.logger.log(f"β
Downloaded: {filename} ({downloaded/1024/1024:.1f} MB)")
|
|
|
|
|
|
|
| 254 |
return filepath
|
| 255 |
+
|
| 256 |
except Exception as e:
|
| 257 |
self.logger.log(f"β Download failed: {str(e)}")
|
| 258 |
raise Exception(f"Download failed: {str(e)}")
|
| 259 |
+
|
| 260 |
def fix_subtitle_encoding(self, subtitle_file):
|
| 261 |
"""Fix Sinhala subtitle encoding"""
|
| 262 |
try:
|
| 263 |
self.logger.log("Fixing subtitle encoding...")
|
| 264 |
+
|
| 265 |
+
encodings = ['utf-8', 'utf-16', 'iso-8859-1', 'windows-1252']
|
| 266 |
content = None
|
| 267 |
+
|
| 268 |
for encoding in encodings:
|
| 269 |
try:
|
| 270 |
+
with open(subtitle_file, 'r', encoding=encoding) as f:
|
| 271 |
content = f.read()
|
| 272 |
break
|
| 273 |
except:
|
| 274 |
continue
|
| 275 |
+
|
| 276 |
if content is None:
|
| 277 |
+
with open(subtitle_file, 'rb') as f:
|
| 278 |
+
content = f.read().decode('utf-8', errors='ignore')
|
| 279 |
+
|
| 280 |
+
cleaned_content = ''
|
| 281 |
for char in content:
|
| 282 |
code = ord(char)
|
| 283 |
+
if (0x0D80 <= code <= 0x0DFF or
|
| 284 |
+
0x0020 <= code <= 0x007E or
|
| 285 |
+
code in [0x000A, 0x000D, 0x0009] or
|
| 286 |
+
0x00A0 <= code <= 0x00FF):
|
|
|
|
|
|
|
| 287 |
cleaned_content += char
|
| 288 |
elif code > 0x007F:
|
| 289 |
cleaned_content += char
|
| 290 |
+
|
| 291 |
+
fixed_file = subtitle_file + '.fixed.srt'
|
| 292 |
+
with open(fixed_file, 'w', encoding='utf-8') as f:
|
| 293 |
f.write(cleaned_content)
|
| 294 |
+
|
| 295 |
self.logger.log("β
Subtitle encoding fixed")
|
| 296 |
return fixed_file
|
| 297 |
+
|
| 298 |
except Exception as e:
|
| 299 |
self.logger.log(f"β Subtitle fix failed: {str(e)}")
|
| 300 |
raise Exception(f"Subtitle encoding fix failed: {str(e)}")
|
| 301 |
+
|
| 302 |
+
def hardcode_subtitle_single(self, video_path, subtitle_path, output_path, index, total):
|
|
|
|
|
|
|
| 303 |
"""Hardcode subtitle with progress tracking"""
|
| 304 |
try:
|
| 305 |
+
self.logger.log(f"Processing video {index}/{total}: {os.path.basename(video_path)}")
|
| 306 |
+
JobStatus.update(self.job_id,
|
| 307 |
+
current_step=f"Hardcoding subtitles {index}/{total}",
|
| 308 |
+
progress=30 + int((index-1)/total * 50))
|
| 309 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
fixed_subtitle = self.fix_subtitle_encoding(subtitle_path)
|
| 311 |
+
|
| 312 |
+
temp_sub = os.path.join(self.temp_dir, f"temp_sub_{os.getpid()}_{index}.srt")
|
|
|
|
|
|
|
| 313 |
shutil.copy(fixed_subtitle, temp_sub)
|
| 314 |
+
|
| 315 |
+
if os.name == 'nt':
|
| 316 |
+
subtitle_escaped = temp_sub.replace('\\', '\\\\').replace(':', '\\:')
|
| 317 |
else:
|
| 318 |
+
subtitle_escaped = temp_sub.replace(':', '\\:')
|
| 319 |
+
|
| 320 |
cmd = [
|
| 321 |
+
'ffmpeg',
|
| 322 |
+
'-i', video_path,
|
| 323 |
+
'-vf', f"subtitles='{subtitle_escaped}':force_style='FontName=Noto Sans Sinhala,FontSize=24,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=3,Outline=2,Shadow=1,MarginV=20'",
|
| 324 |
+
'-c:v', 'libx264',
|
| 325 |
+
'-c:a', 'copy',
|
| 326 |
+
'-preset', 'ultrafast',
|
| 327 |
+
'-crf', '23',
|
| 328 |
+
'-y',
|
| 329 |
+
output_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
]
|
| 331 |
+
|
| 332 |
process = subprocess.Popen(
|
| 333 |
cmd,
|
| 334 |
stdout=subprocess.PIPE,
|
| 335 |
stderr=subprocess.PIPE,
|
| 336 |
+
universal_newlines=True
|
| 337 |
)
|
| 338 |
+
|
| 339 |
process.wait()
|
| 340 |
+
|
| 341 |
for f in [fixed_subtitle, temp_sub]:
|
| 342 |
if os.path.exists(f):
|
| 343 |
try:
|
| 344 |
os.remove(f)
|
| 345 |
except:
|
| 346 |
pass
|
| 347 |
+
|
| 348 |
if process.returncode != 0:
|
| 349 |
raise Exception(f"FFmpeg failed")
|
| 350 |
+
|
| 351 |
if not os.path.exists(output_path) or os.path.getsize(output_path) == 0:
|
| 352 |
raise Exception("Output video not created")
|
| 353 |
+
|
| 354 |
self.logger.log(f"β
Processed: {os.path.basename(output_path)}")
|
| 355 |
JobStatus.update(self.job_id, processed_videos=index)
|
| 356 |
return output_path
|
| 357 |
+
|
| 358 |
except Exception as e:
|
| 359 |
self.logger.log(f"β Processing failed: {str(e)}")
|
| 360 |
raise Exception(f"Hardcoding failed: {str(e)}")
|
| 361 |
+
|
| 362 |
def upload_to_pixeldrain(self, filepath, api_key, index, total):
|
| 363 |
+
"""Upload with progress tracking to PixelDrain"""
|
| 364 |
try:
|
| 365 |
self.logger.log(f"Uploading {index}/{total} to PixelDrain...")
|
| 366 |
+
JobStatus.update(self.job_id,
|
| 367 |
+
current_step=f"Uploading {index}/{total} to PixelDrain",
|
| 368 |
+
progress=80 + int((index-1)/total * 10))
|
| 369 |
+
|
|
|
|
|
|
|
| 370 |
url = "https://pixeldrain.com/api/file"
|
| 371 |
filename = os.path.basename(filepath)
|
| 372 |
+
|
| 373 |
headers = {}
|
| 374 |
if api_key:
|
| 375 |
+
headers['Authorization'] = f'Basic {api_key}'
|
| 376 |
+
|
| 377 |
+
with open(filepath, 'rb') as f:
|
| 378 |
+
files = {'file': (filename, f, 'video/mp4')}
|
| 379 |
+
|
| 380 |
if api_key:
|
| 381 |
+
response = requests.post(url, files=files, headers=headers, timeout=600)
|
|
|
|
|
|
|
| 382 |
else:
|
| 383 |
response = requests.post(url, files=files, timeout=600)
|
| 384 |
+
|
| 385 |
response.raise_for_status()
|
| 386 |
+
|
| 387 |
result = response.json()
|
| 388 |
+
file_id = result.get('id')
|
| 389 |
+
|
| 390 |
if file_id:
|
| 391 |
download_link = f"https://pixeldrain.com/u/{file_id}"
|
| 392 |
+
self.logger.log(f"β
Uploaded to PixelDrain: {download_link}")
|
| 393 |
return download_link
|
| 394 |
else:
|
| 395 |
raise Exception("No file ID returned")
|
| 396 |
+
|
| 397 |
except Exception as e:
|
| 398 |
+
self.logger.log(f"β οΈ PixelDrain upload failed: {str(e)}")
|
| 399 |
+
raise Exception(f"PixelDrain upload failed: {str(e)}")
|
| 400 |
+
|
| 401 |
+
def upload_to_gofile(self, filepath, index, total, gofile_token=None):
|
| 402 |
+
"""Upload file to Gofile.io with optional authentication
|
| 403 |
+
|
| 404 |
+
Args:
|
| 405 |
+
filepath: Path to file to upload
|
| 406 |
+
index: Current file index
|
| 407 |
+
total: Total files to upload
|
| 408 |
+
gofile_token: Optional Gofile API token for authenticated uploads
|
| 409 |
+
|
| 410 |
+
Gofile API Token:
|
| 411 |
+
- Get token: https://gofile.io/myaccount (after login)
|
| 412 |
+
- Anonymous: 24h retention, slower speeds
|
| 413 |
+
- With token: Permanent storage, faster, file management
|
| 414 |
+
"""
|
| 415 |
+
try:
|
| 416 |
+
self.logger.log(f"Uploading {index}/{total} to Gofile.io...")
|
| 417 |
+
JobStatus.update(self.job_id,
|
| 418 |
+
current_step=f"Uploading {index}/{total} to Gofile",
|
| 419 |
+
progress=90 + int((index-1)/total * 10))
|
| 420 |
+
|
| 421 |
+
filename = os.path.basename(filepath)
|
| 422 |
+
|
| 423 |
+
# Step 1: Get best server (can use token for better server)
|
| 424 |
+
try:
|
| 425 |
+
headers = {}
|
| 426 |
+
if gofile_token:
|
| 427 |
+
headers['Authorization'] = f'Bearer {gofile_token}'
|
| 428 |
+
self.logger.log(f"Using authenticated Gofile upload")
|
| 429 |
+
|
| 430 |
+
server_response = requests.get(
|
| 431 |
+
'https://api.gofile.io/servers',
|
| 432 |
+
headers=headers,
|
| 433 |
+
timeout=30
|
| 434 |
+
)
|
| 435 |
+
server_data = server_response.json()
|
| 436 |
+
|
| 437 |
+
if server_data['status'] == 'ok':
|
| 438 |
+
# Get best available server
|
| 439 |
+
servers = server_data['data']['servers']
|
| 440 |
+
if servers:
|
| 441 |
+
server = servers[0]['name']
|
| 442 |
+
self.logger.log(f"Using Gofile server: {server}")
|
| 443 |
+
else:
|
| 444 |
+
server = 'store1'
|
| 445 |
+
else:
|
| 446 |
+
server = 'store1'
|
| 447 |
+
except Exception as e:
|
| 448 |
+
self.logger.log(f"Server selection failed, using fallback: {str(e)}")
|
| 449 |
+
server = 'store1'
|
| 450 |
+
|
| 451 |
+
# Step 2: Upload file
|
| 452 |
+
upload_url = f'https://{server}.gofile.io/contents/uploadfile'
|
| 453 |
+
|
| 454 |
+
# Prepare upload data
|
| 455 |
+
files = {'file': (filename, open(filepath, 'rb'), 'video/mp4')}
|
| 456 |
+
data = {}
|
| 457 |
+
headers = {}
|
| 458 |
+
|
| 459 |
+
# Add authentication if token provided
|
| 460 |
+
if gofile_token:
|
| 461 |
+
headers['Authorization'] = f'Bearer {gofile_token}'
|
| 462 |
+
# Can also specify folder ID if wanted
|
| 463 |
+
# data['folderId'] = 'folder_id_here'
|
| 464 |
+
|
| 465 |
+
try:
|
| 466 |
+
response = requests.post(
|
| 467 |
+
upload_url,
|
| 468 |
+
files=files,
|
| 469 |
+
data=data,
|
| 470 |
+
headers=headers,
|
| 471 |
+
timeout=600
|
| 472 |
+
)
|
| 473 |
+
response.raise_for_status()
|
| 474 |
+
|
| 475 |
+
result = response.json()
|
| 476 |
+
|
| 477 |
+
if result['status'] == 'ok':
|
| 478 |
+
# Get download link
|
| 479 |
+
file_code = result['data']['fileId']
|
| 480 |
+
download_page = result['data']['downloadPage']
|
| 481 |
+
|
| 482 |
+
if gofile_token:
|
| 483 |
+
self.logger.log(f"β
Uploaded to Gofile (authenticated): {download_page}")
|
| 484 |
+
else:
|
| 485 |
+
self.logger.log(f"β
Uploaded to Gofile (anonymous - 24h retention): {download_page}")
|
| 486 |
+
|
| 487 |
+
return download_page
|
| 488 |
+
else:
|
| 489 |
+
raise Exception(f"Gofile API error: {result.get('status', 'unknown')}")
|
| 490 |
+
finally:
|
| 491 |
+
# Close file handle
|
| 492 |
+
files['file'][1].close()
|
| 493 |
+
|
| 494 |
+
except Exception as e:
|
| 495 |
+
self.logger.log(f"β οΈ Gofile upload failed: {str(e)}")
|
| 496 |
+
raise Exception(f"Gofile upload failed: {str(e)}")
|
| 497 |
+
|
| 498 |
+
def process_multiple_videos(self, video_urls, subtitle_path, pixeldrain_api_key=None, gofile_token=None):
|
| 499 |
+
"""Process multiple videos in parallel"""
|
| 500 |
results = []
|
| 501 |
video_paths = []
|
| 502 |
+
|
| 503 |
try:
|
| 504 |
+
JobStatus.update(self.job_id, status='downloading')
|
| 505 |
+
|
| 506 |
# Download all videos
|
| 507 |
total = len(video_urls)
|
| 508 |
for i, url in enumerate(video_urls, 1):
|
| 509 |
video_path = self.download_video(url, i, total)
|
| 510 |
video_paths.append(video_path)
|
| 511 |
+
|
| 512 |
+
JobStatus.update(self.job_id, status='processing')
|
| 513 |
+
|
| 514 |
# Process in parallel
|
| 515 |
output_paths = []
|
| 516 |
+
|
| 517 |
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
| 518 |
futures = []
|
| 519 |
for i, video_path in enumerate(video_paths, 1):
|
| 520 |
output_name = f"output_{i}_{Path(video_path).stem}_subbed.mp4"
|
| 521 |
output_path = os.path.join(self.temp_dir, output_name)
|
| 522 |
output_paths.append(output_path)
|
| 523 |
+
|
| 524 |
future = executor.submit(
|
| 525 |
self.hardcode_subtitle_single,
|
| 526 |
video_path,
|
| 527 |
subtitle_path,
|
| 528 |
output_path,
|
| 529 |
i,
|
| 530 |
+
total
|
| 531 |
)
|
| 532 |
futures.append(future)
|
| 533 |
+
|
| 534 |
for future in futures:
|
| 535 |
try:
|
| 536 |
result = future.result()
|
| 537 |
results.append(result)
|
| 538 |
except Exception as e:
|
| 539 |
raise
|
| 540 |
+
|
| 541 |
+
JobStatus.update(self.job_id, status='uploading')
|
| 542 |
+
|
| 543 |
+
# Upload to PixelDrain and Gofile
|
| 544 |
uploaded_links = []
|
| 545 |
for i, output_path in enumerate(results, 1):
|
| 546 |
if os.path.exists(output_path):
|
| 547 |
+
upload_results = {}
|
| 548 |
+
|
| 549 |
+
# Try PixelDrain first
|
| 550 |
+
try:
|
| 551 |
+
pixeldrain_link = self.upload_to_pixeldrain(output_path, pixeldrain_api_key, i, len(results))
|
| 552 |
+
upload_results['pixeldrain'] = pixeldrain_link
|
| 553 |
+
except Exception as e:
|
| 554 |
+
self.logger.log(f"β οΈ PixelDrain upload failed, trying Gofile...")
|
| 555 |
+
upload_results['pixeldrain'] = None
|
| 556 |
+
|
| 557 |
+
# Always try Gofile as backup (with token if provided)
|
| 558 |
+
try:
|
| 559 |
+
gofile_link = self.upload_to_gofile(output_path, i, len(results), gofile_token)
|
| 560 |
+
upload_results['gofile'] = gofile_link
|
| 561 |
+
except Exception as e:
|
| 562 |
+
self.logger.log(f"β οΈ Gofile upload also failed")
|
| 563 |
+
upload_results['gofile'] = None
|
| 564 |
+
|
| 565 |
+
# Add results
|
| 566 |
+
if upload_results['pixeldrain'] or upload_results['gofile']:
|
| 567 |
+
uploaded_links.append(upload_results)
|
| 568 |
+
else:
|
| 569 |
+
raise Exception("Both PixelDrain and Gofile uploads failed!")
|
| 570 |
+
|
| 571 |
+
JobStatus.update(self.job_id,
|
| 572 |
+
status='completed',
|
| 573 |
+
current_step='All done!',
|
| 574 |
+
progress=100)
|
| 575 |
JobStatus.set_results(self.job_id, uploaded_links)
|
| 576 |
self.logger.log(f"π All {len(uploaded_links)} videos completed!")
|
| 577 |
+
|
| 578 |
return uploaded_links, results
|
| 579 |
+
|
| 580 |
except Exception as e:
|
| 581 |
+
JobStatus.update(self.job_id, status='failed', error=str(e))
|
| 582 |
self.logger.log(f"β Job failed: {str(e)}")
|
| 583 |
raise Exception(f"Processing failed: {str(e)}")
|
| 584 |
+
|
| 585 |
def cleanup(self):
|
| 586 |
"""Clean up temporary files"""
|
| 587 |
try:
|
|
|
|
| 590 |
except:
|
| 591 |
pass
|
| 592 |
|
| 593 |
+
def process_job_background(job_id, video_urls, subtitle_path, pixeldrain_api_key, gofile_token):
|
|
|
|
| 594 |
"""Background job processor"""
|
| 595 |
logger = JobLogger(job_id)
|
| 596 |
processor = VideoSubtitleProcessor(job_id, logger)
|
| 597 |
+
|
| 598 |
try:
|
| 599 |
uploaded_links, output_paths = processor.process_multiple_videos(
|
| 600 |
+
video_urls,
|
| 601 |
+
subtitle_path,
|
| 602 |
+
pixeldrain_api_key,
|
| 603 |
+
gofile_token
|
| 604 |
)
|
| 605 |
finally:
|
| 606 |
processor.cleanup()
|
| 607 |
if os.path.exists(subtitle_path):
|
| 608 |
os.remove(subtitle_path)
|
| 609 |
|
|
|
|
| 610 |
# Flask routes
|
| 611 |
+
@app.route('/')
|
| 612 |
def index():
|
| 613 |
+
return render_template('index.html')
|
| 614 |
|
| 615 |
+
@app.route('/jobs')
|
|
|
|
| 616 |
def jobs_list():
|
| 617 |
"""Get all jobs"""
|
| 618 |
jobs = JobStatus.get_all()
|
| 619 |
+
return jsonify({'jobs': jobs})
|
|
|
|
| 620 |
|
| 621 |
+
@app.route('/job/<job_id>')
|
| 622 |
def job_status(job_id):
|
| 623 |
"""Get job status"""
|
| 624 |
job = JobStatus.get(job_id)
|
| 625 |
if job:
|
| 626 |
return jsonify(job)
|
| 627 |
+
return jsonify({'error': 'Job not found'}), 404
|
| 628 |
|
| 629 |
+
@app.route('/process', methods=['POST'])
|
|
|
|
| 630 |
def process_videos():
|
| 631 |
try:
|
| 632 |
+
video_urls_text = request.form.get('video_urls', '')
|
| 633 |
+
subtitle_file = request.files.get('subtitle_file')
|
| 634 |
+
pixeldrain_api_key = request.form.get('pixeldrain_api_key', '').strip()
|
| 635 |
+
gofile_token = request.form.get('gofile_token', '').strip()
|
| 636 |
+
|
| 637 |
+
# Use environment variables as fallback
|
| 638 |
if not pixeldrain_api_key:
|
| 639 |
+
pixeldrain_api_key = os.environ.get('PIXELDRAIN_API_KEY', '').strip()
|
| 640 |
+
|
| 641 |
+
if not gofile_token:
|
| 642 |
+
gofile_token = os.environ.get('GOFILE_TOKEN', '').strip()
|
| 643 |
+
|
| 644 |
if not video_urls_text or not video_urls_text.strip():
|
| 645 |
+
return jsonify({'error': 'Please enter at least one video URL'}), 400
|
| 646 |
+
|
| 647 |
if not subtitle_file:
|
| 648 |
+
return jsonify({'error': 'Please upload a subtitle file'}), 400
|
| 649 |
+
|
| 650 |
+
video_urls = [url.strip() for url in video_urls_text.split('\n') if url.strip()]
|
| 651 |
+
|
| 652 |
if not video_urls:
|
| 653 |
+
return jsonify({'error': 'No valid video URLs found'}), 400
|
| 654 |
+
|
| 655 |
# Create job
|
| 656 |
job_id = str(uuid.uuid4())
|
| 657 |
JobStatus.create(job_id, len(video_urls))
|
| 658 |
+
|
| 659 |
# Small delay to ensure database write completes
|
| 660 |
time.sleep(0.1)
|
| 661 |
+
|
| 662 |
# Save subtitle file
|
| 663 |
subtitle_filename = secure_filename(subtitle_file.filename)
|
| 664 |
+
subtitle_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{job_id}_{subtitle_filename}")
|
|
|
|
|
|
|
| 665 |
subtitle_file.save(subtitle_path)
|
| 666 |
+
|
| 667 |
+
# Start background processing with both API keys
|
| 668 |
+
pixeldrain_key = pixeldrain_api_key if pixeldrain_api_key else None
|
| 669 |
+
gofile_key = gofile_token if gofile_token else None
|
| 670 |
+
|
| 671 |
thread = threading.Thread(
|
| 672 |
target=process_job_background,
|
| 673 |
+
args=(job_id, video_urls, subtitle_path, pixeldrain_key, gofile_key)
|
| 674 |
)
|
| 675 |
thread.daemon = True
|
| 676 |
thread.start()
|
| 677 |
+
|
| 678 |
+
return jsonify({
|
| 679 |
+
'success': True,
|
| 680 |
+
'job_id': job_id,
|
| 681 |
+
'message': 'Job started! You can close this page and check back later.'
|
| 682 |
+
})
|
| 683 |
+
|
|
|
|
|
|
|
| 684 |
except Exception as e:
|
| 685 |
print(f"Error: {e}")
|
| 686 |
import traceback
|
|
|
|
| 687 |
traceback.print_exc()
|
| 688 |
+
return jsonify({'error': str(e)}), 500
|
| 689 |
+
return jsonify({'error': str(e)}), 500
|
| 690 |
|
| 691 |
+
@app.route('/health')
|
| 692 |
def health():
|
| 693 |
+
return jsonify({'status': 'ok', 'service': 'Sinhala Subtitle Hardcoder'})
|
|
|
|
| 694 |
|
| 695 |
+
if __name__ == '__main__':
|
| 696 |
+
os.makedirs('templates', exist_ok=True)
|
| 697 |
+
app.run(host='0.0.0.0', port=7860, debug=False, threaded=True)
|
templates/index.html
CHANGED
|
@@ -380,10 +380,27 @@
|
|
| 380 |
</div>
|
| 381 |
|
| 382 |
<div class="form-group">
|
| 383 |
-
<label for="pixeldrain_api_key">
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
| 385 |
<div class="help-text">
|
| 386 |
-
π Get key: <a href="https://pixeldrain.com/user/api_keys" target="_blank" style="color: #667eea;">pixeldrain.com/user/api_keys</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
</div>
|
| 388 |
</div>
|
| 389 |
|
|
@@ -608,14 +625,47 @@
|
|
| 608 |
resultsContainer.style.display = 'block';
|
| 609 |
resultsList.innerHTML = '';
|
| 610 |
|
| 611 |
-
job.results.forEach((
|
| 612 |
const resultDiv = document.createElement('div');
|
| 613 |
resultDiv.className = 'result-link';
|
| 614 |
-
resultDiv.
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
`;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 619 |
resultsList.appendChild(resultDiv);
|
| 620 |
});
|
| 621 |
|
|
|
|
| 380 |
</div>
|
| 381 |
|
| 382 |
<div class="form-group">
|
| 383 |
+
<label for="pixeldrain_api_key">
|
| 384 |
+
PixelDrain API Key
|
| 385 |
+
<span style="font-weight: normal; color: #666;">(Optional)</span>
|
| 386 |
+
</label>
|
| 387 |
+
<input type="text" id="pixeldrain_api_key" name="pixeldrain_api_key" placeholder="Your PixelDrain API key (optional)" style="padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; width: 100%; font-family: 'Courier New', monospace;">
|
| 388 |
<div class="help-text">
|
| 389 |
+
π Get key: <a href="https://pixeldrain.com/user/api_keys" target="_blank" style="color: #667eea;">pixeldrain.com/user/api_keys</a><br>
|
| 390 |
+
π‘ With key: Upload to YOUR account, permanent storage
|
| 391 |
+
</div>
|
| 392 |
+
</div>
|
| 393 |
+
|
| 394 |
+
<div class="form-group">
|
| 395 |
+
<label for="gofile_token">
|
| 396 |
+
Gofile API Token
|
| 397 |
+
<span style="font-weight: normal; color: #666;">(Optional)</span>
|
| 398 |
+
</label>
|
| 399 |
+
<input type="text" id="gofile_token" name="gofile_token" placeholder="Your Gofile API token (optional)" style="padding: 12px; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 14px; width: 100%; font-family: 'Courier New', monospace;">
|
| 400 |
+
<div class="help-text">
|
| 401 |
+
π Get token: <a href="https://gofile.io/myProfile" target="_blank" style="color: #667eea;">gofile.io/myProfile</a> (after login)<br>
|
| 402 |
+
π‘ Without token: Anonymous upload (24h retention)<br>
|
| 403 |
+
π‘ With token: Permanent storage, faster speeds, file management
|
| 404 |
</div>
|
| 405 |
</div>
|
| 406 |
|
|
|
|
| 625 |
resultsContainer.style.display = 'block';
|
| 626 |
resultsList.innerHTML = '';
|
| 627 |
|
| 628 |
+
job.results.forEach((uploadResult, index) => {
|
| 629 |
const resultDiv = document.createElement('div');
|
| 630 |
resultDiv.className = 'result-link';
|
| 631 |
+
resultDiv.style.flexDirection = 'column';
|
| 632 |
+
resultDiv.style.alignItems = 'flex-start';
|
| 633 |
+
resultDiv.style.padding = '15px';
|
| 634 |
+
|
| 635 |
+
let html = `<div style="font-weight: 600; margin-bottom: 10px;">Video ${index + 1}:</div>`;
|
| 636 |
+
|
| 637 |
+
// Handle both old format (string) and new format (object)
|
| 638 |
+
if (typeof uploadResult === 'string') {
|
| 639 |
+
// Old format - just a link
|
| 640 |
+
html += `
|
| 641 |
+
<div style="display: flex; width: 100%; align-items: center; gap: 10px;">
|
| 642 |
+
<a href="${uploadResult}" target="_blank" style="flex: 1;">${uploadResult}</a>
|
| 643 |
+
<button class="copy-btn" onclick="copyLink('${uploadResult}')">Copy</button>
|
| 644 |
+
</div>
|
| 645 |
+
`;
|
| 646 |
+
} else {
|
| 647 |
+
// New format - object with pixeldrain and gofile
|
| 648 |
+
if (uploadResult.pixeldrain) {
|
| 649 |
+
html += `
|
| 650 |
+
<div style="display: flex; width: 100%; align-items: center; gap: 10px; margin-bottom: 8px;">
|
| 651 |
+
<span style="min-width: 80px; font-weight: 500;">π¦ PixelDrain:</span>
|
| 652 |
+
<a href="${uploadResult.pixeldrain}" target="_blank" style="flex: 1; word-break: break-all;">${uploadResult.pixeldrain}</a>
|
| 653 |
+
<button class="copy-btn" onclick="copyLink('${uploadResult.pixeldrain}')">Copy</button>
|
| 654 |
+
</div>
|
| 655 |
+
`;
|
| 656 |
+
}
|
| 657 |
+
if (uploadResult.gofile) {
|
| 658 |
+
html += `
|
| 659 |
+
<div style="display: flex; width: 100%; align-items: center; gap: 10px;">
|
| 660 |
+
<span style="min-width: 80px; font-weight: 500;">π Gofile:</span>
|
| 661 |
+
<a href="${uploadResult.gofile}" target="_blank" style="flex: 1; word-break: break-all;">${uploadResult.gofile}</a>
|
| 662 |
+
<button class="copy-btn" onclick="copyLink('${uploadResult.gofile}')">Copy</button>
|
| 663 |
+
</div>
|
| 664 |
+
`;
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
resultDiv.innerHTML = html;
|
| 669 |
resultsList.appendChild(resultDiv);
|
| 670 |
});
|
| 671 |
|