From 86117d3f3edc7024cc6e0be645a094c1b0ae48a5 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 19 Mar 2026 20:29:23 +0100 Subject: [PATCH] feat: AI Shorts low-cost mode, UGC gallery, universal business support - Add Low Cost video mode (Hailuo 2.3 + VEED Lipsync ~$0.65) alongside Premium (Kling Avatar v2 ~$2) - Add UGC video gallery with SEO pages (/gallery, /video/{id}) and JSON-LD structured data - Make AI Shorts work for any business (URL optional, manual description supported) - Add shared actor gallery on public S3 with prompt history - Add custom actor photo upload - Add Upload-Post social publishing to AI Shorts result step - Add UGC Gallery tab with Videos + Avatars tabs - Update landing page with 3-tools-in-1 section (Clip Generator, AI Shorts, YouTube Studio) - Rename SaaS Shorts to AI Shorts, Dashboard to Clip Generator - Add vite proxy for /gallery and /video routes - Add image upload validation - Remove hardcoded bucket names from code - Update README with full documentation and screenshot references Co-Authored-By: Claude Opus 4.6 (1M context) --- .env.example | 1 + README.md | 249 ++++++++----- app.py | 403 +++++++++++++++++++++- dashboard/src/App.jsx | 26 +- dashboard/src/Landing.jsx | 123 ++++++- dashboard/src/components/SaaShortsTab.jsx | 357 +++++++++++++++++-- dashboard/src/components/UGCGallery.jsx | 237 +++++++++++++ dashboard/vite.config.js | 8 + s3_uploader.py | 243 ++++++++++++- saasshorts.py | 139 +++++++- 10 files changed, 1619 insertions(+), 167 deletions(-) create mode 100644 dashboard/src/components/UGCGallery.jsx diff --git a/.env.example b/.env.example index ae49394..7a2e21f 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,7 @@ AWS_ACCESS_KEY_ID=your_aws_access_key_here AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here AWS_REGION=eu-west-3 AWS_S3_BUCKET=your-bucket-name +AWS_S3_PUBLIC_BUCKET=your-public-bucket-name # YouTube cookies (optional β€” paste Netscape-format cookies to bypass bot detection) # YOUTUBE_COOKIES=... diff --git a/README.md b/README.md index 9fdee3e..cb61cc2 100644 --- a/README.md +++ b/README.md @@ -1,143 +1,224 @@ -# OpenShorts.app πŸš€πŸŽ¬ +# OpenShorts.app [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) -OpenShorts is an all-in-one open-source solution to automate the creation and distribution of viral vertical content. It transforms long YouTube videos or local files into high-potential short clips optimized for **TikTok**, **Instagram Reels**, and **YouTube Shorts**. +**Free & open source AI video platform** with 3 tools in one: **Clip Generator**, **AI Shorts (UGC videos with AI actors)**, and **YouTube Studio**. Self-hosted with Docker. No watermarks, no limits. ![OpenShorts Demo](https://github.com/kamilstanuch/Autocrop-vertical/blob/main/churchil_queen_vertical_short.gif?raw=true) -### πŸ“Ί Video Tutorial: How it works +### Video Tutorial: How it works [![OpenShorts Tutorial](https://img.youtube.com/vi/xlyjD1qCaX0/maxresdefault.jpg)](https://www.youtube.com/watch?v=xlyjD1qCaX0 "Click to watch the video on YouTube") *Click the image above to watch the full walkthrough.* --- -## ✨ Key Features +## 3 Tools in 1 Platform -OpenShorts leverages state-of-the-art AI to handle the entire content lifecycle: +### 1. Clip Generator +Turn long YouTube videos or local uploads into viral-ready 9:16 shorts for TikTok, Instagram Reels, and YouTube Shorts. -1. **🧠 Viral Moment Detection:** - * **Faster-Whisper**: High-speed, CPU-optimized transcription and word-level timestamps. - * **Google Gemini 2.0 Flash**: Advanced AI analysis to identify the 3-15 most viral moments based on hooks and engagement potential. - * **Automatic Copywriting**: Generates SEO-optimized titles and descriptions for all platforms. +![Clip Generator](screenshots/clip-generator.png) -2. **βœ‚οΈ Smart AI Cropping & Tracking (New V2 Engine):** - * **Dual-Mode Strategy**: Automatically detects scene composition to apply the best framing strategy. - * **TRACK Mode (Single Subject)**: Uses **MediaPipe Face Detection** + **YOLOv8** fallback for ultra-fast, robust subject tracking. Features a **"Heavy Tripod" stabilization engine** that eliminates jitter and unnatural movements, providing smooth, cinematic reframing. Includes **Speaker Identification** to stick to the active speaker and avoid erratic switching. - * **GENERAL Mode (Groups/Landscapes)**: For scenes with multiple people or no clear subject, it automatically switches to a professional **blurred-background layout**, preserving the full width of the original shot while filling the 9:16 vertical space. - * **Intelligent Scene Analysis**: Pre-scans every scene to determine the optimal strategy before processing. +### 2. AI Shorts (UGC Video Creator) +Generate marketing videos with AI actors for **any product or business**. No camera, no studio, no influencer budget. Just describe your product or paste a URL. -3. **☁️ Automated S3 Backup:** - * **Silent Background Upload**: Once clips are generated, they are automatically uploaded to an AWS S3 bucket. - * **Seamless Integration**: Operates in the background without affecting processing logs or UI performance. +![AI Shorts Setup](screenshots/ai-shorts.png) -4. **πŸ“² Direct Social Posting:** - * **Upload-Post Integration**: Share your generated clips directly to TikTok, Instagram, and YouTube with a single click. - * **Profile Selector**: Manage multiple social accounts easily through the dashboard. +- **Two cost modes**: Low Cost (~$0.65/video) and Premium (~$2/video) +- Works for any business: SaaS, restaurants, e-commerce, coaching, local businesses +- AI-generated actors with lip-sync, voiceover, b-roll, and TikTok-style subtitles +- Choose from a shared avatar gallery or upload your own photo +- Publish directly to TikTok, Instagram, and YouTube -5. **πŸŽ™οΈ AI Voice Dubbing:** - * **ElevenLabs Integration**: Translate your clips to 30+ languages with AI-powered voice dubbing. - * **Voice Cloning**: Preserves the original speaker's voice characteristics in the new language. - * **Auto-Subtitles**: Automatically generates subtitles in the dubbed language. +### 3. YouTube Studio +Complete free AI YouTube toolkit: thumbnails, titles, descriptions, and direct publishing. -6. **🎨 Modern Web Dashboard:** - * **Real-time Progress**: Watch clips appear as they are generated with a live results feed. - * **Log Streaming**: Follow the technical process with real-time log updates. - * **Responsive Design**: A premium, dark-mode glassmorphism interface. +![YouTube Studio](screenshots/youtube-studio.png) -7. **πŸ“Ί YouTube Studio (Full Publishing Pipeline):** - * **AI Title Generation**: Upload a video and let Gemini analyze the transcript to suggest viral, SEO-optimized titles with AI-ranked top picks. - * **Title Refinement Chat**: Iteratively refine suggested titles via a built-in chat interface β€” ask for more clickbait, different tone, etc. - * **AI Thumbnail Generation**: Generate professional thumbnails with optional face overlay, custom background, and extra creative instructions. - * **AI Description with Chapters**: Automatically generates a YouTube description with chapter timestamps derived from the Whisper transcript. - * **One-Click YouTube Publishing**: Publish the final video with its title, thumbnail, and description directly to YouTube via Upload-Post integration. - * **Manual Mode**: Skip video analysis and enter your own title to jump straight to thumbnail generation. +- AI thumbnail generator with face overlay +- 10 viral title suggestions with refinement chat +- Auto-generated descriptions with chapter timestamps +- One-click publish to YouTube + +### UGC Video Gallery +All generated videos and avatars are saved to a public gallery with SEO pages for each video. + +![UGC Gallery](screenshots/ugc-gallery.png) + +- Public gallery page with hover-to-play (`/gallery`) +- Individual SEO video pages with og:video meta tags (`/video/{id}`) +- JSON-LD structured data for search engines +- Avatar gallery with prompt history --- -## πŸ› οΈ Requirements +## Key Features -* **Docker & Docker Compose**. -* **Google Gemini API Key** ([Get it for free here](https://aistudio.google.com/app/apikey)). -* **Upload-Post API Key** (Optional, for direct social posting. **Free tier available, no credit card required**). -* **ElevenLabs API Key** (Optional, for AI voice dubbing. [Get it here](https://elevenlabs.io)). +### Clip Generator +- **Viral Moment Detection**: Google Gemini 3.0 Flash analyzes transcripts and scene boundaries to detect 3-15 high-potential moments +- **Smart 9:16 Cropping**: Dual-mode AI reframing β€” TRACK mode (MediaPipe + YOLOv8 face tracking) and GENERAL mode (blurred background) +- **Auto Subtitles**: faster-whisper with word-level timestamps, styled and burned into clips +- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages with voice cloning +- **Hook Text Overlays**: AI-generated attention-grabbing text overlays +- **AI Video Effects**: Gemini-generated FFmpeg filters for professional effects -### πŸ“² Social Media Setup (Upload-Post) -To enable direct posting, follow these steps: -1. **Login/Register**: [app.upload-post.com/login](https://app.upload-post.com/login) -2. **Create Profile**: Go to [Manage Users](https://app.upload-post.com/manage-users) and create a user profile. -3. **Connect Accounts**: In the same section, connect your TikTok, Instagram, or YouTube accounts to that profile. -4. **Get API Key**: Navigate to [API Keys](https://app.upload-post.com/api-keys) and generate your key. -5. **Use in OpenShorts**: Paste the API Key and select your Profile in the dashboard. - +### AI Shorts Pipeline +1. **Analyze**: Scrape website URL + web research, or generate from manual description +2. **Script**: AI writes viral scripts (hook - problem - solution - CTA format) +3. **Actor**: Generate AI actors with Flux 2 Pro or select from shared gallery +4. **Voice**: ElevenLabs TTS voiceover (English/Spanish, male/female) +5. **Video**: Talking head generation (Hailuo 2.3 Fast img2video + VEED Lipsync) +6. **B-roll**: AI-generated visuals with Ken Burns effect +7. **Composite**: FFmpeg final assembly with subtitles and hook overlays +8. **Publish**: Direct posting to TikTok, Instagram Reels, YouTube Shorts via Upload-Post -### ☁️ AWS S3 Setup (Optional) -To enable automatic backup of your clips to S3: -1. **Environment Variables**: Set the following in your `.env` file or system environment: - * `AWS_ACCESS_KEY_ID`: Your AWS access key. - * `AWS_SECRET_ACCESS_KEY`: Your AWS secret key. - * `AWS_REGION`: (Optional) Defaults to `us-east-1`. - * `AWS_S3_BUCKET`: (Optional) Defaults to `openshorts.app-clips`. -2. **Bucket**: Clips are uploaded to the specified bucket automatically after generation. +### YouTube Studio +- AI-powered title generation with 10 viral options +- Interactive refinement chat for titles +- AI thumbnail generation with custom face + background +- Auto descriptions with chapter timestamps from Whisper transcript +- Direct YouTube publishing via Upload-Post +### Social Publishing +- One-click posting to TikTok, Instagram Reels, and YouTube Shorts +- Schedule posts for later +- Upload-Post integration with async uploads + +### Infrastructure +- S3 cloud backup (private bucket for clips, public bucket for gallery/avatars) +- SEO gallery pages served by FastAPI with JSON-LD structured data +- Shared avatar gallery across all users +- Async job queue with configurable concurrency --- -## πŸš€ Getting Started +## Requirements -The easiest way to run OpenShorts is using Docker Compose. +- **Docker & Docker Compose** +- **Google Gemini API Key** ([Free β€” get it here](https://aistudio.google.com/app/apikey)) β€” required for all AI features +- **fal.ai API Key** ([Pay-per-use](https://fal.ai)) β€” required for AI Shorts (actor generation, video, lip-sync) +- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) β€” required for voiceover/dubbing +- **Upload-Post API Key** (Optional, [free tier](https://upload-post.com)) β€” for direct social posting -### 1. Setup +--- + +## Getting Started + +### 1. Clone ```bash git clone https://github.com/your-username/OpenShorts.git cd OpenShorts ``` -### 2. Launch the Application +### 2. Configure (optional) +```bash +cp .env.example .env +# Edit .env with your AWS keys for S3 backup +``` + +### 3. Launch ```bash docker compose up --build ``` -### 3. Access the Dashboard -Open your browser and navigate to: -**`http://localhost:5173`** +### 4. Open Dashboard +Navigate to **`http://localhost:5175`** -1. Enter your **Gemini API Key**. -2. (Optional) Enter your **Upload-Post API Key** to enable social sharing. -3. Paste a **YouTube URL** or **Upload a Video**. -4. Click **"Generate Clips"** and watch the magic happen! +1. Go to **Settings** and enter your API keys (Gemini, fal.ai, ElevenLabs, Upload-Post) +2. **Clip Generator**: Paste a YouTube URL or upload a video to generate viral shorts +3. **AI Shorts**: Describe your product or paste a URL to generate UGC marketing videos +4. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube +5. **UGC Gallery**: Browse all generated videos and avatars --- -## πŸ—οΈ Technical Pipeline +## Technical Pipeline -1. **Ingestion**: Downloads YouTube videos via `yt-dlp` or handles local uploads. -2. **Transcription**: `faster-whisper` converts audio to text in seconds. -3. **AI Intelligence**: Gemini reads the transcript and selects periods of high interest. -4. **Extraction**: FFmpeg precisely cuts the selected segments. -5. **Reframing**: AI-powered visual tracking crops clips to vertical format. -6. **Backup**: Automated silent upload of clips and metadata to AWS S3. -7. **Distribution**: One-click posting via Upload-Post API. -8. **YouTube Studio**: Full publishing pipeline β€” AI titles, thumbnails, descriptions with chapters, and direct YouTube upload. +### Clip Generator +1. **Ingest** β€” YouTube download (yt-dlp) or local upload +2. **Transcribe** β€” faster-whisper with word-level timestamps +3. **Detect** β€” PySceneDetect for scene boundaries +4. **Analyze** β€” Gemini identifies 3-15 viral moments (15-60s each) +5. **Extract** β€” FFmpeg precise clip cutting +6. **Reframe** β€” AI vertical cropping with subject tracking +7. **Effects** β€” Subtitles, hooks, AI video effects +8. **Publish** β€” S3 backup + Upload-Post social distribution + +### AI Shorts +1. **Analyze** β€” Website scraping + Gemini web research (or manual description) +2. **Script** β€” Gemini generates viral scripts with segments +3. **Actor** β€” Flux 2 Pro portrait generation (or gallery/upload) +4. **Voice** β€” ElevenLabs TTS voiceover +5. **Video** β€” Hailuo 2.3 Fast img2video + VEED Lipsync (Low Cost) or Kling Avatar v2 (Premium) +6. **B-roll** β€” Flux 2 Pro image generation + Ken Burns effect +7. **Composite** β€” FFmpeg assembly with ASS subtitles and hook overlays +8. **Gallery** β€” Upload to public S3 with metadata for SEO pages +9. **Publish** β€” Upload-Post to TikTok, Instagram, YouTube --- -## πŸ”’ Security & Performance +## Tech Stack -* **Non-Root Execution**: Containers run as a dedicated `appuser` for security. -* **Concurrency Control**: Configurable job queue (`MAX_CONCURRENT_JOBS`). -* **Auto-Cleanup**: Automatic purging of old jobs and temporary files. -* **File Limits**: Built-in protection against oversized uploads. +| Layer | Technology | +|-------|-----------| +| Backend | Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx | +| Frontend | React 18, Vite 4, Tailwind CSS 3.4 | +| AI APIs | Google Gemini, fal.ai (Flux, Hailuo, VEED, Kling), ElevenLabs | +| Infrastructure | Docker + Docker Compose, AWS S3 | +| Publishing | Upload-Post API (TikTok, Instagram, YouTube) | --- -## 🀝 Contributions +## Environment Variables -Contributions are welcome! Whether it's adding new AI models or improving the cropping engine, feel free to open a PR. +**Server-side (.env):** +| Variable | Description | +|----------|------------| +| `AWS_ACCESS_KEY_ID` | AWS access key for S3 | +| `AWS_SECRET_ACCESS_KEY` | AWS secret key | +| `AWS_REGION` | AWS region (default: us-east-1) | +| `AWS_S3_BUCKET` | Private bucket for clip backup | +| `AWS_S3_PUBLIC_BUCKET` | Public bucket for gallery/avatars | +| `MAX_CONCURRENT_JOBS` | Concurrent processing limit (default: 5) | -## πŸ“„ License +**Client-side (encrypted in localStorage):** +| Key | Description | +|-----|------------| +| `GEMINI_API_KEY` | Google Gemini β€” required | +| `FAL_KEY` | fal.ai β€” required for AI Shorts | +| `ELEVENLABS_API_KEY` | ElevenLabs β€” required for voiceover/dubbing | +| `UPLOAD_POST_API_KEY` | Upload-Post β€” optional, for social posting | + +--- + +## Security & Performance + +- **Non-Root Execution**: Containers run as dedicated `appuser` +- **Concurrency Control**: Semaphore-based job queue (`MAX_CONCURRENT_JOBS`) +- **Auto-Cleanup**: Automatic purging of old jobs (1h retention) +- **Encrypted Keys**: API keys encrypted client-side, never stored server-side +- **Upload Validation**: Image uploads validated for format and minimum size +- **File Limits**: 2GB upload limit protection + +--- + +## Social Media Setup (Upload-Post) + +1. **Register**: [app.upload-post.com/login](https://app.upload-post.com/login) +2. **Create Profile**: Go to [Manage Users](https://app.upload-post.com/manage-users) +3. **Connect Accounts**: Link TikTok, Instagram, and/or YouTube +4. **Get API Key**: Navigate to [API Keys](https://app.upload-post.com/api-keys) +5. **Use in OpenShorts**: Paste the key in Settings + +--- + +## Contributions + +Contributions are welcome! Whether it's adding new AI models, improving the lip-sync pipeline, or building new features β€” feel free to open a PR. + +## License MIT License. OpenShorts is yours to use, modify, and scale. diff --git a/app.py b/app.py index 139b1d0..1a1e0ac 100644 --- a/app.py +++ b/app.py @@ -13,8 +13,9 @@ from contextlib import asynccontextmanager from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles +from fastapi.responses import HTMLResponse from pydantic import BaseModel -from s3_uploader import upload_job_artifacts, list_all_clips +from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery load_dotenv() @@ -1441,7 +1442,8 @@ saas_jobs: Dict[str, Dict] = {} class SaaSAnalyzeRequest(BaseModel): - url: str + url: Optional[str] = None + description: Optional[str] = None # Manual product/business description num_scripts: int = 3 style: str = "ugc" language: str = "en" @@ -1453,22 +1455,37 @@ async def saasshorts_analyze( req: SaaSAnalyzeRequest, x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key"), ): - """Scrape a SaaS URL, analyze it, and generate video scripts.""" + """Analyze a URL or manual description and generate video scripts.""" gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") if not gemini_key: raise HTTPException(status_code=400, detail="Missing Gemini API Key") + if not req.url and not req.description: + raise HTTPException(status_code=400, detail="Provide a URL or a product description") + try: loop = asyncio.get_event_loop() def run_analysis(): - # Phase 1a: Scrape the website directly - scraped = scrape_website(req.url) - # Phase 1b: Research across the web with Google Search grounding - web_research = research_saas_online(req.url, gemini_key) - # Phase 1c: Combine both sources into deep analysis - analysis = analyze_saas(scraped, gemini_key, web_research=web_research) - # Phase 1d: Generate scripts based on analysis + web_research = None + + if req.url and req.url.strip(): + # URL provided: full scrape + research pipeline + scraped = scrape_website(req.url) + web_research = research_saas_online(req.url, gemini_key) + analysis = analyze_saas(scraped, gemini_key, web_research=web_research) + else: + # Manual description: build analysis from description + analysis = { + "product_name": req.description.split(",")[0].strip()[:60] if req.description else "Product", + "description": req.description, + "value_proposition": req.description, + "target_audience": "general audience", + "key_features": [req.description], + "pain_points": [], + "tone": "casual and authentic", + } + scripts = generate_scripts(analysis, gemini_key, req.num_scripts, req.style, req.language, req.actor_gender) return { "analysis": analysis, @@ -1486,6 +1503,37 @@ async def saasshorts_analyze( class SaaSActorRequest(BaseModel): actor_description: str num_options: int = 3 + product_description: Optional[str] = None + + +@app.post("/api/saasshorts/actor-upload") +async def saasshorts_actor_upload(file: UploadFile = File(...)): + """Upload a custom actor image (stored locally only, not S3).""" + if not file.content_type or not file.content_type.startswith("image/"): + raise HTTPException(status_code=400, detail="File must be an image") + + try: + content = await file.read() + + # Validate minimum size + if len(content) < 1000: + raise HTTPException(status_code=400, detail="File too small to be a valid image") + + upload_id = uuid.uuid4().hex[:8] + upload_dir = os.path.join(OUTPUT_DIR, "actor_uploads") + os.makedirs(upload_dir, exist_ok=True) + filename = f"custom_{upload_id}.png" + file_path = os.path.join(upload_dir, filename) + + with open(file_path, "wb") as f: + f.write(content) + + return {"url": f"/videos/actor_uploads/{filename}"} + + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) @app.post("/api/saasshorts/actor-options") @@ -1504,25 +1552,301 @@ async def saasshorts_actor_options( os.makedirs(out_dir, exist_ok=True) loop = asyncio.get_running_loop() + import functools paths = await loop.run_in_executor( None, - generate_actor_images, - req.actor_description, fal_key, out_dir, "actor", req.num_options, + functools.partial( + generate_actor_images, + req.actor_description, fal_key, out_dir, "actor", req.num_options, + product_description=req.product_description, + ), ) - urls = [f"/videos/saas_actors_{job_id}/{os.path.basename(p)}" for p in paths] + # Upload each actor image to public S3 with description + desc = req.actor_description + if req.product_description: + desc += f" (holding {req.product_description})" + urls = [] + for p in paths: + s3_url = upload_actor_to_s3(p, description=desc) + if s3_url: + urls.append(s3_url) + else: + # Fallback to local URL if S3 fails + urls.append(f"/videos/saas_actors_{job_id}/{os.path.basename(p)}") + return {"images": urls} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) +@app.get("/api/saasshorts/gallery") +async def saasshorts_video_gallery(limit: int = 50): + """List all UGC videos from the public gallery.""" + try: + loop = asyncio.get_running_loop() + videos = await loop.run_in_executor(None, list_video_gallery, limit) + return {"videos": videos, "total": len(videos)} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +class SaaSPostRequest(BaseModel): + job_id: str + api_key: str + user_id: str + platforms: List[str] + title: Optional[str] = None + description: Optional[str] = None + scheduled_date: Optional[str] = None + timezone: Optional[str] = "UTC" + + +@app.post("/api/saasshorts/post") +async def saasshorts_post_to_socials(req: SaaSPostRequest): + """Post an AI Shorts video to social media via Upload-Post.""" + if req.job_id not in saas_jobs: + raise HTTPException(status_code=404, detail="Job not found") + + job = saas_jobs[req.job_id] + result = job.get("result") + if not result or not result.get("video_url"): + raise HTTPException(status_code=400, detail="No video available for this job") + + try: + # Resolve video file path + video_url = result["video_url"] # e.g. /videos/saas_xxx/slug_final.mp4 + rel_path = video_url.replace("/videos/", "") + file_path = os.path.join(OUTPUT_DIR, rel_path) + + if not os.path.exists(file_path): + raise HTTPException(status_code=404, detail=f"Video file not found") + + script = result.get("script", {}) + final_title = req.title or script.get("title", "AI Short") + final_description = req.description or script.get("caption", "") + if not final_description: + final_description = script.get("full_narration", "Check this out!") + + url = "https://api.upload-post.com/api/upload" + headers = {"Authorization": f"Apikey {req.api_key}"} + + data_payload = { + "user": req.user_id, + "title": final_title, + "platform[]": req.platforms, + "async_upload": "true", + } + + if req.scheduled_date: + data_payload["scheduled_date"] = req.scheduled_date + if req.timezone: + data_payload["timezone"] = req.timezone + + if "tiktok" in req.platforms: + data_payload["tiktok_title"] = final_description + if "instagram" in req.platforms: + data_payload["instagram_title"] = final_description + data_payload["media_type"] = "REELS" + if "youtube" in req.platforms: + data_payload["youtube_title"] = final_title + data_payload["youtube_description"] = final_description + data_payload["privacyStatus"] = "public" + + filename = os.path.basename(file_path) + with open(file_path, "rb") as f: + file_content = f.read() + + files = {"video": (filename, file_content, "video/mp4")} + + with httpx.Client(timeout=120.0) as client: + print(f"πŸ“‘ [AI Shorts] Sending to Upload-Post: {req.platforms}") + response = client.post(url, headers=headers, data=data_payload, files=files) + + if response.status_code not in [200, 201, 202]: + raise HTTPException(status_code=response.status_code, detail=f"Upload-Post Error: {response.text}") + + return response.json() + + except HTTPException: + raise + except Exception as e: + print(f"❌ [AI Shorts] Post Exception: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + +@app.get("/gallery", response_class=HTMLResponse) +async def gallery_html_page(): + """SEO gallery page with all generated UGC videos.""" + import html as html_mod + loop = asyncio.get_running_loop() + videos = await loop.run_in_executor(None, list_video_gallery, 100) + + cards_html = "" + ld_items = [] + for i, v in enumerate(videos): + title = html_mod.escape(v.get("title", "Untitled")) + video_url = v.get("video_url", "") + actor_url = v.get("actor_url", "") + video_id = v.get("video_id", "") + duration = v.get("duration", 0) + mode = v.get("video_mode", "") + product = html_mod.escape(v.get("product_name", "")) + caption = html_mod.escape(v.get("caption", "")[:120]) + + mode_badge = 'LOW COST' if mode == "lowcost" else 'PREMIUM' + + cards_html += f''' + +
+
+ +
{mode_badge}
+
+
+

{title}

+

{duration:.0f}s Β· {product}

+
+
+
''' + + ld_items.append(f'{{"@type":"ListItem","position":{i+1},"url":"https://openshorts.app/video/{video_id}","name":"{title}"}}') + + ld_json = f'{{"@context":"https://schema.org","@type":"CollectionPage","name":"AI UGC Video Gallery","mainEntity":{{"@type":"ItemList","numberOfItems":{len(videos)},"itemListElement":[{",".join(ld_items)}]}}}}' + + return f''' + + + +AI UGC Video Gallery | OpenShorts + + + + + + + + + + +

AI-Generated UGC Videos

+

{len(videos)} videos generated Β· Low Cost & Premium modes

+
{cards_html}
+
Create Your Own UGC Video
+''' + + +@app.get("/video/{video_id}", response_class=HTMLResponse) +async def video_html_page(video_id: str): + """SEO individual video page with og:video meta tags.""" + import html as html_mod + loop = asyncio.get_running_loop() + videos = await loop.run_in_executor(None, list_video_gallery, 200) + meta = next((v for v in videos if v.get("video_id") == video_id), None) + if not meta: + raise HTTPException(status_code=404, detail="Video not found") + + title = html_mod.escape(meta.get("title", "Untitled")) + caption = html_mod.escape(meta.get("caption", "")) + narration = html_mod.escape(meta.get("full_narration", "")) + video_url = meta.get("video_url", "") + actor_url = meta.get("actor_url", "") + duration = meta.get("duration", 0) + mode = meta.get("video_mode", "") + product = html_mod.escape(meta.get("product_name", "")) + product_url = html_mod.escape(meta.get("product_url", "")) + language = meta.get("language", "en") + hashtags = " ".join(meta.get("hashtags", [])) + cost = meta.get("cost_estimate", {}).get("total", 0) + created = meta.get("created_at", "") + actor_desc = html_mod.escape(meta.get("actor_description", "")) + + ld_json = f'{{"@context":"https://schema.org","@type":"VideoObject","name":"{title}","description":"{caption}","thumbnailUrl":"{actor_url}","contentUrl":"{video_url}","uploadDate":"{created}","duration":"PT{int(duration)}S","width":1080,"height":1920,"inLanguage":"{language}"}}' + + mode_label = "Low Cost" if mode == "lowcost" else "Premium" + + return f''' + + + +{title} - AI UGC Video | OpenShorts + + + + + + + + + + + + + + + + + +
+
+
+

{title}

+

{duration:.0f}s Β· {mode_label} Β· ${cost:.2f} Β· {product}

+

Caption

{caption}

{hashtags}

+

Script

{narration}

+

Actor

{actor_desc}

+{f'

Product

{product}

' if product_url else ''} +← Back to Gallery +
Create Your Own +
+
+''' + + +@app.get("/api/saasshorts/actor-gallery") +async def saasshorts_actor_gallery(): + """List all previously generated actor images from public S3.""" + try: + loop = asyncio.get_running_loop() + images = await loop.run_in_executor(None, list_actor_gallery) + return {"images": images} + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + class SaaSGenerateRequest(BaseModel): script: dict voice_id: Optional[str] = None actor_description: Optional[str] = None selected_actor_url: Optional[str] = None # Pre-selected actor image URL retry_job_id: Optional[str] = None + video_mode: str = "lowcost" # "lowcost" or "premium" @app.post("/api/saasshorts/generate") @@ -1575,12 +1899,26 @@ async def saasshorts_generate( "output_dir": job_output_dir, } - # If user selected a pre-generated actor, copy it into the job output dir + # If user selected a pre-generated actor, resolve it to a local path selected_actor_path = None if req.selected_actor_url: - src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "")) - if os.path.exists(src): - selected_actor_path = src + if req.selected_actor_url.startswith("http"): + # Download from S3 public URL to job output dir + import httpx + try: + actor_local = os.path.join(job_output_dir, "selected_actor.png") + with httpx.Client(timeout=30.0) as client: + resp = client.get(req.selected_actor_url) + if resp.status_code == 200: + with open(actor_local, "wb") as f: + f.write(resp.content) + selected_actor_path = actor_local + except Exception: + pass + else: + src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "")) + if os.path.exists(src): + selected_actor_path = src config = { "fal_key": fal_key, @@ -1588,6 +1926,7 @@ async def saasshorts_generate( "voice_id": req.voice_id or "21m00Tcm4TlvDq8ikWAM", "actor_description": req.actor_description, "selected_actor_path": selected_actor_path, + "video_mode": req.video_mode, } async def run_generation(): @@ -1617,6 +1956,36 @@ async def saasshorts_generate( } saas_jobs[job_id]["logs"].append("Video generation completed!") + # Upload to public gallery (non-blocking) + try: + gallery_meta = { + "title": req.script.get("title", "Untitled"), + "hook_text": req.script.get("hook_text", ""), + "caption": req.script.get("caption", ""), + "hashtags": req.script.get("hashtags", []), + "full_narration": req.script.get("full_narration", ""), + "actor_description": req.script.get("actor_description", ""), + "style": req.script.get("style", "ugc"), + "language": req.script.get("language", "en"), + "duration": result.get("duration", 0), + "video_mode": req.video_mode, + "product_name": req.script.get("_product_name", ""), + "product_url": req.script.get("_product_url", ""), + "segments": req.script.get("segments", []), + "cost_estimate": result.get("cost_estimate", {}), + } + gallery_result = upload_video_to_gallery( + video_path=result["video_path"], + actor_image_path=result.get("actor_image", ""), + metadata=gallery_meta, + video_id=job_id[:8], + ) + if gallery_result: + saas_jobs[job_id]["result"]["gallery_video_id"] = gallery_result["video_id"] + log_msg("πŸ“€ Uploaded to public gallery.") + except Exception as gallery_err: + log_msg(f"⚠️ Gallery upload skipped: {gallery_err}") + except Exception as e: print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}") if job_id in saas_jobs: diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 1695127..5e58506 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -7,6 +7,7 @@ import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; +import UGCGallery from './components/UGCGallery'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -377,7 +378,7 @@ function App() { className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'dashboard' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`} > - Dashboard + Clip Generator + + + + + + +
+
@@ -383,12 +455,26 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) { type="url" value={url} onChange={(e) => setUrl(e.target.value)} - placeholder="https://your-saas.com" + placeholder="https://your-website.com" className="input-field pl-10" onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()} />
+

If provided, we'll scrape and research your site automatically

+
+ +
+ +