From e5dd902e8a89190f0998fea99c3b99564ea743c8 Mon Sep 17 00:00:00 2001
From: "juancarlos.cavero"
Date: Fri, 19 Dec 2025 20:30:13 +0100
Subject: [PATCH] added upload to social networks and change to fast-whisper
---
app.py | 205 ++++++++++++++++++++++-
dashboard/src/App.jsx | 208 +++++++++++++++++++++++-
dashboard/src/components/MediaInput.jsx | 10 +-
dashboard/src/components/ResultCard.jsx | 165 ++++++++++++++++++-
main.py | 50 +++++-
requirements.txt | 3 +-
6 files changed, 615 insertions(+), 26 deletions(-)
diff --git a/app.py b/app.py
index 98c8de0..433afb0 100644
--- a/app.py
+++ b/app.py
@@ -5,10 +5,12 @@ import threading
import json
import shutil
import glob
+import glob
+import time
import asyncio
from typing import Dict, Optional, List
from contextlib import asynccontextmanager
-from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request
+from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
@@ -126,6 +128,7 @@ def enqueue_output(out, job_id):
for line in iter(out.readline, b''):
decoded_line = line.decode('utf-8').strip()
if decoded_line:
+ print(f"📝 [Job Output] {decoded_line}")
if job_id in jobs:
jobs[job_id]['logs'].append(decoded_line)
except Exception as e:
@@ -142,6 +145,7 @@ async def run_job(job_id, job_data):
jobs[job_id]['status'] = 'processing'
jobs[job_id]['logs'].append("Job started by worker.")
+ print(f"🎬 [run_job] Executing command for {job_id}: {' '.join(cmd)}")
try:
process = subprocess.Popen(
@@ -157,10 +161,44 @@ async def run_job(job_id, job_data):
t_log.daemon = True
t_log.start()
- # Async wait for process
+ # Async wait for process with incremental updates
+ start_wait = time.time()
while process.poll() is None:
- await asyncio.sleep(1)
+ await asyncio.sleep(2)
+ # Check for partial results every 2 seconds
+ # Look for metadata file
+ try:
+ json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
+ if json_files:
+ target_json = json_files[0]
+ # Read metadata (it might be being written to, so simple try/except or just read)
+ # Use a lock or just robust read? json.load might fail if file is partial.
+ # Usually main.py writes it once at start (based on my review).
+ if os.path.getsize(target_json) > 0:
+ with open(target_json, 'r') as f:
+ data = json.load(f)
+
+ base_name = os.path.basename(target_json).replace('_metadata.json', '')
+ clips = data.get('shorts', [])
+
+ # Check which clips actually exist on disk
+ ready_clips = []
+ for i, clip in enumerate(clips):
+ clip_filename = f"{base_name}_clip_{i+1}.mp4"
+ clip_path = os.path.join(output_dir, clip_filename)
+ if os.path.exists(clip_path) and os.path.getsize(clip_path) > 0:
+ # Checking if file is growing? For now assume if it exists and main.py moves it there, it's done.
+ # main.py writes to temp_... then moves to final name. So presence means ready!
+ clip['video_url'] = f"/videos/{job_id}/{clip_filename}"
+ ready_clips.append(clip)
+
+ if ready_clips:
+ jobs[job_id]['result'] = {'clips': ready_clips}
+ except Exception as e:
+ # Ignore read errors during processing
+ pass
+
returncode = process.returncode
if returncode == 0:
@@ -268,3 +306,164 @@ async def get_status(job_id: str):
"logs": job['logs'],
"result": job.get('result')
}
+
+class SocialPostRequest(BaseModel):
+ job_id: str
+ clip_index: int
+ api_key: str
+ user_id: str
+ platforms: List[str] # ["tiktok", "instagram", "youtube"]
+ # Optional overrides if frontend wants to edit them
+ title: Optional[str] = None
+ tiktok_description: Optional[str] = None
+ instagram_description: Optional[str] = None
+ youtube_description: Optional[str] = None
+
+import httpx
+
+@app.post("/api/social/post")
+async def post_to_socials(req: SocialPostRequest):
+ if req.job_id not in jobs:
+ raise HTTPException(status_code=404, detail="Job not found")
+
+ job = jobs[req.job_id]
+ if 'result' not in job or 'clips' not in job['result']:
+ raise HTTPException(status_code=400, detail="Job result not available")
+
+ try:
+ clip = job['result']['clips'][req.clip_index]
+ # Video URL is relative /videos/..., we need absolute file path
+ # clip['video_url'] is like "/videos/{job_id}/{filename}"
+ # We constructed it as: f"/videos/{job_id}/{clip_filename}"
+ # And file is at f"{OUTPUT_DIR}/{job_id}/{clip_filename}"
+
+ filename = clip['video_url'].split('/')[-1]
+ file_path = os.path.join(OUTPUT_DIR, req.job_id, filename)
+
+ if not os.path.exists(file_path):
+ raise HTTPException(status_code=404, detail=f"Video file not found: {file_path}")
+
+ # Construct parameters for Upload-Post API
+ # Fallbacks
+ final_title = req.title or clip.get('title', 'Viral Short')
+
+ # Prepare form data
+ url = "https://api.upload-post.com/api/upload"
+ headers = {
+ "Authorization": f"Apikey {req.api_key}"
+ }
+
+ data = {
+ "user": req.user_id,
+ "title": final_title,
+ "privacy_level": "PUBLIC_TO_EVERYONE", # TikTok
+ "privacyStatus": "public", # YouTube
+ "media_type": "REELS", # Instagram
+ }
+
+ # Add platforms
+ for p in req.platforms:
+ data.update({f"platform[{len(data.get('platform', [])) if 'platform' in data else 0}]": p})
+ # Wait, httpx/requests handling of list params can be tricky.
+ # Usually list of tuples [('platform[]', 'tiktok'), ('platform[]', 'instagram')] works.
+
+ # Prepare data as dict (httpx handles lists for multiple values)
+ data_payload = {
+ "user": req.user_id,
+ "title": final_title,
+ "platform[]": req.platforms # Pass list directly
+ }
+
+ # Add Platform specifics
+ if "tiktok" in req.platforms:
+ desc = req.tiktok_description or clip.get('social_descriptions', {}).get('tiktok', final_title)
+ data_payload["tiktok_title"] = desc
+
+ if "instagram" in req.platforms:
+ desc = req.instagram_description or clip.get('social_descriptions', {}).get('instagram', final_title)
+ data_payload["instagram_title"] = desc
+ data_payload["media_type"] = "REELS"
+
+ if "youtube" in req.platforms:
+ desc = req.youtube_description or clip.get('social_descriptions', {}).get('instagram', final_title) # Fallback
+ data_payload["youtube_title"] = final_title
+ data_payload["youtube_description"] = desc
+ data_payload["privacyStatus"] = "public"
+
+ # Send File
+ # httpx AsyncClient requires async file reading or bytes.
+ # Since we have MAX_FILE_SIZE_MB, reading into memory is safe-ish.
+ with open(file_path, "rb") as f:
+ file_content = f.read()
+
+ files = {
+ "video": (filename, file_content, "video/mp4")
+ }
+
+ # Switch to synchronous Client to avoid "sync request with AsyncClient" error with multipart/files
+ with httpx.Client(timeout=120.0) as client:
+ print(f"📡 Sending to Upload-Post for platforms: {req.platforms}")
+ response = client.post(url, headers=headers, data=data_payload, files=files)
+
+ if response.status_code not in [200, 201, 202]: # Added 201
+ print(f"❌ Upload-Post Error: {response.text}")
+ raise HTTPException(status_code=response.status_code, detail=f"Vendor API Error: {response.text}")
+
+ return response.json()
+
+ except Exception as e:
+ print(f"❌ Social Post Exception: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+@app.get("/api/social/user")
+async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")):
+ """Proxy to fetch user ID from Upload-Post"""
+ if not api_key:
+ raise HTTPException(status_code=400, detail="Missing X-Upload-Post-Key header")
+
+ url = "https://api.upload-post.com/api/uploadposts/users"
+ print(f"🔍 Fetching User ID from: {url}")
+ headers = {"Authorization": f"Apikey {api_key}"}
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ try:
+ resp = await client.get(url, headers=headers)
+ if resp.status_code != 200:
+ print(f"❌ Upload-Post User Fetch Error: {resp.text}")
+ raise HTTPException(status_code=resp.status_code, detail=f"Failed to fetch user: {resp.text}")
+
+ data = resp.json()
+ print(f"🔍 Upload-Post User Response: {data}")
+
+ user_id = None
+ # The structure is {'success': True, 'profiles': [{'username': '...'}, ...]}
+ profiles_list = []
+ if isinstance(data, dict):
+ raw_profiles = data.get('profiles', [])
+ if isinstance(raw_profiles, list):
+ for p in raw_profiles:
+ username = p.get('username')
+ if username:
+ # Determine connected platforms
+ socials = p.get('social_accounts', {})
+ connected = []
+ # Check typical platforms
+ for platform in ['tiktok', 'instagram', 'youtube']:
+ account_info = socials.get(platform)
+ # If it's a dict and typically has data, or just not empty string
+ if isinstance(account_info, dict):
+ connected.append(platform)
+
+ profiles_list.append({
+ "username": username,
+ "connected": connected
+ })
+
+ if not profiles_list:
+ # Fallback if no profiles found
+ return {"profiles": [], "error": "No profiles found"}
+
+ return {"profiles": profiles_list}
+
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx
index 7d3066c..a159e88 100644
--- a/dashboard/src/App.jsx
+++ b/dashboard/src/App.jsx
@@ -1,9 +1,87 @@
import React, { useState, useEffect } from 'react';
-import { Sparkles, Activity } from 'lucide-react';
+import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
+// Simple TikTok icon sine Lucide might not have it or it varies
+const TikTokIcon = ({ size = 16, className = "" }) => (
+
+
+
+);
+
+const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => {
+ const [isOpen, setIsOpen] = useState(false);
+
+ if (!profiles || profiles.length === 0) return null;
+
+ const selectedProfile = profiles.find(p => p.username === selectedUserId) || profiles[0];
+
+ return (
+
+
Select User Profile
+
setIsOpen(!isOpen)}
+ className="w-full flex items-center justify-between bg-black/20 border border-white/10 rounded-lg px-4 py-2 text-sm text-zinc-300 hover:bg-black/30 transition-colors"
+ >
+
+ {selectedProfile?.username || "Select User"}
+ {selectedProfile && (
+
+ {selectedProfile.connected.includes('tiktok') && }
+ {selectedProfile.connected.includes('instagram') && }
+ {selectedProfile.connected.includes('youtube') && }
+
+ )}
+
+
+
+
+ {isOpen && (
+
+
+ {profiles.map((profile) => (
+
{
+ onSelect(profile.username);
+ setIsOpen(false);
+ }}
+ className="w-full flex items-center justify-between px-4 py-3 hover:bg-white/5 transition-colors text-left group border-b border-white/5 last:border-0"
+ >
+
+
+ {profile.username.substring(0, 2).toUpperCase()}
+
+
+
+ {profile.username}
+
+
+ {/* Status indicators */}
+
+
+
+
+
+
+
+
+
+
+
+
+ {selectedUserId === profile.username && }
+
+ ))}
+
+
+ )}
+
+ );
+};
+
// Mock polling function
const pollJob = async (jobId) => {
const res = await fetch(`/api/status/${jobId}`);
@@ -13,6 +91,10 @@ const pollJob = async (jobId) => {
function App() {
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
+ // Social API State
+ const [uploadPostKey, setUploadPostKey] = useState(() => localStorage.getItem('uploadPostKey') || '');
+ const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || '');
+ const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []}
const [jobId, setJobId] = useState(null);
const [status, setStatus] = useState('idle'); // idle, processing, complete, error
const [results, setResults] = useState(null);
@@ -23,15 +105,34 @@ function App() {
if (apiKey) localStorage.setItem('gemini_key', apiKey);
}, [apiKey]);
+ useEffect(() => {
+ localStorage.setItem('uploadPostKey', uploadPostKey);
+ localStorage.setItem('uploadUserId', uploadUserId);
+ }, [uploadPostKey, uploadUserId]);
+
+ // Auto-fetch profiles when key is set (and not just on mount, but when key changes we might want to debounce or wait)
+ // But user said "when I reload the web I have to hit load profiles".
+ // So on mount, if key exists, fetch.
+ useEffect(() => {
+ if (uploadPostKey && userProfiles.length === 0) {
+ fetchUserProfiles();
+ }
+ }, [uploadPostKey]);
+
useEffect(() => {
let interval;
- if (status === 'processing' && jobId) {
+ if ((status === 'processing' || status === 'completed') && jobId) {
interval = setInterval(async () => {
try {
const data = await pollJob(jobId);
console.log("Job status:", data);
- if (data.status === 'completed') {
+
+ // Update results if available (real-time)
+ if (data.result) {
setResults(data.result);
+ }
+
+ if (data.status === 'completed') {
setStatus('complete');
clearInterval(interval);
} else if (data.status === 'failed') {
@@ -50,6 +151,30 @@ function App() {
return () => clearInterval(interval);
}, [status, jobId]);
+
+ const fetchUserProfiles = async () => {
+ if (!uploadPostKey) return;
+ try {
+ const res = await fetch('/api/social/user', {
+ headers: { 'X-Upload-Post-Key': uploadPostKey }
+ });
+ if (!res.ok) throw new Error("Failed to fetch");
+ const data = await res.json();
+ if (data.profiles && data.profiles.length > 0) {
+ setUserProfiles(data.profiles);
+ // Auto select first if none selected
+ if (!uploadUserId) {
+ setUploadUserId(data.profiles[0].username);
+ }
+ } else {
+ alert("No profiles found for this API Key.");
+ }
+ } catch (e) {
+ alert("Error fetching User Profiles. Please check key.");
+ console.error(e);
+ }
+ };
+
const handleProcess = async (data) => {
setStatus('processing');
setLogs(["Starting process..."]);
@@ -107,7 +232,73 @@ function App() {
-
+
+
+
+
+
+
+
+
Upload-Post API Key (Optional)
+
+ setUploadPostKey(e.target.value)}
+ className="flex-1 bg-black/20 border border-white/10 rounded-lg px-4 py-2 text-sm text-zinc-300 focus:outline-none focus:border-primary/50 transition-colors"
+ />
+
+ Load Profiles
+
+
+
+
+ {userProfiles.length > 0 ? (
+
+ ) : (
+
+ Upload-Post User ID
+ setUploadUserId(e.target.value)}
+ className="w-full bg-black/20 border border-white/10 rounded-lg px-4 py-2 text-sm text-zinc-300 focus:outline-none focus:border-primary/50 transition-colors"
+ />
+
+ )}
+
+
+
+
+ Social Auto-Post
+
+
+ Connect your accounts to post directly to TikTok, Instagram & YouTube.
+
+
+ Post directly to all your social networks. Start with a free trial (no credit card required). Simply connect your accounts, generate an API Key, and you're ready to go.
+
+
+ Get Account Used
+
+
+
+
+
@@ -170,7 +361,14 @@ function App() {
{results.clips.map((clip, i) => (
-
+
))}
diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx
index ff2fec9..40a08fb 100644
--- a/dashboard/src/components/MediaInput.jsx
+++ b/dashboard/src/components/MediaInput.jsx
@@ -29,8 +29,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
setMode('url')}
className={`flex items-center gap-2 pb-2 px-2 transition-all ${mode === 'url'
- ? 'text-primary border-b-2 border-primary -mb-[17px]'
- : 'text-zinc-400 hover:text-white'
+ ? 'text-primary border-b-2 border-primary -mb-[17px]'
+ : 'text-zinc-400 hover:text-white'
}`}
>
@@ -39,8 +39,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
setMode('file')}
className={`flex items-center gap-2 pb-2 px-2 transition-all ${mode === 'file'
- ? 'text-primary border-b-2 border-primary -mb-[17px]'
- : 'text-zinc-400 hover:text-white'
+ ? 'text-primary border-b-2 border-primary -mb-[17px]'
+ : 'text-zinc-400 hover:text-white'
}`}
>
@@ -107,7 +107,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
>
) : (
<>
- Start Automation
+ Generate Clips
>
)}
diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx
index 86210d5..800c10f 100644
--- a/dashboard/src/components/ResultCard.jsx
+++ b/dashboard/src/components/ResultCard.jsx
@@ -1,9 +1,68 @@
-import React from 'react';
-import { Download, Share2, Instagram, Youtube, Video } from 'lucide-react';
+import React, { useState } from 'react';
+import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2 } from 'lucide-react';
-export default function ResultCard({ clip, index }) {
- // clip contains: start, end, video_description_for_tiktok, etc.
- // We also expect a videoUrl or similar from the API response
+export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId }) {
+ const [showModal, setShowModal] = useState(false);
+ const [platforms, setPlatforms] = useState({
+ tiktok: true,
+ instagram: true,
+ youtube: true
+ });
+ const [posting, setPosting] = useState(false);
+ const [postResult, setPostResult] = useState(null); // { success: boolean, msg: string }
+
+ const handlePost = async () => {
+ if (!uploadPostKey || !uploadUserId) {
+ setPostResult({ success: false, msg: "Missing API Key or User ID. Configure them at the top." });
+ return;
+ }
+
+ const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
+ if (selectedPlatforms.length === 0) {
+ setPostResult({ success: false, msg: "Select at least one platform." });
+ return;
+ }
+
+ setPosting(true);
+ setPostResult(null);
+
+ try {
+ const res = await fetch('/api/social/post', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ job_id: jobId,
+ clip_index: index,
+ api_key: uploadPostKey,
+ user_id: uploadUserId,
+ platforms: selectedPlatforms
+ })
+ });
+
+ if (!res.ok) {
+ const errText = await res.text();
+ // Try parsing JSON error
+ try {
+ const jsonErr = JSON.parse(errText);
+ throw new Error(jsonErr.detail || errText);
+ } catch (e) {
+ throw new Error(errText);
+ }
+ }
+
+ const data = await res.json();
+ setPostResult({ success: true, msg: "Posted successfully! Check your social accounts." });
+ setTimeout(() => {
+ setShowModal(false);
+ setPostResult(null);
+ }, 3000);
+
+ } catch (e) {
+ setPostResult({ success: false, msg: `Failed: ${e.message}` });
+ } finally {
+ setPosting(false);
+ }
+ };
return (
@@ -65,8 +124,11 @@ export default function ResultCard({ clip, index }) {
-
- Share
+ setShowModal(true)}
+ className="flex-1 py-2 bg-white/5 hover:bg-white/10 rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2 text-white"
+ >
+ Post to Socials
+
+ {/* Modal */}
+ {showModal && (
+
+
+
setShowModal(false)}
+ className="absolute top-4 right-4 text-zinc-500 hover:text-white"
+ >
+
+
+
+
Post to Socials
+
+ {!uploadPostKey && (
+
+
+
+ Please configure your Upload-Post API Key at the top of the page first.
+
+
+ )}
+
+
+
+ {postResult && (
+
+ {postResult.success ?
:
}
+
{postResult.msg}
+
+ )}
+
+
+ {posting ? (
+ <>
+ Publishing...
+ >
+ ) : (
+ <>
+ Publish Now
+ >
+ )}
+
+
+
+ )}
);
}
diff --git a/main.py b/main.py
index 6e63d02..a48c73e 100644
--- a/main.py
+++ b/main.py
@@ -12,7 +12,9 @@ import os
import numpy as np
from tqdm import tqdm
import yt_dlp
-import whisper
+import yt_dlp
+# import whisper (replaced by faster_whisper inside function)
+from google import genai
from google import genai
from dotenv import load_dotenv
import json
@@ -380,10 +382,48 @@ def process_video_to_vertical(input_video, final_output_video):
return True
def transcribe_video(video_path):
- print("🎙️ Transcribing video with Whisper...")
- model_whisper = whisper.load_model("base")
- result = model_whisper.transcribe(video_path, word_timestamps=True)
- return result
+ print("🎙️ Transcribing video with Faster-Whisper (CPU Optimized)...")
+ from faster_whisper import WhisperModel
+
+ # Run on CPU with INT8 quantization for speed
+ model = WhisperModel("base", device="cpu", compute_type="int8")
+
+ segments, info = model.transcribe(video_path, word_timestamps=True)
+
+ print(f" Detected language '{info.language}' with probability {info.language_probability:.2f}")
+
+ # Convert to openai-whisper compatible format
+ transcript_segments = []
+ full_text = ""
+
+ for segment in segments:
+ # Print progress to keep user informed (and prevent timeouts feeling)
+ print(f" [{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
+
+ seg_dict = {
+ 'text': segment.text,
+ 'start': segment.start,
+ 'end': segment.end,
+ 'words': []
+ }
+
+ if segment.words:
+ for word in segment.words:
+ seg_dict['words'].append({
+ 'word': word.word,
+ 'start': word.start,
+ 'end': word.end,
+ 'probability': word.probability
+ })
+
+ transcript_segments.append(seg_dict)
+ full_text += segment.text + " "
+
+ return {
+ 'text': full_text.strip(),
+ 'segments': transcript_segments,
+ 'language': info.language
+ }
def get_viral_clips(transcript_result, video_duration):
print("🤖 Analyzing with Gemini...")
diff --git a/requirements.txt b/requirements.txt
index ea2fa0b..99d16c7 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -5,10 +5,11 @@ torch
torchvision
tqdm
yt-dlp
-openai-whisper
+faster-whisper
google-genai
python-dotenv
fastapi
uvicorn
python-multipart
+httpx