added upload to social networks and change to fast-whisper

This commit is contained in:
juancarlos.cavero 2025-12-19 20:30:13 +01:00
parent f7cc7b8fe3
commit e5dd902e8a
6 changed files with 615 additions and 26 deletions

205
app.py
View file

@ -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,9 +161,43 @@ 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
@ -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))

View file

@ -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 = "" }) => (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}>
<path d="M19.589 6.686a4.793 4.793 0 0 1-3.77-4.245V2h-3.445v13.672a2.896 2.896 0 0 1-5.201 1.743l-.002-.001.002.001a2.895 2.895 0 0 1 3.183-4.51v-3.5a6.329 6.329 0 0 0-5.394 10.692 6.33 6.33 0 0 0 10.857-4.424V8.687a8.182 8.182 0 0 0 4.773 1.526V6.79a4.831 4.831 0 0 1-1.003-.104z" />
</svg>
);
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 (
<div className="relative">
<label className="text-xs text-zinc-500 font-medium ml-1 mb-1 block">Select User Profile</label>
<button
onClick={() => 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"
>
<span className="flex items-center gap-2">
<span className="font-medium text-white">{selectedProfile?.username || "Select User"}</span>
{selectedProfile && (
<div className="flex gap-1">
{selectedProfile.connected.includes('tiktok') && <TikTokIcon size={12} className="text-white" />}
{selectedProfile.connected.includes('instagram') && <Instagram size={12} className="text-pink-500" />}
{selectedProfile.connected.includes('youtube') && <Youtube size={12} className="text-red-500" />}
</div>
)}
</span>
<ChevronDown size={14} className={`text-zinc-500 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
{isOpen && (
<div className="absolute bottom-full mb-2 left-0 right-0 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-xl z-50 overflow-hidden">
<div className="max-h-60 overflow-y-auto custom-scrollbar">
{profiles.map((profile) => (
<button
key={profile.username}
onClick={() => {
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"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-primary/20 to-purple-500/20 flex items-center justify-center text-xs font-bold text-white border border-white/10 shrink-0">
{profile.username.substring(0, 2).toUpperCase()}
</div>
<div className="min-w-0">
<div className="text-sm font-medium text-zinc-200 group-hover:text-white transition-colors truncate">
{profile.username}
</div>
<div className="flex gap-2 mt-0.5">
{/* Status indicators */}
<div className={`flex items-center gap-1 text-[10px] ${profile.connected.includes('tiktok') ? 'text-zinc-300' : 'text-zinc-600'}`}>
<TikTokIcon size={10} />
</div>
<div className={`flex items-center gap-1 text-[10px] ${profile.connected.includes('instagram') ? 'text-pink-400' : 'text-zinc-600'}`}>
<Instagram size={10} />
</div>
<div className={`flex items-center gap-1 text-[10px] ${profile.connected.includes('youtube') ? 'text-red-400' : 'text-zinc-600'}`}>
<Youtube size={10} />
</div>
</div>
</div>
</div>
{selectedUserId === profile.username && <Check size={14} className="text-primary shrink-0" />}
</button>
))}
</div>
</div>
)}
</div>
);
};
// 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,8 +232,74 @@ function App() {
</p>
</header>
<div className="space-y-4 mb-8">
<KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className="p-4 rounded-xl bg-white/5 border border-white/10 backdrop-blur-sm">
<div className="flex flex-col md:flex-row gap-6">
<div className="flex-1 space-y-4">
<div className="relative">
<label className="text-xs text-zinc-500 font-medium ml-1 mb-1 block">Upload-Post API Key (Optional)</label>
<div className="flex gap-2">
<input
type="password"
placeholder="ey..."
value={uploadPostKey}
onChange={(e) => 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"
/>
<button
onClick={fetchUserProfiles}
className="px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-xs font-medium text-zinc-300 transition-colors"
title="Fetch User Profiles"
>
Load Profiles
</button>
</div>
</div>
{userProfiles.length > 0 ? (
<UserProfileSelector
profiles={userProfiles}
selectedUserId={uploadUserId}
onSelect={setUploadUserId}
/>
) : (
<div className="relative">
<label className="text-xs text-zinc-500 font-medium ml-1 mb-1 block">Upload-Post User ID</label>
<input
type="text"
placeholder="User Identifier (or Load Profiles)"
value={uploadUserId}
onChange={(e) => 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"
/>
</div>
)}
</div>
<div className="md:w-64 bg-primary/5 border border-primary/10 rounded-lg p-3">
<h4 className="text-xs font-bold text-primary mb-2 flex items-center gap-1.5">
<Sparkles size={12} /> Social Auto-Post
</h4>
<p className="text-[11px] text-zinc-400 leading-relaxed mb-2">
Connect your accounts to post directly to TikTok, Instagram & YouTube.
</p>
<p className="text-[11px] text-zinc-400 leading-relaxed mb-3 border-l-2 border-white/10 pl-2">
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.
</p>
<a
href="https://app.upload-post.com/"
target="_blank"
className="block w-full py-1.5 bg-primary/10 hover:bg-primary/20 text-primary text-center rounded text-xs font-medium transition-colors"
>
Get Account Used
</a>
</div>
</div>
</div>
</div>
<div className="space-y-8">
<MediaInput onProcess={handleProcess} isProcessing={status === 'processing'} />
@ -170,7 +361,14 @@ function App() {
</h2>
<div className="grid gap-6">
{results.clips.map((clip, i) => (
<ResultCard key={i} clip={clip} index={i} />
<ResultCard
key={i}
clip={clip}
index={i}
jobId={jobId}
uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId}
/>
))}
</div>
</div>

View file

@ -107,7 +107,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
</>
) : (
<>
Start Automation
Generate Clips
</>
)}
</button>

View file

@ -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 (
<div className="glass-panel overflow-hidden animate-[fadeIn_0.5s_ease-out]" style={{ animationDelay: `${index * 0.1}s` }}>
@ -65,8 +124,11 @@ export default function ResultCard({ clip, index }) {
</div>
<div className="mt-6 pt-4 border-t border-white/10 flex gap-2">
<button 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">
<Share2 size={16} /> Share
<button
onClick={() => 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"
>
<Share2 size={16} /> Post to Socials
</button>
<a
href={clip.video_url}
@ -78,6 +140,95 @@ export default function ResultCard({ clip, index }) {
</div>
</div>
</div>
{/* Modal */}
{showModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]">
<div className="bg-zinc-900 border border-white/10 p-6 rounded-2xl w-full max-w-sm shadow-2xl relative">
<button
onClick={() => setShowModal(false)}
className="absolute top-4 right-4 text-zinc-500 hover:text-white"
>
<X size={20} />
</button>
<h3 className="text-xl font-bold text-white mb-4">Post to Socials</h3>
{!uploadPostKey && (
<div className="mb-4 p-3 bg-yellow-500/10 border border-yellow-500/20 text-yellow-200 text-sm rounded-lg flex items-start gap-2">
<AlertCircle size={16} className="mt-0.5 shrink-0" />
<div>
Please configure your Upload-Post API Key at the top of the page first.
</div>
</div>
)}
<div className="space-y-3 mb-6">
<label className="flex items-center gap-3 p-3 bg-white/5 rounded-lg cursor-pointer hover:bg-white/10 transition-colors border border-white/5">
<input
type="checkbox"
checked={platforms.tiktok}
onChange={e => setPlatforms({ ...platforms, tiktok: e.target.checked })}
className="w-4 h-4 rounded border-zinc-600 bg-black/50 text-primary focus:ring-primary"
/>
<div className="flex items-center gap-2">
<Video size={18} className="text-cyan-400" />
<span className="text-sm font-medium text-white">TikTok</span>
</div>
</label>
<label className="flex items-center gap-3 p-3 bg-white/5 rounded-lg cursor-pointer hover:bg-white/10 transition-colors border border-white/5">
<input
type="checkbox"
checked={platforms.instagram}
onChange={e => setPlatforms({ ...platforms, instagram: e.target.checked })}
className="w-4 h-4 rounded border-zinc-600 bg-black/50 text-primary focus:ring-primary"
/>
<div className="flex items-center gap-2">
<Instagram size={18} className="text-pink-400" />
<span className="text-sm font-medium text-white">Instagram</span>
</div>
</label>
<label className="flex items-center gap-3 p-3 bg-white/5 rounded-lg cursor-pointer hover:bg-white/10 transition-colors border border-white/5">
<input
type="checkbox"
checked={platforms.youtube}
onChange={e => setPlatforms({ ...platforms, youtube: e.target.checked })}
className="w-4 h-4 rounded border-zinc-600 bg-black/50 text-primary focus:ring-primary"
/>
<div className="flex items-center gap-2">
<Youtube size={18} className="text-red-400" />
<span className="text-sm font-medium text-white">YouTube Shorts</span>
</div>
</label>
</div>
{postResult && (
<div className={`mb-4 p-3 rounded-lg text-sm flex items-start gap-2 ${postResult.success ? 'bg-green-500/10 text-green-400' : 'bg-red-500/10 text-red-400'}`}>
{postResult.success ? <CheckCircle size={16} className="mt-0.5 shrink-0" /> : <AlertCircle size={16} className="mt-0.5 shrink-0" />}
<div>{postResult.msg}</div>
</div>
)}
<button
onClick={handlePost}
disabled={posting || !uploadPostKey}
className="w-full py-3 bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed rounded-xl text-white font-bold transition-all flex items-center justify-center gap-2"
>
{posting ? (
<>
<Loader2 size={18} className="animate-spin" /> Publishing...
</>
) : (
<>
<Share2 size={18} /> Publish Now
</>
)}
</button>
</div>
</div>
)}
</div>
);
}

50
main.py
View file

@ -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...")

View file

@ -5,10 +5,11 @@ torch
torchvision
tqdm
yt-dlp
openai-whisper
faster-whisper
google-genai
python-dotenv
fastapi
uvicorn
python-multipart
httpx