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) <noreply@anthropic.com>
This commit is contained in:
parent
29681bab82
commit
86117d3f3e
10 changed files with 1619 additions and 167 deletions
|
|
@ -3,6 +3,7 @@ AWS_ACCESS_KEY_ID=your_aws_access_key_here
|
||||||
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
|
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
|
||||||
AWS_REGION=eu-west-3
|
AWS_REGION=eu-west-3
|
||||||
AWS_S3_BUCKET=your-bucket-name
|
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 (optional — paste Netscape-format cookies to bypass bot detection)
|
||||||
# YOUTUBE_COOKIES=...
|
# YOUTUBE_COOKIES=...
|
||||||
|
|
|
||||||
249
README.md
249
README.md
|
|
@ -1,143 +1,224 @@
|
||||||
# OpenShorts.app 🚀🎬
|
# OpenShorts.app
|
||||||
|
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://opensource.org/)
|
[](https://opensource.org/)
|
||||||
[](http://makeapullrequest.com)
|
[](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.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
### 📺 Video Tutorial: How it works
|
### Video Tutorial: How it works
|
||||||
[](https://www.youtube.com/watch?v=xlyjD1qCaX0 "Click to watch the video on YouTube")
|
[](https://www.youtube.com/watch?v=xlyjD1qCaX0 "Click to watch the video on YouTube")
|
||||||
|
|
||||||
*Click the image above to watch the full walkthrough.*
|
*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.
|
|
||||||
|
|
||||||
2. **✂️ Smart AI Cropping & Tracking (New V2 Engine):**
|
### 2. AI Shorts (UGC Video Creator)
|
||||||
* **Dual-Mode Strategy**: Automatically detects scene composition to apply the best framing strategy.
|
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.
|
||||||
* **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.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
4. **📲 Direct Social Posting:**
|
- **Two cost modes**: Low Cost (~$0.65/video) and Premium (~$2/video)
|
||||||
* **Upload-Post Integration**: Share your generated clips directly to TikTok, Instagram, and YouTube with a single click.
|
- Works for any business: SaaS, restaurants, e-commerce, coaching, local businesses
|
||||||
* **Profile Selector**: Manage multiple social accounts easily through the dashboard.
|
- 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:**
|
### 3. YouTube Studio
|
||||||
* **ElevenLabs Integration**: Translate your clips to 30+ languages with AI-powered voice dubbing.
|
Complete free AI YouTube toolkit: thumbnails, titles, descriptions, and direct publishing.
|
||||||
* **Voice Cloning**: Preserves the original speaker's voice characteristics in the new language.
|
|
||||||
* **Auto-Subtitles**: Automatically generates subtitles in the dubbed language.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
7. **📺 YouTube Studio (Full Publishing Pipeline):**
|
- AI thumbnail generator with face overlay
|
||||||
* **AI Title Generation**: Upload a video and let Gemini analyze the transcript to suggest viral, SEO-optimized titles with AI-ranked top picks.
|
- 10 viral title suggestions with refinement chat
|
||||||
* **Title Refinement Chat**: Iteratively refine suggested titles via a built-in chat interface — ask for more clickbait, different tone, etc.
|
- Auto-generated descriptions with chapter timestamps
|
||||||
* **AI Thumbnail Generation**: Generate professional thumbnails with optional face overlay, custom background, and extra creative instructions.
|
- One-click publish to YouTube
|
||||||
* **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.
|
### UGC Video Gallery
|
||||||
* **Manual Mode**: Skip video analysis and enter your own title to jump straight to thumbnail generation.
|
All generated videos and avatars are saved to a public gallery with SEO pages for each video.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
- 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**.
|
### Clip Generator
|
||||||
* **Google Gemini API Key** ([Get it for free here](https://aistudio.google.com/app/apikey)).
|
- **Viral Moment Detection**: Google Gemini 3.0 Flash analyzes transcripts and scene boundaries to detect 3-15 high-potential moments
|
||||||
* **Upload-Post API Key** (Optional, for direct social posting. **Free tier available, no credit card required**).
|
- **Smart 9:16 Cropping**: Dual-mode AI reframing — TRACK mode (MediaPipe + YOLOv8 face tracking) and GENERAL mode (blurred background)
|
||||||
* **ElevenLabs API Key** (Optional, for AI voice dubbing. [Get it here](https://elevenlabs.io)).
|
- **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)
|
### AI Shorts Pipeline
|
||||||
To enable direct posting, follow these steps:
|
1. **Analyze**: Scrape website URL + web research, or generate from manual description
|
||||||
1. **Login/Register**: [app.upload-post.com/login](https://app.upload-post.com/login)
|
2. **Script**: AI writes viral scripts (hook - problem - solution - CTA format)
|
||||||
2. **Create Profile**: Go to [Manage Users](https://app.upload-post.com/manage-users) and create a user profile.
|
3. **Actor**: Generate AI actors with Flux 2 Pro or select from shared gallery
|
||||||
3. **Connect Accounts**: In the same section, connect your TikTok, Instagram, or YouTube accounts to that profile.
|
4. **Voice**: ElevenLabs TTS voiceover (English/Spanish, male/female)
|
||||||
4. **Get API Key**: Navigate to [API Keys](https://app.upload-post.com/api-keys) and generate your key.
|
5. **Video**: Talking head generation (Hailuo 2.3 Fast img2video + VEED Lipsync)
|
||||||
5. **Use in OpenShorts**: Paste the API Key and select your Profile in the dashboard.
|
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)
|
### YouTube Studio
|
||||||
To enable automatic backup of your clips to S3:
|
- AI-powered title generation with 10 viral options
|
||||||
1. **Environment Variables**: Set the following in your `.env` file or system environment:
|
- Interactive refinement chat for titles
|
||||||
* `AWS_ACCESS_KEY_ID`: Your AWS access key.
|
- AI thumbnail generation with custom face + background
|
||||||
* `AWS_SECRET_ACCESS_KEY`: Your AWS secret key.
|
- Auto descriptions with chapter timestamps from Whisper transcript
|
||||||
* `AWS_REGION`: (Optional) Defaults to `us-east-1`.
|
- Direct YouTube publishing via Upload-Post
|
||||||
* `AWS_S3_BUCKET`: (Optional) Defaults to `openshorts.app-clips`.
|
|
||||||
2. **Bucket**: Clips are uploaded to the specified bucket automatically after generation.
|
|
||||||
|
|
||||||
|
### 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
|
```bash
|
||||||
git clone https://github.com/your-username/OpenShorts.git
|
git clone https://github.com/your-username/OpenShorts.git
|
||||||
cd OpenShorts
|
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
|
```bash
|
||||||
docker compose up --build
|
docker compose up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Access the Dashboard
|
### 4. Open Dashboard
|
||||||
Open your browser and navigate to:
|
Navigate to **`http://localhost:5175`**
|
||||||
**`http://localhost:5173`**
|
|
||||||
|
|
||||||
1. Enter your **Gemini API Key**.
|
1. Go to **Settings** and enter your API keys (Gemini, fal.ai, ElevenLabs, Upload-Post)
|
||||||
2. (Optional) Enter your **Upload-Post API Key** to enable social sharing.
|
2. **Clip Generator**: Paste a YouTube URL or upload a video to generate viral shorts
|
||||||
3. Paste a **YouTube URL** or **Upload a Video**.
|
3. **AI Shorts**: Describe your product or paste a URL to generate UGC marketing videos
|
||||||
4. Click **"Generate Clips"** and watch the magic happen!
|
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.
|
### Clip Generator
|
||||||
2. **Transcription**: `faster-whisper` converts audio to text in seconds.
|
1. **Ingest** — YouTube download (yt-dlp) or local upload
|
||||||
3. **AI Intelligence**: Gemini reads the transcript and selects periods of high interest.
|
2. **Transcribe** — faster-whisper with word-level timestamps
|
||||||
4. **Extraction**: FFmpeg precisely cuts the selected segments.
|
3. **Detect** — PySceneDetect for scene boundaries
|
||||||
5. **Reframing**: AI-powered visual tracking crops clips to vertical format.
|
4. **Analyze** — Gemini identifies 3-15 viral moments (15-60s each)
|
||||||
6. **Backup**: Automated silent upload of clips and metadata to AWS S3.
|
5. **Extract** — FFmpeg precise clip cutting
|
||||||
7. **Distribution**: One-click posting via Upload-Post API.
|
6. **Reframe** — AI vertical cropping with subject tracking
|
||||||
8. **YouTube Studio**: Full publishing pipeline — AI titles, thumbnails, descriptions with chapters, and direct YouTube upload.
|
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.
|
| Layer | Technology |
|
||||||
* **Concurrency Control**: Configurable job queue (`MAX_CONCURRENT_JOBS`).
|
|-------|-----------|
|
||||||
* **Auto-Cleanup**: Automatic purging of old jobs and temporary files.
|
| Backend | Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx |
|
||||||
* **File Limits**: Built-in protection against oversized uploads.
|
| 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.
|
MIT License. OpenShorts is yours to use, modify, and scale.
|
||||||
|
|
|
||||||
403
app.py
403
app.py
|
|
@ -13,8 +13,9 @@ from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
from pydantic import BaseModel
|
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()
|
load_dotenv()
|
||||||
|
|
||||||
|
|
@ -1441,7 +1442,8 @@ saas_jobs: Dict[str, Dict] = {}
|
||||||
|
|
||||||
|
|
||||||
class SaaSAnalyzeRequest(BaseModel):
|
class SaaSAnalyzeRequest(BaseModel):
|
||||||
url: str
|
url: Optional[str] = None
|
||||||
|
description: Optional[str] = None # Manual product/business description
|
||||||
num_scripts: int = 3
|
num_scripts: int = 3
|
||||||
style: str = "ugc"
|
style: str = "ugc"
|
||||||
language: str = "en"
|
language: str = "en"
|
||||||
|
|
@ -1453,22 +1455,37 @@ async def saasshorts_analyze(
|
||||||
req: SaaSAnalyzeRequest,
|
req: SaaSAnalyzeRequest,
|
||||||
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key"),
|
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")
|
gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY")
|
||||||
if not gemini_key:
|
if not gemini_key:
|
||||||
raise HTTPException(status_code=400, detail="Missing Gemini API 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:
|
try:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
|
|
||||||
def run_analysis():
|
def run_analysis():
|
||||||
# Phase 1a: Scrape the website directly
|
web_research = None
|
||||||
scraped = scrape_website(req.url)
|
|
||||||
# Phase 1b: Research across the web with Google Search grounding
|
if req.url and req.url.strip():
|
||||||
web_research = research_saas_online(req.url, gemini_key)
|
# URL provided: full scrape + research pipeline
|
||||||
# Phase 1c: Combine both sources into deep analysis
|
scraped = scrape_website(req.url)
|
||||||
analysis = analyze_saas(scraped, gemini_key, web_research=web_research)
|
web_research = research_saas_online(req.url, gemini_key)
|
||||||
# Phase 1d: Generate scripts based on analysis
|
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)
|
scripts = generate_scripts(analysis, gemini_key, req.num_scripts, req.style, req.language, req.actor_gender)
|
||||||
return {
|
return {
|
||||||
"analysis": analysis,
|
"analysis": analysis,
|
||||||
|
|
@ -1486,6 +1503,37 @@ async def saasshorts_analyze(
|
||||||
class SaaSActorRequest(BaseModel):
|
class SaaSActorRequest(BaseModel):
|
||||||
actor_description: str
|
actor_description: str
|
||||||
num_options: int = 3
|
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")
|
@app.post("/api/saasshorts/actor-options")
|
||||||
|
|
@ -1504,25 +1552,301 @@ async def saasshorts_actor_options(
|
||||||
os.makedirs(out_dir, exist_ok=True)
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
|
import functools
|
||||||
paths = await loop.run_in_executor(
|
paths = await loop.run_in_executor(
|
||||||
None,
|
None,
|
||||||
generate_actor_images,
|
functools.partial(
|
||||||
req.actor_description, fal_key, out_dir, "actor", req.num_options,
|
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}
|
return {"images": urls}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(status_code=500, detail=str(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 = '<span style="background:#22c55e;color:#000;padding:2px 8px;border-radius:9999px;font-size:10px;font-weight:700">LOW COST</span>' if mode == "lowcost" else '<span style="background:#8b5cf6;color:#fff;padding:2px 8px;border-radius:9999px;font-size:10px;font-weight:700">PREMIUM</span>'
|
||||||
|
|
||||||
|
cards_html += f'''
|
||||||
|
<a href="/video/{video_id}" style="text-decoration:none;color:inherit">
|
||||||
|
<div style="background:#18181b;border-radius:16px;overflow:hidden;border:1px solid #27272a;transition:transform 0.2s" onmouseover="this.style.transform='scale(1.02)'" onmouseout="this.style.transform='scale(1)'">
|
||||||
|
<div style="position:relative;aspect-ratio:9/16;background:#000">
|
||||||
|
<video src="{video_url}" poster="{actor_url}" muted playsinline preload="metadata"
|
||||||
|
onmouseenter="this.play()" onmouseleave="this.pause();this.currentTime=0"
|
||||||
|
style="width:100%;height:100%;object-fit:cover"></video>
|
||||||
|
<div style="position:absolute;top:8px;right:8px">{mode_badge}</div>
|
||||||
|
</div>
|
||||||
|
<div style="padding:12px">
|
||||||
|
<h2 style="font-size:14px;font-weight:600;margin:0 0 4px 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">{title}</h2>
|
||||||
|
<p style="font-size:11px;color:#71717a;margin:0">{duration:.0f}s · {product}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</a>'''
|
||||||
|
|
||||||
|
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'''<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>AI UGC Video Gallery | OpenShorts</title>
|
||||||
|
<meta name="description" content="Browse {len(videos)} AI-generated UGC marketing videos. Create viral TikTok and Instagram Reels for your SaaS product.">
|
||||||
|
<meta name="robots" content="index, follow">
|
||||||
|
<meta property="og:title" content="AI UGC Video Gallery | OpenShorts">
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:description" content="Browse AI-generated UGC marketing videos for SaaS products.">
|
||||||
|
<script type="application/ld+json">{ld_json}</script>
|
||||||
|
<style>
|
||||||
|
*{{margin:0;padding:0;box-sizing:border-box}}
|
||||||
|
body{{background:#0a0a0c;color:#e4e4e7;font-family:-apple-system,BlinkMacSystemFont,sans-serif}}
|
||||||
|
.grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:20px;padding:20px;max-width:1400px;margin:0 auto}}
|
||||||
|
nav{{padding:20px 40px;border-bottom:1px solid #27272a;display:flex;align-items:center;justify-content:space-between}}
|
||||||
|
h1{{font-size:28px;font-weight:700;padding:40px 20px 0;text-align:center}}
|
||||||
|
.subtitle{{text-align:center;color:#71717a;font-size:14px;padding:8px 20px 20px}}
|
||||||
|
.cta{{display:inline-block;background:#8b5cf6;color:#fff;padding:10px 24px;border-radius:12px;text-decoration:none;font-weight:600;font-size:14px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav><strong style="font-size:18px">OpenShorts</strong><a href="/" class="cta">Create Your Video</a></nav>
|
||||||
|
<h1>AI-Generated UGC Videos</h1>
|
||||||
|
<p class="subtitle">{len(videos)} videos generated · Low Cost & Premium modes</p>
|
||||||
|
<div class="grid">{cards_html}</div>
|
||||||
|
<div style="text-align:center;padding:40px"><a href="/" class="cta">Create Your Own UGC Video</a></div>
|
||||||
|
</body></html>'''
|
||||||
|
|
||||||
|
|
||||||
|
@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'''<!DOCTYPE html>
|
||||||
|
<html lang="{language}">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>{title} - AI UGC Video | OpenShorts</title>
|
||||||
|
<meta name="description" content="{caption} {hashtags}">
|
||||||
|
<meta property="og:type" content="video.other">
|
||||||
|
<meta property="og:title" content="{title}">
|
||||||
|
<meta property="og:description" content="{caption}">
|
||||||
|
<meta property="og:video" content="{video_url}">
|
||||||
|
<meta property="og:video:type" content="video/mp4">
|
||||||
|
<meta property="og:video:width" content="1080">
|
||||||
|
<meta property="og:video:height" content="1920">
|
||||||
|
<meta property="og:image" content="{actor_url}">
|
||||||
|
<meta name="twitter:card" content="player">
|
||||||
|
<meta name="twitter:title" content="{title}">
|
||||||
|
<meta name="twitter:image" content="{actor_url}">
|
||||||
|
<script type="application/ld+json">{ld_json}</script>
|
||||||
|
<style>
|
||||||
|
*{{margin:0;padding:0;box-sizing:border-box}}
|
||||||
|
body{{background:#0a0a0c;color:#e4e4e7;font-family:-apple-system,BlinkMacSystemFont,sans-serif}}
|
||||||
|
nav{{padding:20px 40px;border-bottom:1px solid #27272a;display:flex;align-items:center;gap:16px}}
|
||||||
|
nav a{{color:#a1a1aa;text-decoration:none;font-size:14px}}
|
||||||
|
.container{{max-width:1000px;margin:0 auto;padding:40px 20px;display:grid;grid-template-columns:1fr 1fr;gap:40px}}
|
||||||
|
@media(max-width:768px){{.container{{grid-template-columns:1fr}}}}
|
||||||
|
video{{width:100%;border-radius:16px;background:#000}}
|
||||||
|
h1{{font-size:22px;font-weight:700;margin-bottom:8px}}
|
||||||
|
.meta{{color:#71717a;font-size:13px;margin-bottom:20px}}
|
||||||
|
.section{{margin-bottom:20px}}
|
||||||
|
.section h2{{font-size:13px;color:#71717a;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px}}
|
||||||
|
.section p{{font-size:14px;line-height:1.6}}
|
||||||
|
.badge{{display:inline-block;padding:3px 10px;border-radius:9999px;font-size:11px;font-weight:700}}
|
||||||
|
.cta{{display:inline-block;background:#8b5cf6;color:#fff;padding:10px 24px;border-radius:12px;text-decoration:none;font-weight:600;font-size:14px;margin-top:20px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav><strong>OpenShorts</strong><a href="/gallery">Gallery</a><span style="color:#3f3f46">›</span><span style="color:#e4e4e7;font-size:14px">{title}</span></nav>
|
||||||
|
<div class="container">
|
||||||
|
<div><video src="{video_url}" poster="{actor_url}" controls autoplay playsinline style="aspect-ratio:9/16;object-fit:cover"></video></div>
|
||||||
|
<div>
|
||||||
|
<h1>{title}</h1>
|
||||||
|
<p class="meta">{duration:.0f}s · {mode_label} · ${cost:.2f} · {product}</p>
|
||||||
|
<div class="section"><h2>Caption</h2><p>{caption}</p><p style="color:#8b5cf6;margin-top:4px">{hashtags}</p></div>
|
||||||
|
<div class="section"><h2>Script</h2><p>{narration}</p></div>
|
||||||
|
<div class="section"><h2>Actor</h2><p>{actor_desc}</p></div>
|
||||||
|
{f'<div class="section"><h2>Product</h2><p><a href="{product_url}" style="color:#8b5cf6" target="_blank">{product}</a></p></div>' if product_url else ''}
|
||||||
|
<a href="/gallery">← Back to Gallery</a>
|
||||||
|
<br><a href="/" class="cta">Create Your Own</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body></html>'''
|
||||||
|
|
||||||
|
|
||||||
|
@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):
|
class SaaSGenerateRequest(BaseModel):
|
||||||
script: dict
|
script: dict
|
||||||
voice_id: Optional[str] = None
|
voice_id: Optional[str] = None
|
||||||
actor_description: Optional[str] = None
|
actor_description: Optional[str] = None
|
||||||
selected_actor_url: Optional[str] = None # Pre-selected actor image URL
|
selected_actor_url: Optional[str] = None # Pre-selected actor image URL
|
||||||
retry_job_id: Optional[str] = None
|
retry_job_id: Optional[str] = None
|
||||||
|
video_mode: str = "lowcost" # "lowcost" or "premium"
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/saasshorts/generate")
|
@app.post("/api/saasshorts/generate")
|
||||||
|
|
@ -1575,12 +1899,26 @@ async def saasshorts_generate(
|
||||||
"output_dir": job_output_dir,
|
"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
|
selected_actor_path = None
|
||||||
if req.selected_actor_url:
|
if req.selected_actor_url:
|
||||||
src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", ""))
|
if req.selected_actor_url.startswith("http"):
|
||||||
if os.path.exists(src):
|
# Download from S3 public URL to job output dir
|
||||||
selected_actor_path = src
|
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 = {
|
config = {
|
||||||
"fal_key": fal_key,
|
"fal_key": fal_key,
|
||||||
|
|
@ -1588,6 +1926,7 @@ async def saasshorts_generate(
|
||||||
"voice_id": req.voice_id or "21m00Tcm4TlvDq8ikWAM",
|
"voice_id": req.voice_id or "21m00Tcm4TlvDq8ikWAM",
|
||||||
"actor_description": req.actor_description,
|
"actor_description": req.actor_description,
|
||||||
"selected_actor_path": selected_actor_path,
|
"selected_actor_path": selected_actor_path,
|
||||||
|
"video_mode": req.video_mode,
|
||||||
}
|
}
|
||||||
|
|
||||||
async def run_generation():
|
async def run_generation():
|
||||||
|
|
@ -1617,6 +1956,36 @@ async def saasshorts_generate(
|
||||||
}
|
}
|
||||||
saas_jobs[job_id]["logs"].append("Video generation completed!")
|
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:
|
except Exception as e:
|
||||||
print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}")
|
print(f"[SaaSShorts] ❌ Job {job_id} failed: {e}")
|
||||||
if job_id in saas_jobs:
|
if job_id in saas_jobs:
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import ProcessingAnimation from './components/ProcessingAnimation';
|
||||||
// import Gallery from './components/Gallery';
|
// import Gallery from './components/Gallery';
|
||||||
import ThumbnailStudio from './components/ThumbnailStudio';
|
import ThumbnailStudio from './components/ThumbnailStudio';
|
||||||
import SaaShortsTab from './components/SaaShortsTab';
|
import SaaShortsTab from './components/SaaShortsTab';
|
||||||
|
import UGCGallery from './components/UGCGallery';
|
||||||
import { getApiUrl } from './config';
|
import { getApiUrl } from './config';
|
||||||
|
|
||||||
// Enhanced "Encryption" using XOR + Base64 with a Salt
|
// 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'}`}
|
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'}`}
|
||||||
>
|
>
|
||||||
<LayoutDashboard size={20} />
|
<LayoutDashboard size={20} />
|
||||||
<span className="font-medium hidden lg:block">Dashboard</span>
|
<span className="font-medium hidden lg:block">Clip Generator</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -385,7 +386,15 @@ function App() {
|
||||||
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'saasshorts' ? 'bg-violet-500/10 text-violet-400' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
|
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'saasshorts' ? 'bg-violet-500/10 text-violet-400' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
|
||||||
>
|
>
|
||||||
<Sparkles size={20} />
|
<Sparkles size={20} />
|
||||||
<span className="font-medium hidden lg:block">SaaS Shorts</span>
|
<span className="font-medium hidden lg:block">AI Shorts</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('ugc-gallery')}
|
||||||
|
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'ugc-gallery' ? 'bg-violet-500/10 text-violet-400' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
|
||||||
|
>
|
||||||
|
<LayoutGrid size={20} />
|
||||||
|
<span className="font-medium hidden lg:block">UGC Gallery</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|
@ -615,12 +624,12 @@ function App() {
|
||||||
|
|
||||||
<div className="glass-panel p-6 mt-8">
|
<div className="glass-panel p-6 mt-8">
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
<h2 className="text-lg font-semibold">SaaS Shorts (AI Actors)</h2>
|
<h2 className="text-lg font-semibold">AI Shorts (UGC Videos)</h2>
|
||||||
<span className="text-[10px] bg-violet-500/10 border border-violet-500/20 px-2 py-0.5 rounded text-violet-400 uppercase tracking-wider">New</span>
|
<span className="text-[10px] bg-violet-500/10 border border-violet-500/20 px-2 py-0.5 rounded text-violet-400 uppercase tracking-wider">New</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-zinc-500 mb-6 leading-relaxed">
|
<p className="text-xs text-zinc-500 mb-6 leading-relaxed">
|
||||||
Generate UGC-style videos with AI actors for your SaaS using <strong>fal.ai</strong> (Flux image generation + Kling lip-sync).
|
Generate UGC-style videos with AI actors for any product or business using <strong>fal.ai</strong>.
|
||||||
Requires a fal.ai API key. ElevenLabs key (above) is also needed for voiceover.
|
Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys.
|
||||||
</p>
|
</p>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<label className="block text-sm text-zinc-400">fal.ai API Key</label>
|
<label className="block text-sm text-zinc-400">fal.ai API Key</label>
|
||||||
|
|
@ -668,7 +677,12 @@ function App() {
|
||||||
|
|
||||||
{/* View: SaaS Shorts */}
|
{/* View: SaaS Shorts */}
|
||||||
{activeTab === 'saasshorts' && (
|
{activeTab === 'saasshorts' && (
|
||||||
<SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} />
|
<SaaShortsTab geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} falKey={falKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* View: UGC Gallery */}
|
||||||
|
{activeTab === 'ugc-gallery' && (
|
||||||
|
<UGCGallery />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* View: Thumbnails */}
|
{/* View: Thumbnails */}
|
||||||
|
|
|
||||||
|
|
@ -108,6 +108,16 @@ export default function Landing({ onLaunchApp }) {
|
||||||
icon: Globe,
|
icon: Globe,
|
||||||
title: "Direct Social Publishing",
|
title: "Direct Social Publishing",
|
||||||
description: "Post directly to TikTok, Instagram Reels, and YouTube Shorts from the dashboard. Async uploads with progress tracking and S3 cloud backup."
|
description: "Post directly to TikTok, Instagram Reels, and YouTube Shorts from the dashboard. Async uploads with progress tracking and S3 cloud backup."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: Sparkles,
|
||||||
|
title: "AI UGC Video Generator",
|
||||||
|
description: "Generate marketing videos with AI actors for any product or business. Paste a URL or describe your product — AI writes the script, generates a realistic avatar with lip-sync, adds b-roll, subtitles, and hook overlays. From $0.65/video."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: FileVideo,
|
||||||
|
title: "AI Actors & Lip-Sync",
|
||||||
|
description: "Choose from a gallery of AI-generated actors or upload your own photo. The pipeline generates a talking head video with natural movement and lip-synced voiceover in English or Spanish. Two modes: Low Cost ($0.65) and Premium ($2.00)."
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
@ -159,6 +169,18 @@ export default function Landing({ onLaunchApp }) {
|
||||||
{
|
{
|
||||||
question: "Is there a free open source clip generator?",
|
question: "Is there a free open source clip generator?",
|
||||||
answer: "Yes — OpenShorts is a 100% free, open source clip generator. Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), OpenShorts lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
|
answer: "Yes — OpenShorts is a 100% free, open source clip generator. Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), OpenShorts lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "What is the AI UGC Video Generator?",
|
||||||
|
answer: "OpenShorts includes an AI UGC (User Generated Content) video creator that generates marketing videos with AI actors for any product or business. You describe your product or paste a website URL — the AI writes a viral script, generates a realistic AI actor with lip-synced voiceover, adds b-roll visuals, TikTok-style subtitles, and hook text overlays. The result is a ready-to-post vertical video for TikTok, Instagram Reels, or YouTube Shorts. Two cost modes: Low Cost (~$0.65/video using Hailuo + VEED Lipsync) and Premium (~$2/video using Kling Avatar v2)."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "How much does it cost to generate an AI UGC video?",
|
||||||
|
answer: "OpenShorts itself is free, but the AI Shorts feature uses external APIs (fal.ai for video generation, ElevenLabs for voiceover) that charge per use. Low Cost mode costs approximately $0.65 per video (Flux image $0.05 + ElevenLabs voice $0.10 + Hailuo img2video $0.19 + VEED Lipsync $0.20 + b-roll $0.10). Premium mode costs approximately $2.00 per video using Kling Avatar v2 for higher quality. Both modes are significantly cheaper than hiring UGC creators ($50-500 per video) or using platforms like HeyGen ($24-180/month)."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question: "Can I use the AI UGC Video Generator for any type of business?",
|
||||||
|
answer: "Yes. The AI Shorts generator works for any product, service, or business — not just SaaS. You can use it for restaurants, e-commerce stores, coaching services, local businesses, personal brands, apps, and more. Just describe your business in the text field (e.g. 'Artisan pizza restaurant in Madrid, wood-fired oven, home delivery') or paste your website URL, and the AI generates viral marketing scripts tailored to your business."
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
@ -205,17 +227,17 @@ export default function Landing({ onLaunchApp }) {
|
||||||
<div className="max-w-5xl mx-auto text-center">
|
<div className="max-w-5xl mx-auto text-center">
|
||||||
<div className="inline-flex items-center gap-2 bg-primary/10 border border-primary/20 rounded-full px-4 py-1.5 text-sm text-primary mb-8">
|
<div className="inline-flex items-center gap-2 bg-primary/10 border border-primary/20 rounded-full px-4 py-1.5 text-sm text-primary mb-8">
|
||||||
<Sparkles size={14} />
|
<Sparkles size={14} />
|
||||||
<span>Free & Open Source AI Clip Generator</span>
|
<span>Free & Open Source AI Clip Generator + UGC Video Creator</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h1 className="text-4xl md:text-6xl lg:text-7xl font-bold leading-tight mb-6 tracking-tight">
|
<h1 className="text-4xl md:text-6xl lg:text-7xl font-bold leading-tight mb-6 tracking-tight">
|
||||||
Free Open Source
|
Free Open Source
|
||||||
<span className="bg-gradient-to-r from-primary via-purple-400 to-pink-500 bg-clip-text text-transparent"> Clip Generator </span>
|
<span className="bg-gradient-to-r from-primary via-purple-400 to-pink-500 bg-clip-text text-transparent"> Clip Generator </span>
|
||||||
for Viral Shorts
|
& AI UGC Video Creator
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<p className="hero-description text-lg md:text-xl text-zinc-400 max-w-3xl mx-auto mb-10 leading-relaxed">
|
<p className="hero-description text-lg md:text-xl text-zinc-400 max-w-3xl mx-auto mb-10 leading-relaxed">
|
||||||
OpenShorts is a free open source clip generator powered by Google Gemini 3.0 Flash AI. According to HubSpot's 2025 report, short-form video delivers the highest ROI of any content format. OpenShorts automates the entire pipeline: viral moment detection, smart 9:16 face-tracking crop, auto subtitles, AI dubbing in 30+ languages, and a free AI YouTube Studio for thumbnails, titles, and descriptions. Self-hosted with Docker, no watermarks, no limits.
|
Three tools in one. <strong className="text-white">Clip Generator:</strong> turn long YouTube videos into viral shorts with AI moment detection, smart 9:16 crop, and auto subtitles. <strong className="text-white">AI Shorts:</strong> generate UGC marketing videos with AI actors and lip-sync for any business. <strong className="text-white">YouTube Studio:</strong> free AI thumbnail generator, 10 viral title suggestions with refinement chat, and auto descriptions with chapters. Self-hosted, open source, no limits.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-12">
|
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-12">
|
||||||
|
|
@ -266,12 +288,12 @@ export default function Landing({ onLaunchApp }) {
|
||||||
<div className="text-sm text-zinc-400 mt-1">Free & Open Source</div>
|
<div className="text-sm text-zinc-400 mt-1">Free & Open Source</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-3xl font-bold text-white">30+</div>
|
<div className="text-3xl font-bold text-white">3</div>
|
||||||
<div className="text-sm text-zinc-400 mt-1">Dubbing Languages</div>
|
<div className="text-sm text-zinc-400 mt-1">Tools in One</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-3xl font-bold text-white">9:16</div>
|
<div className="text-3xl font-bold text-white">30+</div>
|
||||||
<div className="text-sm text-zinc-400 mt-1">Vertical Format</div>
|
<div className="text-sm text-zinc-400 mt-1">Dubbing Languages</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-3xl font-bold text-white">$0</div>
|
<div className="text-3xl font-bold text-white">$0</div>
|
||||||
|
|
@ -280,12 +302,57 @@ export default function Landing({ onLaunchApp }) {
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
{/* 3 Tools in 1 Section */}
|
||||||
|
<section className="py-20 px-6">
|
||||||
|
<div className="max-w-6xl mx-auto">
|
||||||
|
<div className="text-center mb-14">
|
||||||
|
<h2 className="text-3xl md:text-4xl font-bold mb-4">3 Free Tools in 1 Platform</h2>
|
||||||
|
<p className="text-zinc-400 max-w-2xl mx-auto">Everything you need to create, optimize, and publish short-form video content — all free and open source.</p>
|
||||||
|
</div>
|
||||||
|
<div className="grid md:grid-cols-3 gap-6">
|
||||||
|
<div className="bg-surface/50 border border-primary/20 rounded-2xl p-8 relative overflow-hidden">
|
||||||
|
<div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2" />
|
||||||
|
<Scissors size={28} className="text-primary mb-4" />
|
||||||
|
<h3 className="text-xl font-bold text-white mb-2">Clip Generator</h3>
|
||||||
|
<p className="text-zinc-400 text-sm leading-relaxed mb-4">Turn long YouTube videos or local uploads into viral-ready 9:16 shorts. AI detects the best moments, crops to vertical with face tracking, and adds subtitles automatically.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['AI viral moment detection', 'Smart face-tracking crop', 'Auto subtitles + hook overlays', 'AI dubbing in 30+ languages'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-zinc-400"><Check size={12} className="text-green-400 shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="bg-surface/50 border border-violet-500/20 rounded-2xl p-8 relative overflow-hidden">
|
||||||
|
<div className="absolute top-0 right-0 w-32 h-32 bg-violet-500/5 rounded-full -translate-y-1/2 translate-x-1/2" />
|
||||||
|
<Sparkles size={28} className="text-violet-400 mb-4" />
|
||||||
|
<h3 className="text-xl font-bold text-white mb-2">AI Shorts</h3>
|
||||||
|
<p className="text-zinc-400 text-sm leading-relaxed mb-4">Generate UGC marketing videos with AI actors for any product or business. No camera, no studio. Just describe your product and get a viral-ready video.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['AI actor generation + lip-sync', 'Script writing from URL or description', 'B-roll + TikTok-style subtitles', 'From $0.65 per video'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-zinc-400"><Check size={12} className="text-green-400 shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="bg-surface/50 border border-pink-500/20 rounded-2xl p-8 relative overflow-hidden">
|
||||||
|
<div className="absolute top-0 right-0 w-32 h-32 bg-pink-500/5 rounded-full -translate-y-1/2 translate-x-1/2" />
|
||||||
|
<Monitor size={28} className="text-pink-400 mb-4" />
|
||||||
|
<h3 className="text-xl font-bold text-white mb-2">YouTube Studio</h3>
|
||||||
|
<p className="text-zinc-400 text-sm leading-relaxed mb-4">Complete free AI YouTube toolkit. Generate thumbnails with your face, get 10 viral title suggestions with refinement chat, and auto-generate descriptions with timestamps.</p>
|
||||||
|
<ul className="space-y-1.5">
|
||||||
|
{['AI thumbnail generator (with face upload)', '10 viral title suggestions + chat', 'Auto descriptions with chapters', 'Direct publish to YouTube'].map((f, i) => (
|
||||||
|
<li key={i} className="flex items-center gap-2 text-xs text-zinc-400"><Check size={12} className="text-green-400 shrink-0" />{f}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
{/* Features Section */}
|
{/* Features Section */}
|
||||||
<section id="features" className="py-20 px-6">
|
<section id="features" className="py-20 px-6">
|
||||||
<div className="max-w-6xl mx-auto">
|
<div className="max-w-6xl mx-auto">
|
||||||
<div className="text-center mb-14">
|
<div className="text-center mb-14">
|
||||||
<h2 className="text-3xl md:text-4xl font-bold mb-4">Free AI Clip Generator with YouTube Studio Built In</h2>
|
<h2 className="text-3xl md:text-4xl font-bold mb-4">Free AI Clip Generator + UGC Video Creator</h2>
|
||||||
<p className="text-zinc-400 max-w-2xl mx-auto">A complete open source clip generator with a full AI-powered pipeline — from viral moment detection to a free YouTube thumbnail generator, AI titles, descriptions, and one-click publishing. No manual editing required.</p>
|
<p className="text-zinc-400 max-w-2xl mx-auto">Three tools in one: clip long videos into viral shorts, generate UGC marketing videos with AI actors, and a complete YouTube Studio for thumbnails, titles, and descriptions.</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
|
||||||
{features.map((feature, i) => (
|
{features.map((feature, i) => (
|
||||||
|
|
@ -331,6 +398,26 @@ export default function Landing({ onLaunchApp }) {
|
||||||
<p className="text-zinc-400 text-sm leading-relaxed">Enables direct publishing to YouTube, TikTok, and Instagram Reels from the dashboard. Post your clips and thumbnails without leaving OpenShorts.</p>
|
<p className="text-zinc-400 text-sm leading-relaxed">Enables direct publishing to YouTube, TikTok, and Instagram Reels from the dashboard. Post your clips and thumbnails without leaving OpenShorts.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="grid md:grid-cols-2 gap-5 mt-5">
|
||||||
|
<div className="bg-surface/50 border border-white/10 rounded-2xl p-6 relative">
|
||||||
|
<div className="absolute top-4 right-4 bg-violet-700/50 text-violet-300 text-[10px] font-bold px-2 py-0.5 rounded-full border border-violet-500/30">AI SHORTS</div>
|
||||||
|
<div className="w-12 h-12 rounded-xl bg-violet-500/10 flex items-center justify-center mb-4">
|
||||||
|
<Zap size={24} className="text-violet-400" />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-lg font-semibold text-white mb-1">fal.ai API</h3>
|
||||||
|
<span className="inline-block text-xs text-green-400 bg-green-500/10 border border-green-500/20 px-2 py-0.5 rounded-full mb-3">Pay-per-use from $0.04</span>
|
||||||
|
<p className="text-zinc-400 text-sm leading-relaxed">Powers AI Shorts: generates AI actor images (Flux), talking head videos (Hailuo/Kling), and lip-sync (VEED). Required only for the AI UGC video generator.</p>
|
||||||
|
</div>
|
||||||
|
<div className="bg-surface/50 border border-white/10 rounded-2xl p-6 relative">
|
||||||
|
<div className="absolute top-4 right-4 bg-violet-700/50 text-violet-300 text-[10px] font-bold px-2 py-0.5 rounded-full border border-violet-500/30">AI SHORTS</div>
|
||||||
|
<div className="w-12 h-12 rounded-xl bg-violet-500/10 flex items-center justify-center mb-4">
|
||||||
|
<Languages size={24} className="text-violet-400" />
|
||||||
|
</div>
|
||||||
|
<h3 className="text-lg font-semibold text-white mb-1">ElevenLabs TTS</h3>
|
||||||
|
<span className="inline-block text-xs text-green-400 bg-green-500/10 border border-green-500/20 px-2 py-0.5 rounded-full mb-3">Free tier included</span>
|
||||||
|
<p className="text-zinc-400 text-sm leading-relaxed">Generates natural voiceovers for AI Shorts from the script. Multiple voice options for male and female actors in English and Spanish.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
@ -363,7 +450,8 @@ export default function Landing({ onLaunchApp }) {
|
||||||
{ name: "YOLOv8", desc: "Object Detection" },
|
{ name: "YOLOv8", desc: "Object Detection" },
|
||||||
{ name: "MediaPipe", desc: "Face Tracking" },
|
{ name: "MediaPipe", desc: "Face Tracking" },
|
||||||
{ name: "FFmpeg", desc: "Video Processing" },
|
{ name: "FFmpeg", desc: "Video Processing" },
|
||||||
{ name: "ElevenLabs", desc: "Voice Dubbing" },
|
{ name: "ElevenLabs", desc: "Voice & TTS" },
|
||||||
|
{ name: "fal.ai", desc: "AI Video Gen" },
|
||||||
{ name: "React + Vite", desc: "Dashboard" },
|
{ name: "React + Vite", desc: "Dashboard" },
|
||||||
{ name: "Docker", desc: "Deployment" }
|
{ name: "Docker", desc: "Deployment" }
|
||||||
].map((tech, i) => (
|
].map((tech, i) => (
|
||||||
|
|
@ -406,6 +494,10 @@ export default function Landing({ onLaunchApp }) {
|
||||||
<ComparisonRow feature="Self-Hosted / Privacy" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">Cloud only</span>} kapwing={<span className="text-zinc-500 text-sm">Cloud only</span>} />
|
<ComparisonRow feature="Self-Hosted / Privacy" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">Cloud only</span>} kapwing={<span className="text-zinc-500 text-sm">Cloud only</span>} />
|
||||||
<ComparisonRow feature="No Watermark" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">Free tier only</span>} kapwing={<span className="text-zinc-500 text-sm">Paid</span>} />
|
<ComparisonRow feature="No Watermark" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">Free tier only</span>} kapwing={<span className="text-zinc-500 text-sm">Paid</span>} />
|
||||||
<ComparisonRow feature="Open Source" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">No</span>} kapwing={<span className="text-zinc-500 text-sm">No</span>} />
|
<ComparisonRow feature="Open Source" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">No</span>} kapwing={<span className="text-zinc-500 text-sm">No</span>} />
|
||||||
|
<ComparisonRow feature="AI YouTube Thumbnail Generator" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">No</span>} kapwing={<span className="text-zinc-500 text-sm">Paid</span>} />
|
||||||
|
<ComparisonRow feature="AI Title & Description Generator" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">Limited</span>} kapwing={<span className="text-zinc-500 text-sm">Paid</span>} />
|
||||||
|
<ComparisonRow feature="AI UGC Video Generator" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">No</span>} kapwing={<span className="text-zinc-500 text-sm">No</span>} />
|
||||||
|
<ComparisonRow feature="AI Actors with Lip-Sync" openshorts={checkIcon} opusclip={<span className="text-zinc-500 text-sm">No</span>} kapwing={<span className="text-zinc-500 text-sm">No</span>} />
|
||||||
<ComparisonRow feature="Usage Limits" openshorts={<span className="text-green-400 text-sm">Unlimited</span>} opusclip={<span className="text-zinc-500 text-sm">Per plan</span>} kapwing={<span className="text-zinc-500 text-sm">Per plan</span>} />
|
<ComparisonRow feature="Usage Limits" openshorts={<span className="text-green-400 text-sm">Unlimited</span>} opusclip={<span className="text-zinc-500 text-sm">Per plan</span>} kapwing={<span className="text-zinc-500 text-sm">Per plan</span>} />
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
@ -436,6 +528,11 @@ export default function Landing({ onLaunchApp }) {
|
||||||
title: "Podcasters & Educators",
|
title: "Podcasters & Educators",
|
||||||
description: "Extract the most engaging moments from podcast episodes and educational content. Research by Headliner shows that podcast clips on social media increase episode downloads by 72% on average.",
|
description: "Extract the most engaging moments from podcast episodes and educational content. Research by Headliner shows that podcast clips on social media increase episode downloads by 72% on average.",
|
||||||
icon: FileVideo
|
icon: FileVideo
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Businesses & Brands",
|
||||||
|
description: "Generate UGC-style marketing videos for any product or business with AI actors. No camera, no studio, no influencer budget. Just describe your product and get a viral-ready video with lip-synced AI avatar, voiceover, b-roll, and subtitles — from $0.65 per video.",
|
||||||
|
icon: Sparkles
|
||||||
}
|
}
|
||||||
].map((useCase, i) => (
|
].map((useCase, i) => (
|
||||||
<div key={i} className="bg-surface/50 border border-white/10 rounded-2xl p-6">
|
<div key={i} className="bg-surface/50 border border-white/10 rounded-2xl p-6">
|
||||||
|
|
@ -472,8 +569,8 @@ export default function Landing({ onLaunchApp }) {
|
||||||
{/* CTA Section */}
|
{/* CTA Section */}
|
||||||
<section className="py-20 px-6">
|
<section className="py-20 px-6">
|
||||||
<div className="max-w-3xl mx-auto text-center">
|
<div className="max-w-3xl mx-auto text-center">
|
||||||
<h2 className="text-3xl md:text-4xl font-bold mb-4">Start Using the Free Open Source Clip Generator</h2>
|
<h2 className="text-3xl md:text-4xl font-bold mb-4">Start Creating Viral Videos for Free</h2>
|
||||||
<p className="text-zinc-400 mb-8 max-w-xl mx-auto">No sign-up, no credit card, no watermarks. Self-host OpenShorts with Docker and start generating viral clips, AI YouTube thumbnails, titles, and descriptions — all for free.</p>
|
<p className="text-zinc-400 mb-8 max-w-xl mx-auto">No sign-up, no credit card, no watermarks. Generate viral clips from long videos or create AI UGC marketing videos with AI actors for any business. Self-host with Docker.</p>
|
||||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-4">
|
<div className="flex flex-col sm:flex-row items-center justify-center gap-4">
|
||||||
<button
|
<button
|
||||||
onClick={onLaunchApp}
|
onClick={onLaunchApp}
|
||||||
|
|
@ -500,7 +597,7 @@ export default function Landing({ onLaunchApp }) {
|
||||||
<div className="max-w-5xl mx-auto flex flex-col md:flex-row items-center justify-between gap-4">
|
<div className="max-w-5xl mx-auto flex flex-col md:flex-row items-center justify-between gap-4">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<img src="/logo-openshorts.png" alt="OpenShorts" className="w-6 h-6" />
|
<img src="/logo-openshorts.png" alt="OpenShorts" className="w-6 h-6" />
|
||||||
<span className="text-sm text-zinc-400">OpenShorts — Free Open Source Clip Generator with AI YouTube Studio</span>
|
<span className="text-sm text-zinc-400">OpenShorts — Free Open Source Clip Generator & AI UGC Video Creator</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-6 text-sm text-zinc-500">
|
<div className="flex items-center gap-6 text-sm text-zinc-500">
|
||||||
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors">GitHub</a>
|
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors">GitHub</a>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye } from 'lucide-react';
|
import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye, Share2, Calendar, Upload } from 'lucide-react';
|
||||||
import { getApiUrl } from '../config';
|
import { getApiUrl } from '../config';
|
||||||
|
|
||||||
const STYLE_OPTIONS = [
|
const STYLE_OPTIONS = [
|
||||||
|
|
@ -34,7 +34,7 @@ function saveCache(url, analysis, webResearch, scripts) {
|
||||||
} catch { /* localStorage full */ }
|
} catch { /* localStorage full */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId }) {
|
||||||
// Wizard state
|
// Wizard state
|
||||||
const [step, setStep] = useState(() => {
|
const [step, setStep] = useState(() => {
|
||||||
const cache = loadCache();
|
const cache = loadCache();
|
||||||
|
|
@ -43,6 +43,8 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
|
|
||||||
// Step 0: URL input
|
// Step 0: URL input
|
||||||
const [url, setUrl] = useState(() => loadCache()?.url || '');
|
const [url, setUrl] = useState(() => loadCache()?.url || '');
|
||||||
|
const [videoMode, setVideoMode] = useState('lowcost'); // "lowcost" or "premium"
|
||||||
|
const [description, setDescription] = useState('');
|
||||||
const [style, setStyle] = useState('ugc');
|
const [style, setStyle] = useState('ugc');
|
||||||
const [language, setLanguage] = useState('en');
|
const [language, setLanguage] = useState('en');
|
||||||
const [actorGender, setActorGender] = useState('female');
|
const [actorGender, setActorGender] = useState('female');
|
||||||
|
|
@ -65,6 +67,11 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
const [actorOptions, setActorOptions] = useState([]);
|
const [actorOptions, setActorOptions] = useState([]);
|
||||||
const [selectedActor, setSelectedActor] = useState(null);
|
const [selectedActor, setSelectedActor] = useState(null);
|
||||||
const [generatingActors, setGeneratingActors] = useState(false);
|
const [generatingActors, setGeneratingActors] = useState(false);
|
||||||
|
const [actorGallery, setActorGallery] = useState([]);
|
||||||
|
const [loadingGallery, setLoadingGallery] = useState(false);
|
||||||
|
const [uploadedActorPreview, setUploadedActorPreview] = useState(null); // {localPreview, serverUrl}
|
||||||
|
const [productPhoto, setProductPhoto] = useState(null); // {preview, serverUrl}
|
||||||
|
const [productDescription, setProductDescription] = useState('');
|
||||||
|
|
||||||
// Step 3: Generate
|
// Step 3: Generate
|
||||||
const [generating, setGenerating] = useState(false);
|
const [generating, setGenerating] = useState(false);
|
||||||
|
|
@ -73,6 +80,13 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
const [genStatus, setGenStatus] = useState('idle');
|
const [genStatus, setGenStatus] = useState('idle');
|
||||||
const [genResult, setGenResult] = useState(null);
|
const [genResult, setGenResult] = useState(null);
|
||||||
|
|
||||||
|
// Publish
|
||||||
|
const [publishing, setPublishing] = useState(false);
|
||||||
|
const [publishResult, setPublishResult] = useState(null);
|
||||||
|
const [publishPlatforms, setPublishPlatforms] = useState({ tiktok: true, instagram: true, youtube: true });
|
||||||
|
const [isScheduling, setIsScheduling] = useState(false);
|
||||||
|
const [scheduleDate, setScheduleDate] = useState('');
|
||||||
|
|
||||||
// UI
|
// UI
|
||||||
const [copied, setCopied] = useState('');
|
const [copied, setCopied] = useState('');
|
||||||
const [logsExpanded, setLogsExpanded] = useState(true);
|
const [logsExpanded, setLogsExpanded] = useState(true);
|
||||||
|
|
@ -85,6 +99,16 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Fetch actor gallery on mount
|
||||||
|
useEffect(() => {
|
||||||
|
setLoadingGallery(true);
|
||||||
|
fetch(getApiUrl('/api/saasshorts/actor-gallery'))
|
||||||
|
.then(res => res.ok ? res.json() : { images: [] })
|
||||||
|
.then(data => setActorGallery(data.images || []))
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => setLoadingGallery(false));
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Fetch voices on mount
|
// Fetch voices on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (elevenLabsKey) {
|
if (elevenLabsKey) {
|
||||||
|
|
@ -144,7 +168,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAnalyze = async () => {
|
const handleAnalyze = async () => {
|
||||||
if (!url.trim()) return;
|
if (!url.trim() && !description.trim()) return;
|
||||||
if (!geminiApiKey) {
|
if (!geminiApiKey) {
|
||||||
setAnalyzeError('Gemini API key required. Set it in Settings.');
|
setAnalyzeError('Gemini API key required. Set it in Settings.');
|
||||||
return;
|
return;
|
||||||
|
|
@ -160,7 +184,14 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Gemini-Key': geminiApiKey,
|
'X-Gemini-Key': geminiApiKey,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ url: url.trim(), num_scripts: numScripts, style, language, actor_gender: actorGender }),
|
body: JSON.stringify({
|
||||||
|
url: url.trim() || undefined,
|
||||||
|
description: description.trim() || undefined,
|
||||||
|
num_scripts: numScripts,
|
||||||
|
style,
|
||||||
|
language,
|
||||||
|
actor_gender: actorGender,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|
@ -220,6 +251,8 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
try {
|
try {
|
||||||
// Update script with edited narration
|
// Update script with edited narration
|
||||||
const scriptToSend = { ...scripts[selectedScript] };
|
const scriptToSend = { ...scripts[selectedScript] };
|
||||||
|
scriptToSend._product_name = analysis?.product_name || analysis?.name || '';
|
||||||
|
scriptToSend._product_url = url;
|
||||||
if (editedNarration !== scriptToSend.full_narration) {
|
if (editedNarration !== scriptToSend.full_narration) {
|
||||||
scriptToSend.full_narration = editedNarration;
|
scriptToSend.full_narration = editedNarration;
|
||||||
}
|
}
|
||||||
|
|
@ -236,6 +269,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
voice_id: selectedVoice,
|
voice_id: selectedVoice,
|
||||||
actor_description: actorDescription || undefined,
|
actor_description: actorDescription || undefined,
|
||||||
selected_actor_url: selectedActor || undefined,
|
selected_actor_url: selectedActor || undefined,
|
||||||
|
video_mode: videoMode,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -263,6 +297,8 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const scriptToSend = { ...scripts[selectedScript] };
|
const scriptToSend = { ...scripts[selectedScript] };
|
||||||
|
scriptToSend._product_name = analysis?.product_name || analysis?.name || '';
|
||||||
|
scriptToSend._product_url = url;
|
||||||
if (editedNarration !== scriptToSend.full_narration) {
|
if (editedNarration !== scriptToSend.full_narration) {
|
||||||
scriptToSend.full_narration = editedNarration;
|
scriptToSend.full_narration = editedNarration;
|
||||||
}
|
}
|
||||||
|
|
@ -279,6 +315,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
voice_id: selectedVoice,
|
voice_id: selectedVoice,
|
||||||
actor_description: actorDescription || undefined,
|
actor_description: actorDescription || undefined,
|
||||||
retry_job_id: jobId,
|
retry_job_id: jobId,
|
||||||
|
video_mode: videoMode,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -334,10 +371,10 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
<div className="w-10 h-10 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-xl flex items-center justify-center">
|
<div className="w-10 h-10 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-xl flex items-center justify-center">
|
||||||
<Zap size={20} className="text-white" />
|
<Zap size={20} className="text-white" />
|
||||||
</div>
|
</div>
|
||||||
SaaS Shorts
|
AI Shorts
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-zinc-500 mt-1">
|
<p className="text-sm text-zinc-500 mt-1">
|
||||||
Generate viral UGC videos for your SaaS with AI actors
|
Generate viral UGC videos for any product or business
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{step > 0 && (
|
{step > 0 && (
|
||||||
|
|
@ -349,7 +386,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
|
|
||||||
{/* Progress Steps */}
|
{/* Progress Steps */}
|
||||||
<div className="flex items-center gap-2 mb-8">
|
<div className="flex items-center gap-2 mb-8">
|
||||||
{['URL & Style', 'Analysis', 'Configure', 'Generate', 'Result'].map((label, i) => (
|
{['Setup', 'Analysis', 'Configure', 'Generate', 'Result'].map((label, i) => (
|
||||||
<React.Fragment key={i}>
|
<React.Fragment key={i}>
|
||||||
{i > 0 && <div className={`flex-1 h-px ${i <= step ? 'bg-violet-500' : 'bg-white/10'}`} />}
|
{i > 0 && <div className={`flex-1 h-px ${i <= step ? 'bg-violet-500' : 'bg-white/10'}`} />}
|
||||||
<div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
|
<div className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
|
||||||
|
|
@ -374,8 +411,43 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
{step === 0 && (
|
{step === 0 && (
|
||||||
<div className="animate-[fadeIn_0.3s_ease-out] space-y-6">
|
<div className="animate-[fadeIn_0.3s_ease-out] space-y-6">
|
||||||
<div className="glass-panel p-8 space-y-6">
|
<div className="glass-panel p-8 space-y-6">
|
||||||
|
{/* Video Mode Selector */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-zinc-300 mb-2">SaaS Website URL</label>
|
<label className="block text-sm font-medium text-zinc-300 mb-3">Video Mode</label>
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<button
|
||||||
|
onClick={() => setVideoMode('lowcost')}
|
||||||
|
className={`p-4 rounded-xl border text-left transition-all ${
|
||||||
|
videoMode === 'lowcost'
|
||||||
|
? 'border-green-500/50 bg-green-500/10 ring-1 ring-green-500/30'
|
||||||
|
: 'border-white/10 bg-white/5 hover:bg-white/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className={`text-sm font-semibold ${videoMode === 'lowcost' ? 'text-green-300' : 'text-zinc-300'}`}>Low Cost</span>
|
||||||
|
<span className="text-xs font-mono text-green-400 bg-green-500/10 px-2 py-0.5 rounded-full">~$0.80</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-zinc-500 leading-relaxed">Hailuo 2.3 img2video + VEED Lipsync. Good movement + lip-sync. Recommended.</p>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setVideoMode('premium')}
|
||||||
|
className={`p-4 rounded-xl border text-left transition-all ${
|
||||||
|
videoMode === 'premium'
|
||||||
|
? 'border-violet-500/50 bg-violet-500/10 ring-1 ring-violet-500/30'
|
||||||
|
: 'border-white/10 bg-white/5 hover:bg-white/10'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className={`text-sm font-semibold ${videoMode === 'premium' ? 'text-violet-300' : 'text-zinc-300'}`}>Premium</span>
|
||||||
|
<span className="text-xs font-mono text-violet-400 bg-violet-500/10 px-2 py-0.5 rounded-full">~$2.00</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-zinc-500 leading-relaxed">Kling Avatar v2 Standard. Full integrated movement. Best quality.</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-300 mb-2">Website URL <span className="text-zinc-600">(optional)</span></label>
|
||||||
<div className="flex gap-3">
|
<div className="flex gap-3">
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
<Globe size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
|
<Globe size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
|
||||||
|
|
@ -383,12 +455,26 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
type="url"
|
type="url"
|
||||||
value={url}
|
value={url}
|
||||||
onChange={(e) => setUrl(e.target.value)}
|
onChange={(e) => setUrl(e.target.value)}
|
||||||
placeholder="https://your-saas.com"
|
placeholder="https://your-website.com"
|
||||||
className="input-field pl-10"
|
className="input-field pl-10"
|
||||||
onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()}
|
onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="text-[10px] text-zinc-600 mt-1">If provided, we'll scrape and research your site automatically</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-300 mb-2">
|
||||||
|
{url.trim() ? 'Extra context' : 'Describe your product/business'} <span className="text-zinc-600">{url.trim() ? '(optional)' : '(required if no URL)'}</span>
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
rows={2}
|
||||||
|
className="input-field resize-none text-sm"
|
||||||
|
placeholder="e.g. Pizzería artesanal en Madrid, Coach de productividad, Tienda de ropa deportiva, App de meditación..."
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -481,18 +567,18 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={handleAnalyze}
|
onClick={handleAnalyze}
|
||||||
disabled={analyzing || !url.trim()}
|
disabled={analyzing || (!url.trim() && !description.trim())}
|
||||||
className="btn-primary w-full py-3 text-sm font-semibold flex items-center justify-center gap-2 disabled:opacity-50"
|
className="btn-primary w-full py-3 text-sm font-semibold flex items-center justify-center gap-2 disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{analyzing ? (
|
{analyzing ? (
|
||||||
<>
|
<>
|
||||||
<Loader2 size={16} className="animate-spin" />
|
<Loader2 size={16} className="animate-spin" />
|
||||||
Scraping + Researching web + Generating scripts... (45-90s)
|
{url.trim() ? 'Scraping + Researching web + Generating scripts... (45-90s)' : 'Generating scripts... (20-40s)'}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Sparkles size={16} />
|
<Sparkles size={16} />
|
||||||
Research & Generate Scripts
|
{url.trim() ? 'Research & Generate Scripts' : 'Generate Scripts'}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -503,7 +589,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
<div className="glass-panel p-4">
|
<div className="glass-panel p-4">
|
||||||
<Target size={16} className="text-violet-400 mb-2" />
|
<Target size={16} className="text-violet-400 mb-2" />
|
||||||
<h3 className="text-sm font-medium text-zinc-300">Deep Research</h3>
|
<h3 className="text-sm font-medium text-zinc-300">Deep Research</h3>
|
||||||
<p className="text-xs text-zinc-500 mt-1">AI scrapes your website + searches Google for reviews, Reddit threads, competitors & real user feedback.</p>
|
<p className="text-xs text-zinc-500 mt-1">AI analyzes your product via URL scraping + web research, or generates directly from your description.</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="glass-panel p-4">
|
<div className="glass-panel p-4">
|
||||||
<MessageSquare size={16} className="text-violet-400 mb-2" />
|
<MessageSquare size={16} className="text-violet-400 mb-2" />
|
||||||
|
|
@ -513,7 +599,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
<div className="glass-panel p-4">
|
<div className="glass-panel p-4">
|
||||||
<Film size={16} className="text-violet-400 mb-2" />
|
<Film size={16} className="text-violet-400 mb-2" />
|
||||||
<h3 className="text-sm font-medium text-zinc-300">AI Actor Videos</h3>
|
<h3 className="text-sm font-medium text-zinc-300">AI Actor Videos</h3>
|
||||||
<p className="text-xs text-zinc-500 mt-1">Realistic AI-generated actors with lip-sync, b-roll, and viral subtitles. ~$2.50/video.</p>
|
<p className="text-xs text-zinc-500 mt-1">Realistic AI-generated actors with lip-sync, b-roll, and viral subtitles. From ~$0.50/video.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -763,8 +849,8 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
const filtered = voices.length > 0
|
const filtered = voices.length > 0
|
||||||
? voices.filter((v) => {
|
? voices.filter((v) => {
|
||||||
const gender = (v.labels?.gender || '').toLowerCase();
|
const gender = (v.labels?.gender || '').toLowerCase();
|
||||||
// Filter by gender only — for Spanish, multilingual_v2 makes any voice work
|
// Only show voices that match the selected gender
|
||||||
return !gender || gender === actorGender;
|
return gender === actorGender;
|
||||||
})
|
})
|
||||||
.sort((a, b) => {
|
.sort((a, b) => {
|
||||||
const aAccent = (a.labels?.accent || '').toLowerCase();
|
const aAccent = (a.labels?.accent || '').toLowerCase();
|
||||||
|
|
@ -852,18 +938,117 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actor Description + Mandatory Selection */}
|
{/* Actor Selection: Gallery + Generate New */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-zinc-300 mb-2 flex items-center gap-2">
|
<label className="block text-sm font-medium text-zinc-300 mb-2 flex items-center gap-2">
|
||||||
<User size={14} /> AI Actor — Choose Your Actor
|
<User size={14} /> AI Actor — Choose Your Actor
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
|
{/* Existing Gallery from S3 */}
|
||||||
|
{actorGallery.length > 0 && (
|
||||||
|
<div className="mb-4">
|
||||||
|
<p className="text-xs text-zinc-400 mb-2">Previously generated actors (click to select):</p>
|
||||||
|
<div className="grid grid-cols-4 sm:grid-cols-6 gap-2 max-h-48 overflow-y-auto pr-1">
|
||||||
|
{actorGallery.map((img, i) => (
|
||||||
|
<button
|
||||||
|
key={img.url}
|
||||||
|
onClick={() => setSelectedActor(img.url)}
|
||||||
|
className={`relative rounded-lg overflow-hidden border-2 transition-all aspect-[3/4] ${
|
||||||
|
selectedActor === img.url ? 'border-violet-500 ring-2 ring-violet-500/30 scale-[1.02]' : 'border-white/10 hover:border-white/30'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<img src={img.url} alt={`Actor ${i+1}`} className="w-full h-full object-cover" />
|
||||||
|
{selectedActor === img.url && (
|
||||||
|
<div className="absolute top-1 right-1 w-5 h-5 bg-violet-500 rounded-full flex items-center justify-center shadow-lg">
|
||||||
|
<Check size={10} className="text-white" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{loadingGallery && (
|
||||||
|
<p className="text-xs text-zinc-500 mb-3 flex items-center gap-1"><Loader2 size={12} className="animate-spin" /> Loading actor gallery...</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Upload Custom Actor */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<label className="flex-1 flex items-center justify-center gap-2 text-sm bg-white/5 text-zinc-400 px-4 py-3 rounded-lg border border-dashed border-white/20 hover:bg-white/10 hover:border-white/30 transition-colors cursor-pointer">
|
||||||
|
<Upload size={14} />
|
||||||
|
<span>Upload your own photo</span>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
className="hidden"
|
||||||
|
onChange={async (e) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
// Show instant preview
|
||||||
|
const localPreview = URL.createObjectURL(file);
|
||||||
|
setUploadedActorPreview({ localPreview, serverUrl: null });
|
||||||
|
setSelectedActor(null);
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
try {
|
||||||
|
const res = await fetch(getApiUrl('/api/saasshorts/actor-upload'), {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.url) {
|
||||||
|
setUploadedActorPreview({ localPreview, serverUrl: data.url });
|
||||||
|
setSelectedActor(data.url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) { console.error('Upload failed:', err); }
|
||||||
|
e.target.value = '';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{uploadedActorPreview && (
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if (uploadedActorPreview.serverUrl) {
|
||||||
|
setSelectedActor(uploadedActorPreview.serverUrl);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`relative w-16 h-20 rounded-lg overflow-hidden border-2 transition-all flex-shrink-0 ${
|
||||||
|
selectedActor === uploadedActorPreview.serverUrl
|
||||||
|
? 'border-violet-500 ring-2 ring-violet-500/30'
|
||||||
|
: 'border-white/20 hover:border-white/40'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<img src={uploadedActorPreview.localPreview} alt="Uploaded" className="w-full h-full object-cover" />
|
||||||
|
{selectedActor === uploadedActorPreview.serverUrl && (
|
||||||
|
<div className="absolute top-1 right-1 w-4 h-4 bg-violet-500 rounded-full flex items-center justify-center">
|
||||||
|
<Check size={8} className="text-white" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{!uploadedActorPreview.serverUrl && (
|
||||||
|
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||||
|
<Loader2 size={12} className="animate-spin text-white" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Generate New Actors */}
|
||||||
|
<p className="text-xs text-zinc-500 mb-2">{actorGallery.length > 0 ? 'Or generate new actors:' : 'Or describe your actor:'}</p>
|
||||||
<textarea
|
<textarea
|
||||||
value={actorDescription}
|
value={actorDescription}
|
||||||
onChange={(e) => { setActorDescription(e.target.value); setActorOptions([]); setSelectedActor(null); }}
|
onChange={(e) => { setActorDescription(e.target.value); setActorOptions([]); }}
|
||||||
rows={2}
|
rows={2}
|
||||||
className="input-field resize-none text-sm"
|
className="input-field resize-none text-sm"
|
||||||
placeholder="e.g. A young woman in her late 20s, dark hair, casual outfit..."
|
placeholder="e.g. A young woman in her late 20s, dark hair, casual outfit..."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (!falKey || !actorDescription) return;
|
if (!falKey || !actorDescription) return;
|
||||||
|
|
@ -879,6 +1064,12 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setActorOptions(data.images || []);
|
setActorOptions(data.images || []);
|
||||||
|
// Refresh gallery to include newly uploaded actors
|
||||||
|
const galRes = await fetch(getApiUrl('/api/saasshorts/actor-gallery'));
|
||||||
|
if (galRes.ok) {
|
||||||
|
const galData = await galRes.json();
|
||||||
|
setActorGallery(galData.images || []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (e) { console.error(e); }
|
} catch (e) { console.error(e); }
|
||||||
finally { setGeneratingActors(false); }
|
finally { setGeneratingActors(false); }
|
||||||
|
|
@ -886,30 +1077,30 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
disabled={generatingActors || !falKey || !actorDescription}
|
disabled={generatingActors || !falKey || !actorDescription}
|
||||||
className="mt-2 w-full text-sm bg-violet-500/20 text-violet-300 px-4 py-2.5 rounded-lg hover:bg-violet-500/30 transition-colors disabled:opacity-40 flex items-center justify-center gap-2 font-medium"
|
className="mt-2 w-full text-sm bg-violet-500/20 text-violet-300 px-4 py-2.5 rounded-lg hover:bg-violet-500/30 transition-colors disabled:opacity-40 flex items-center justify-center gap-2 font-medium"
|
||||||
>
|
>
|
||||||
{generatingActors ? <><Loader2 size={14} className="animate-spin" /> Generating 3 actors...</> : <><User size={14} /> {actorOptions.length > 0 ? 'Regenerate Actors' : 'Generate 3 Actor Options'} (~$0.06)</>}
|
{generatingActors ? <><Loader2 size={14} className="animate-spin" /> Generating 3 actors...</> : <><User size={14} /> {actorOptions.length > 0 ? 'Regenerate Actors' : 'Generate 3 New Actors'} (~$0.06)</>}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Actor Options Grid — Must select one */}
|
{/* Newly Generated Actor Options */}
|
||||||
{actorOptions.length > 0 && (
|
{actorOptions.length > 0 && (
|
||||||
<div className="mt-3">
|
<div className="mt-3">
|
||||||
<p className="text-xs text-zinc-400 mb-2">Select an actor to continue:</p>
|
<p className="text-xs text-zinc-400 mb-2">New actors (select one):</p>
|
||||||
<div className="grid grid-cols-3 gap-3">
|
<div className="grid grid-cols-3 gap-3">
|
||||||
{actorOptions.map((imgUrl, i) => (
|
{actorOptions.map((imgUrl, i) => (
|
||||||
<button
|
<button
|
||||||
key={i}
|
key={imgUrl}
|
||||||
onClick={() => setSelectedActor(imgUrl)}
|
onClick={() => setSelectedActor(imgUrl)}
|
||||||
className={`relative rounded-xl overflow-hidden border-2 transition-all aspect-[9/16] ${
|
className={`relative rounded-xl overflow-hidden border-2 transition-all aspect-[9/16] ${
|
||||||
selectedActor === imgUrl ? 'border-violet-500 ring-2 ring-violet-500/30 scale-[1.02]' : 'border-white/10 hover:border-white/30'
|
selectedActor === imgUrl ? 'border-violet-500 ring-2 ring-violet-500/30 scale-[1.02]' : 'border-white/10 hover:border-white/30'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<img src={getApiUrl(imgUrl)} alt={`Option ${i+1}`} className="w-full h-full object-cover" />
|
<img src={imgUrl} alt={`New ${i+1}`} className="w-full h-full object-cover" />
|
||||||
{selectedActor === imgUrl && (
|
{selectedActor === imgUrl && (
|
||||||
<div className="absolute top-2 right-2 w-6 h-6 bg-violet-500 rounded-full flex items-center justify-center shadow-lg">
|
<div className="absolute top-2 right-2 w-6 h-6 bg-violet-500 rounded-full flex items-center justify-center shadow-lg">
|
||||||
<Check size={12} className="text-white" />
|
<Check size={12} className="text-white" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="absolute bottom-0 inset-x-0 bg-gradient-to-t from-black/60 to-transparent p-2">
|
<div className="absolute bottom-0 inset-x-0 bg-gradient-to-t from-black/60 to-transparent p-2">
|
||||||
<span className="text-[10px] text-white/80">Option {i+1}</span>
|
<span className="text-[10px] text-white/80">New {i+1}</span>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
|
|
@ -917,7 +1108,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!selectedActor && actorOptions.length > 0 && (
|
{!selectedActor && (actorOptions.length > 0 || actorGallery.length > 0) && (
|
||||||
<p className="text-xs text-amber-400 mt-2 flex items-center gap-1"><AlertCircle size={12} /> Select an actor to continue</p>
|
<p className="text-xs text-amber-400 mt-2 flex items-center gap-1"><AlertCircle size={12} /> Select an actor to continue</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -940,10 +1131,13 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
<div className="p-3 bg-white/5 rounded-lg border border-white/10">
|
<div className="p-3 bg-white/5 rounded-lg border border-white/10">
|
||||||
<div className="flex items-center justify-between text-sm">
|
<div className="flex items-center justify-between text-sm">
|
||||||
<span className="text-zinc-400">Estimated cost</span>
|
<span className="text-zinc-400">Estimated cost</span>
|
||||||
<span className="text-green-400 font-semibold">~$2.50</span>
|
<span className="text-green-400 font-semibold">~${videoMode === 'lowcost' ? '0.65' : '2.50'}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] text-zinc-600 mt-1">
|
<div className="text-[10px] text-zinc-600 mt-1">
|
||||||
Flux image ($0.05) + ElevenLabs voice ($0.10) + Kling avatar ($1.69) + Kling b-roll ($0.70)
|
{videoMode === 'lowcost'
|
||||||
|
? 'Flux image ($0.05) + ElevenLabs voice ($0.10) + Hailuo 2.3 img2video ($0.19) + VEED Lipsync ($0.20) + Flux b-roll ($0.10)'
|
||||||
|
: 'Flux image ($0.05) + ElevenLabs voice ($0.10) + Kling avatar ($1.69) + Kling b-roll ($0.70)'
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -971,7 +1165,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
) : !selectedActor ? (
|
) : !selectedActor ? (
|
||||||
<><User size={14} /> Select an actor first</>
|
<><User size={14} /> Select an actor first</>
|
||||||
) : (
|
) : (
|
||||||
<><Film size={14} /> Generate Video (~$2.00)</>
|
<><Film size={14} /> Generate Video (~${videoMode === 'lowcost' ? '0.65' : '2.00'})</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -1183,6 +1377,113 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey }) {
|
||||||
<RefreshCw size={14} /> New Video
|
<RefreshCw size={14} /> New Video
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Publish to Social Media */}
|
||||||
|
<div className="p-4 bg-white/5 rounded-xl border border-white/10 space-y-3 mt-2">
|
||||||
|
<h3 className="text-sm font-semibold text-zinc-300 flex items-center gap-2">
|
||||||
|
<Share2 size={14} /> Publish to Social Media
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
{!uploadPostKey ? (
|
||||||
|
<p className="text-xs text-zinc-500">Set your Upload-Post API key in Settings to enable publishing.</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Platform checkboxes */}
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{[
|
||||||
|
{ id: 'tiktok', label: 'TikTok', icon: '🎵' },
|
||||||
|
{ id: 'instagram', label: 'Instagram', icon: '📸' },
|
||||||
|
{ id: 'youtube', label: 'YouTube', icon: '▶️' },
|
||||||
|
].map((p) => (
|
||||||
|
<label key={p.id} className="flex items-center gap-2 text-xs text-zinc-300 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={publishPlatforms[p.id]}
|
||||||
|
onChange={(e) => setPublishPlatforms({ ...publishPlatforms, [p.id]: e.target.checked })}
|
||||||
|
className="w-3.5 h-3.5 rounded border-zinc-600 bg-black/50 text-violet-500 focus:ring-violet-500"
|
||||||
|
/>
|
||||||
|
<span>{p.icon}</span> {p.label}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Schedule toggle */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<label className="flex items-center gap-2 text-xs text-zinc-400 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={isScheduling}
|
||||||
|
onChange={(e) => setIsScheduling(e.target.checked)}
|
||||||
|
className="w-3.5 h-3.5 rounded border-zinc-600 bg-black/50 text-violet-500 focus:ring-violet-500"
|
||||||
|
/>
|
||||||
|
<Calendar size={12} /> Schedule
|
||||||
|
</label>
|
||||||
|
{isScheduling && (
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={scheduleDate}
|
||||||
|
onChange={(e) => setScheduleDate(e.target.value)}
|
||||||
|
className="input-field text-xs py-1 px-2 w-auto"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Publish button */}
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
const selected = Object.keys(publishPlatforms).filter(k => publishPlatforms[k]);
|
||||||
|
if (selected.length === 0) { setPublishResult({ ok: false, msg: 'Select at least one platform' }); return; }
|
||||||
|
if (isScheduling && !scheduleDate) { setPublishResult({ ok: false, msg: 'Select a date' }); return; }
|
||||||
|
|
||||||
|
setPublishing(true);
|
||||||
|
setPublishResult(null);
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
job_id: jobId,
|
||||||
|
api_key: uploadPostKey,
|
||||||
|
user_id: uploadUserId,
|
||||||
|
platforms: selected,
|
||||||
|
title: genResult.script?.title,
|
||||||
|
description: genResult.script?.caption || genResult.script?.full_narration,
|
||||||
|
};
|
||||||
|
if (isScheduling && scheduleDate) {
|
||||||
|
payload.scheduled_date = new Date(scheduleDate).toISOString();
|
||||||
|
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||||
|
}
|
||||||
|
const res = await fetch(getApiUrl('/api/saasshorts/post'), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({ detail: 'Failed' }));
|
||||||
|
throw new Error(err.detail || 'Failed');
|
||||||
|
}
|
||||||
|
setPublishResult({ ok: true, msg: isScheduling ? 'Scheduled!' : 'Published!' });
|
||||||
|
} catch (e) {
|
||||||
|
setPublishResult({ ok: false, msg: e.message });
|
||||||
|
} finally {
|
||||||
|
setPublishing(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={publishing}
|
||||||
|
className="w-full btn-primary py-2 text-sm flex items-center justify-center gap-2 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{publishing ? (
|
||||||
|
<><Loader2 size={14} className="animate-spin" /> {isScheduling ? 'Scheduling...' : 'Publishing...'}</>
|
||||||
|
) : (
|
||||||
|
<><Share2 size={14} /> {isScheduling ? 'Schedule Post' : 'Publish Now'}</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{publishResult && (
|
||||||
|
<p className={`text-xs ${publishResult.ok ? 'text-green-400' : 'text-red-400'}`}>
|
||||||
|
{publishResult.msg}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
237
dashboard/src/components/UGCGallery.jsx
Normal file
237
dashboard/src/components/UGCGallery.jsx
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
|
import { Film, Download, Copy, Check, ExternalLink, Loader2, Play, User } from 'lucide-react';
|
||||||
|
import { getApiUrl } from '../config';
|
||||||
|
|
||||||
|
export default function UGCGallery() {
|
||||||
|
const [tab, setTab] = useState('videos');
|
||||||
|
const [videos, setVideos] = useState([]);
|
||||||
|
const [avatars, setAvatars] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [copied, setCopied] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLoading(true);
|
||||||
|
Promise.all([
|
||||||
|
fetch(getApiUrl('/api/saasshorts/gallery?limit=100')).then(r => r.ok ? r.json() : { videos: [] }),
|
||||||
|
fetch(getApiUrl('/api/saasshorts/actor-gallery')).then(r => r.ok ? r.json() : { images: [] }),
|
||||||
|
])
|
||||||
|
.then(([vData, aData]) => {
|
||||||
|
setVideos(vData.videos || []);
|
||||||
|
setAvatars(aData.images || []);
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleCopy = (text, id) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopied(id);
|
||||||
|
setTimeout(() => setCopied(''), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-64">
|
||||||
|
<Loader2 size={24} className="animate-spin text-violet-400" />
|
||||||
|
<span className="ml-2 text-zinc-400">Loading gallery...</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-bold text-zinc-200">UGC Gallery</h2>
|
||||||
|
<p className="text-xs text-zinc-500">{videos.length} videos · {avatars.length} avatars</p>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href={getApiUrl('/gallery')}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-xs text-violet-400 hover:text-violet-300 flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<ExternalLink size={12} /> Public Gallery
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex gap-1 bg-white/5 p-1 rounded-lg w-fit">
|
||||||
|
<button
|
||||||
|
onClick={() => setTab('videos')}
|
||||||
|
className={`px-4 py-1.5 rounded-md text-xs font-medium transition-all ${
|
||||||
|
tab === 'videos' ? 'bg-violet-500/20 text-violet-300' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Film size={12} className="inline mr-1.5" />Videos ({videos.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setTab('avatars')}
|
||||||
|
className={`px-4 py-1.5 rounded-md text-xs font-medium transition-all ${
|
||||||
|
tab === 'avatars' ? 'bg-violet-500/20 text-violet-300' : 'text-zinc-400 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<User size={12} className="inline mr-1.5" />Avatars ({avatars.length})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Videos Tab */}
|
||||||
|
{tab === 'videos' && (
|
||||||
|
videos.length === 0 ? (
|
||||||
|
<div className="text-center py-16">
|
||||||
|
<Film size={40} className="mx-auto text-zinc-700 mb-3" />
|
||||||
|
<p className="text-sm text-zinc-500">No videos yet. Generate one from AI Shorts.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
|
||||||
|
{videos.map((video) => (
|
||||||
|
<VideoCard key={video.video_id} video={video} copied={copied} onCopy={handleCopy} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Avatars Tab */}
|
||||||
|
{tab === 'avatars' && (
|
||||||
|
avatars.length === 0 ? (
|
||||||
|
<div className="text-center py-16">
|
||||||
|
<User size={40} className="mx-auto text-zinc-700 mb-3" />
|
||||||
|
<p className="text-sm text-zinc-500">No avatars yet. Generate actors from AI Shorts.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-3">
|
||||||
|
{avatars.map((avatar, i) => (
|
||||||
|
<AvatarCard key={avatar.key || i} avatar={avatar} copied={copied} onCopy={handleCopy} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarCard({ avatar, copied, onCopy }) {
|
||||||
|
return (
|
||||||
|
<div className="group rounded-xl overflow-hidden border border-white/10 bg-white/5 hover:border-white/20 transition-all">
|
||||||
|
<div className="aspect-[3/4] bg-black">
|
||||||
|
<img src={avatar.url} alt="Avatar" className="w-full h-full object-cover" />
|
||||||
|
</div>
|
||||||
|
<div className="p-2 space-y-1">
|
||||||
|
{avatar.description ? (
|
||||||
|
<div className="relative pr-4">
|
||||||
|
<p className="text-[9px] text-zinc-400 line-clamp-2">{avatar.description}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => onCopy(avatar.description, `avatar-${avatar.key}`)}
|
||||||
|
className="absolute top-0 right-0 p-0.5 text-zinc-600 hover:text-zinc-300"
|
||||||
|
title="Copy prompt"
|
||||||
|
>
|
||||||
|
{copied === `avatar-${avatar.key}` ? <Check size={9} /> : <Copy size={9} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-[9px] text-zinc-600 italic">No description</p>
|
||||||
|
)}
|
||||||
|
<a
|
||||||
|
href={avatar.url}
|
||||||
|
download
|
||||||
|
className="block text-center text-[9px] bg-white/5 hover:bg-white/10 text-zinc-400 py-1 rounded-md transition-colors"
|
||||||
|
>
|
||||||
|
<Download size={9} className="inline mr-0.5" />Download
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function VideoCard({ video, copied, onCopy }) {
|
||||||
|
const videoRef = useRef(null);
|
||||||
|
const [playing, setPlaying] = useState(false);
|
||||||
|
|
||||||
|
const handleMouseEnter = () => {
|
||||||
|
if (videoRef.current) {
|
||||||
|
videoRef.current.play().catch(() => {});
|
||||||
|
setPlaying(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseLeave = () => {
|
||||||
|
if (videoRef.current) {
|
||||||
|
videoRef.current.pause();
|
||||||
|
videoRef.current.currentTime = 0;
|
||||||
|
setPlaying(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const mode = video.video_mode;
|
||||||
|
const caption = video.caption || '';
|
||||||
|
const hashtags = (video.hashtags || []).join(' ');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="group rounded-xl overflow-hidden border border-white/10 bg-white/5 hover:border-white/20 transition-all">
|
||||||
|
<div
|
||||||
|
className="relative aspect-[9/16] bg-black cursor-pointer"
|
||||||
|
onMouseEnter={handleMouseEnter}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
|
>
|
||||||
|
<video
|
||||||
|
ref={videoRef}
|
||||||
|
src={video.video_url}
|
||||||
|
poster={video.actor_url}
|
||||||
|
muted
|
||||||
|
playsInline
|
||||||
|
preload="metadata"
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
{!playing && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-black/20">
|
||||||
|
<Play size={20} className="text-white/70" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="absolute top-1.5 right-1.5">
|
||||||
|
<span className={`text-[8px] font-bold px-1.5 py-0.5 rounded-full ${
|
||||||
|
mode === 'lowcost' ? 'bg-green-500 text-black' : 'bg-violet-500 text-white'
|
||||||
|
}`}>
|
||||||
|
{mode === 'lowcost' ? 'LOW COST' : 'PREMIUM'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-2 space-y-1">
|
||||||
|
<h3 className="text-[11px] font-semibold text-zinc-200 truncate">{video.title || 'Untitled'}</h3>
|
||||||
|
<p className="text-[9px] text-zinc-500">
|
||||||
|
{video.duration?.toFixed(0)}s · ${video.cost_estimate?.total?.toFixed(2) || '?'}
|
||||||
|
</p>
|
||||||
|
{caption && (
|
||||||
|
<div className="relative pr-4">
|
||||||
|
<p className="text-[9px] text-zinc-400 line-clamp-2">{caption}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => onCopy(`${caption}\n${hashtags}`, `caption-${video.video_id}`)}
|
||||||
|
className="absolute top-0 right-0 p-0.5 text-zinc-600 hover:text-zinc-300"
|
||||||
|
title="Copy caption"
|
||||||
|
>
|
||||||
|
{copied === `caption-${video.video_id}` ? <Check size={9} /> : <Copy size={9} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-1 pt-0.5">
|
||||||
|
<a
|
||||||
|
href={video.video_url}
|
||||||
|
download
|
||||||
|
className="flex-1 text-center text-[9px] bg-white/5 hover:bg-white/10 text-zinc-400 py-1 rounded-md transition-colors"
|
||||||
|
>
|
||||||
|
<Download size={9} className="inline mr-0.5" />Download
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={getApiUrl(`/video/${video.video_id}`)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex-1 text-center text-[9px] bg-violet-500/10 hover:bg-violet-500/20 text-violet-400 py-1 rounded-md transition-colors"
|
||||||
|
>
|
||||||
|
<ExternalLink size={9} className="inline mr-0.5" />View
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -21,6 +21,14 @@ export default defineConfig({
|
||||||
'/thumbnails': {
|
'/thumbnails': {
|
||||||
target: 'http://backend:8000',
|
target: 'http://backend:8000',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
'/gallery': {
|
||||||
|
target: 'http://backend:8000',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
'/video': {
|
||||||
|
target: 'http://backend:8000',
|
||||||
|
changeOrigin: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
243
s3_uploader.py
243
s3_uploader.py
|
|
@ -1,4 +1,6 @@
|
||||||
import os
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv()
|
||||||
import boto3
|
import boto3
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
import logging
|
import logging
|
||||||
|
|
@ -102,7 +104,7 @@ def list_all_clips(bucket_name=None, limit=50, force_refresh=False):
|
||||||
return cached[:limit] if limit else cached
|
return cached[:limit] if limit else cached
|
||||||
|
|
||||||
if not bucket_name:
|
if not bucket_name:
|
||||||
bucket_name = os.environ.get('AWS_S3_BUCKET', 'openshorts.app-clips')
|
bucket_name = os.environ.get('AWS_S3_BUCKET', 'my-clips-bucket')
|
||||||
|
|
||||||
s3_client = get_s3_client()
|
s3_client = get_s3_client()
|
||||||
if not s3_client:
|
if not s3_client:
|
||||||
|
|
@ -188,11 +190,248 @@ def list_all_clips(bucket_name=None, limit=50, force_refresh=False):
|
||||||
|
|
||||||
return all_clips[:limit] if limit else all_clips
|
return all_clips[:limit] if limit else all_clips
|
||||||
|
|
||||||
|
def upload_actor_to_s3(file_path, description=""):
|
||||||
|
"""
|
||||||
|
Upload an actor image to the public S3 bucket.
|
||||||
|
Returns the public URL or None on failure.
|
||||||
|
"""
|
||||||
|
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
|
||||||
|
region = os.environ.get('AWS_REGION', 'us-east-1')
|
||||||
|
|
||||||
|
s3_client = get_s3_client()
|
||||||
|
if not s3_client:
|
||||||
|
return None
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
unique_id = str(uuid.uuid4())[:8]
|
||||||
|
filename = os.path.basename(file_path)
|
||||||
|
name, ext = os.path.splitext(filename)
|
||||||
|
s3_key = f"avatars/{name}_{unique_id}{ext}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Skip broken/tiny files
|
||||||
|
if os.path.getsize(file_path) < 1000:
|
||||||
|
logger.warning(f"Skipping tiny file ({os.path.getsize(file_path)} bytes): {file_path}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
s3_client.upload_file(
|
||||||
|
file_path, bucket_name, s3_key,
|
||||||
|
ExtraArgs={'ContentType': 'image/png'},
|
||||||
|
)
|
||||||
|
public_url = f"https://{bucket_name}.s3.{region}.amazonaws.com/{s3_key}"
|
||||||
|
|
||||||
|
# Save metadata JSON alongside the image
|
||||||
|
if description:
|
||||||
|
import datetime
|
||||||
|
meta_key = s3_key.rsplit('.', 1)[0] + '.json'
|
||||||
|
meta = json.dumps({
|
||||||
|
"description": description,
|
||||||
|
"url": public_url,
|
||||||
|
"created_at": datetime.datetime.utcnow().isoformat() + "Z",
|
||||||
|
}, ensure_ascii=False)
|
||||||
|
s3_client.put_object(
|
||||||
|
Bucket=bucket_name, Key=meta_key,
|
||||||
|
Body=meta.encode('utf-8'),
|
||||||
|
ContentType='application/json',
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"Uploaded actor to S3: {public_url}")
|
||||||
|
return public_url
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to upload actor to S3: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def list_actor_gallery():
|
||||||
|
"""
|
||||||
|
List all actor images from the public S3 bucket.
|
||||||
|
Returns list with URLs and descriptions, newest first.
|
||||||
|
"""
|
||||||
|
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
|
||||||
|
region = os.environ.get('AWS_REGION', 'us-east-1')
|
||||||
|
|
||||||
|
s3_client = get_s3_client()
|
||||||
|
if not s3_client:
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
paginator = s3_client.get_paginator('list_objects_v2')
|
||||||
|
pages = paginator.paginate(Bucket=bucket_name, Prefix='avatars/')
|
||||||
|
|
||||||
|
all_objects = {}
|
||||||
|
for page in pages:
|
||||||
|
for obj in page.get('Contents', []):
|
||||||
|
key = obj['Key']
|
||||||
|
base = key.rsplit('.', 1)[0]
|
||||||
|
if base not in all_objects:
|
||||||
|
all_objects[base] = {}
|
||||||
|
if key.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
|
||||||
|
all_objects[base]['image'] = obj
|
||||||
|
elif key.endswith('.json'):
|
||||||
|
all_objects[base]['meta_key'] = key
|
||||||
|
|
||||||
|
images = []
|
||||||
|
for base, data in all_objects.items():
|
||||||
|
if 'image' not in data:
|
||||||
|
continue
|
||||||
|
obj = data['image']
|
||||||
|
key = obj['Key']
|
||||||
|
public_url = f"https://{bucket_name}.s3.{region}.amazonaws.com/{key}"
|
||||||
|
entry = {
|
||||||
|
"url": public_url,
|
||||||
|
"key": key,
|
||||||
|
"created_at": obj['LastModified'].isoformat(),
|
||||||
|
"description": "",
|
||||||
|
}
|
||||||
|
# Try to read metadata JSON
|
||||||
|
if 'meta_key' in data:
|
||||||
|
try:
|
||||||
|
meta_resp = s3_client.get_object(Bucket=bucket_name, Key=data['meta_key'])
|
||||||
|
meta = json.loads(meta_resp['Body'].read().decode('utf-8'))
|
||||||
|
entry['description'] = meta.get('description', '')
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
images.append(entry)
|
||||||
|
|
||||||
|
images.sort(key=lambda x: x['created_at'], reverse=True)
|
||||||
|
return images
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to list actor gallery: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
# ── SaaS Video Gallery (public S3) ──────────────────────────────────
|
||||||
|
|
||||||
|
_video_gallery_cache = {
|
||||||
|
"data": None,
|
||||||
|
"timestamp": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
def upload_video_to_gallery(video_path, actor_image_path, metadata, video_id=None):
|
||||||
|
"""
|
||||||
|
Upload a generated UGC video + actor + metadata to the public S3 bucket.
|
||||||
|
Returns dict with public URLs or None on failure.
|
||||||
|
"""
|
||||||
|
import uuid
|
||||||
|
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
|
||||||
|
region = os.environ.get('AWS_REGION', 'us-east-1')
|
||||||
|
|
||||||
|
s3_client = get_s3_client()
|
||||||
|
if not s3_client:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not video_id:
|
||||||
|
video_id = str(uuid.uuid4())[:8]
|
||||||
|
|
||||||
|
base_url = f"https://{bucket_name}.s3.{region}.amazonaws.com"
|
||||||
|
results = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Upload video
|
||||||
|
if os.path.exists(video_path):
|
||||||
|
s3_key = f"videos/{video_id}/video.mp4"
|
||||||
|
s3_client.upload_file(video_path, bucket_name, s3_key,
|
||||||
|
ExtraArgs={'ContentType': 'video/mp4'})
|
||||||
|
results["video_url"] = f"{base_url}/{s3_key}"
|
||||||
|
|
||||||
|
# Upload actor image
|
||||||
|
if actor_image_path and os.path.exists(actor_image_path):
|
||||||
|
s3_key = f"videos/{video_id}/actor.png"
|
||||||
|
s3_client.upload_file(actor_image_path, bucket_name, s3_key,
|
||||||
|
ExtraArgs={'ContentType': 'image/png'})
|
||||||
|
results["actor_url"] = f"{base_url}/{s3_key}"
|
||||||
|
|
||||||
|
# Build and upload metadata
|
||||||
|
import datetime
|
||||||
|
metadata["video_id"] = video_id
|
||||||
|
metadata["video_url"] = results.get("video_url", "")
|
||||||
|
metadata["actor_url"] = results.get("actor_url", "")
|
||||||
|
metadata["created_at"] = datetime.datetime.utcnow().isoformat() + "Z"
|
||||||
|
|
||||||
|
meta_json = json.dumps(metadata, ensure_ascii=False, indent=2)
|
||||||
|
s3_key = f"videos/{video_id}/metadata.json"
|
||||||
|
s3_client.put_object(
|
||||||
|
Bucket=bucket_name, Key=s3_key,
|
||||||
|
Body=meta_json.encode('utf-8'),
|
||||||
|
ContentType='application/json',
|
||||||
|
)
|
||||||
|
results["metadata_url"] = f"{base_url}/{s3_key}"
|
||||||
|
results["video_id"] = video_id
|
||||||
|
|
||||||
|
logger.info(f"Uploaded video gallery: {video_id}")
|
||||||
|
|
||||||
|
# Invalidate cache
|
||||||
|
_video_gallery_cache["data"] = None
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to upload video to gallery: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def list_video_gallery(limit=50, force_refresh=False):
|
||||||
|
"""
|
||||||
|
List all UGC videos from the public S3 bucket.
|
||||||
|
Returns list of metadata dicts, newest first.
|
||||||
|
"""
|
||||||
|
global _video_gallery_cache
|
||||||
|
|
||||||
|
now = time_module.time()
|
||||||
|
if not force_refresh and _video_gallery_cache["data"] is not None:
|
||||||
|
if now - _video_gallery_cache["timestamp"] < CACHE_TTL_SECONDS:
|
||||||
|
cached = _video_gallery_cache["data"]
|
||||||
|
return cached[:limit] if limit else cached
|
||||||
|
|
||||||
|
bucket_name = os.environ.get('AWS_S3_PUBLIC_BUCKET', 'my-public-bucket')
|
||||||
|
|
||||||
|
s3_client = get_s3_client()
|
||||||
|
if not s3_client:
|
||||||
|
return []
|
||||||
|
|
||||||
|
videos = []
|
||||||
|
|
||||||
|
try:
|
||||||
|
paginator = s3_client.get_paginator('list_objects_v2')
|
||||||
|
pages = paginator.paginate(Bucket=bucket_name, Prefix='videos/')
|
||||||
|
|
||||||
|
meta_files = []
|
||||||
|
for page in pages:
|
||||||
|
for obj in page.get('Contents', []):
|
||||||
|
if obj['Key'].endswith('/metadata.json'):
|
||||||
|
meta_files.append(obj)
|
||||||
|
|
||||||
|
# Newest first
|
||||||
|
meta_files.sort(key=lambda x: x['LastModified'], reverse=True)
|
||||||
|
|
||||||
|
for meta_obj in meta_files:
|
||||||
|
try:
|
||||||
|
obj_resp = s3_client.get_object(Bucket=bucket_name, Key=meta_obj['Key'])
|
||||||
|
content = obj_resp['Body'].read().decode('utf-8')
|
||||||
|
data = json.loads(content)
|
||||||
|
videos.append(data)
|
||||||
|
if limit and len(videos) >= limit:
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error reading metadata {meta_obj['Key']}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to list video gallery: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
_video_gallery_cache["data"] = videos
|
||||||
|
_video_gallery_cache["timestamp"] = now
|
||||||
|
|
||||||
|
return videos[:limit] if limit else videos
|
||||||
|
|
||||||
|
|
||||||
def upload_job_artifacts(directory, job_id):
|
def upload_job_artifacts(directory, job_id):
|
||||||
"""
|
"""
|
||||||
Upload all generated clips and metadata for a job to S3.
|
Upload all generated clips and metadata for a job to S3.
|
||||||
"""
|
"""
|
||||||
bucket_name = os.environ.get('AWS_S3_BUCKET', 'openshorts.app-clips')
|
bucket_name = os.environ.get('AWS_S3_BUCKET', 'my-clips-bucket')
|
||||||
|
|
||||||
if not os.path.exists(directory):
|
if not os.path.exists(directory):
|
||||||
return
|
return
|
||||||
|
|
|
||||||
139
saasshorts.py
139
saasshorts.py
|
|
@ -404,8 +404,8 @@ Use natural casual American English like a real person on TikTok. Contractions,
|
||||||
Examples of English UGC hooks: "Okay so I just found this tool and...", "Stop doing this manually, there's a better way", "I can't believe nobody told me about this sooner..."
|
Examples of English UGC hooks: "Okay so I just found this tool and...", "Stop doing this manually, there's a better way", "I can't believe nobody told me about this sooner..."
|
||||||
"""
|
"""
|
||||||
|
|
||||||
prompt = f"""You are a viral short-form video scriptwriter specializing in SaaS B2B marketing.
|
prompt = f"""You are a viral short-form video scriptwriter for TikTok/Instagram Reels.
|
||||||
Generate {num_scripts} video scripts for TikTok/Instagram Reels.
|
Generate {num_scripts} video scripts to promote this product/business.
|
||||||
{lang_instructions}
|
{lang_instructions}
|
||||||
PRODUCT ANALYSIS:
|
PRODUCT ANALYSIS:
|
||||||
{json.dumps(analysis, indent=2)}
|
{json.dumps(analysis, indent=2)}
|
||||||
|
|
@ -671,10 +671,11 @@ def _fal_upload_file(file_path: str, fal_key: str) -> str:
|
||||||
|
|
||||||
|
|
||||||
def generate_actor_images(
|
def generate_actor_images(
|
||||||
description: str, fal_key: str, output_dir: str, title_slug: str, num_options: int = 3
|
description: str, fal_key: str, output_dir: str, title_slug: str, num_options: int = 3,
|
||||||
|
product_description: str = None,
|
||||||
) -> List[str]:
|
) -> List[str]:
|
||||||
"""Generate multiple hyper-realistic actor portrait options using Recraft V4."""
|
"""Generate multiple hyper-realistic actor portrait options using Flux 2 Pro."""
|
||||||
print(f"[SaaSShorts] 🎨 Generating {num_options} actor image options (Recraft V4)...")
|
print(f"[SaaSShorts] 🎨 Generating {num_options} actor image options (Flux 2 Pro)...")
|
||||||
|
|
||||||
# Clean description: strip scene/actions, keep only physical appearance
|
# Clean description: strip scene/actions, keep only physical appearance
|
||||||
clean_desc = description
|
clean_desc = description
|
||||||
|
|
@ -686,7 +687,13 @@ def generate_actor_images(
|
||||||
|
|
||||||
import random
|
import random
|
||||||
img_num = random.randint(1000, 9999)
|
img_num = random.randint(1000, 9999)
|
||||||
prompt = f"""IMG_{img_num}.jpg Raw candid selfie of {clean_desc}, sitting at their desk at home, looking at camera with a relaxed natural smile. Headphones around neck, monitor glow behind them. Not posed, casual and real. Low quality front camera, soft room lighting. Reddit selfie."""
|
|
||||||
|
if product_description:
|
||||||
|
prompt = f"""IMG_{img_num}.jpg Raw candid selfie of {clean_desc}, casually holding {product_description}, showing it to the camera with a natural smile. Product clearly visible in hand. Casual and real, not an ad. Low quality front camera, soft room lighting. Reddit selfie."""
|
||||||
|
else:
|
||||||
|
prompt = f"""IMG_{img_num}.jpg Raw candid selfie of {clean_desc}, sitting at their desk at home, looking at camera with a relaxed natural smile. Headphones around neck, monitor glow behind them. Not posed, casual and real. Low quality front camera, soft room lighting. Reddit selfie."""
|
||||||
|
|
||||||
|
print(f"[SaaSShorts] Prompt: {prompt[:120]}...{' (with product)' if product_description else ''}")
|
||||||
|
|
||||||
paths = []
|
paths = []
|
||||||
# Flux 2 Pro — #1 for photorealistic faces
|
# Flux 2 Pro — #1 for photorealistic faces
|
||||||
|
|
@ -700,7 +707,7 @@ def generate_actor_images(
|
||||||
"seed": random.randint(0, 999999),
|
"seed": random.randint(0, 999999),
|
||||||
},
|
},
|
||||||
fal_key,
|
fal_key,
|
||||||
timeout=180,
|
timeout=300,
|
||||||
)
|
)
|
||||||
images = result.get("images") or result.get("output", [])
|
images = result.get("images") or result.get("output", [])
|
||||||
if not images:
|
if not images:
|
||||||
|
|
@ -855,6 +862,89 @@ def generate_talking_head(
|
||||||
return output_path
|
return output_path
|
||||||
|
|
||||||
|
|
||||||
|
def generate_talking_head_lowcost(
|
||||||
|
image_path: str,
|
||||||
|
audio_path: str,
|
||||||
|
fal_key: str,
|
||||||
|
output_path: str,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Low-cost talking head: Hailuo 2.3 Fast img2video → VEED Lipsync.
|
||||||
|
~$0.39 vs ~$1.69 for Kling Avatar v2.
|
||||||
|
"""
|
||||||
|
print(f"[SaaSShorts] 🗣️ Generating talking head (Low Cost: Hailuo + VEED Lipsync)...")
|
||||||
|
|
||||||
|
# Step 1: Generate 6s video from image using MiniMax Hailuo 2.3 Fast ($0.19)
|
||||||
|
# Cache the Hailuo clip so retries don't re-generate it
|
||||||
|
hailuo_cache_path = output_path.replace(".mp4", "_hailuo_cache.mp4")
|
||||||
|
|
||||||
|
if os.path.exists(hailuo_cache_path) and os.path.getsize(hailuo_cache_path) > 0:
|
||||||
|
print(f"[SaaSShorts] Hailuo clip cached, skipping generation.")
|
||||||
|
hailuo_video_url = _fal_upload_file(hailuo_cache_path, fal_key)
|
||||||
|
else:
|
||||||
|
image_url = _fal_upload_file(image_path, fal_key)
|
||||||
|
|
||||||
|
hailuo_result = _fal_run(
|
||||||
|
"fal-ai/minimax/hailuo-2.3-fast/standard/image-to-video",
|
||||||
|
{
|
||||||
|
"image_url": image_url,
|
||||||
|
"prompt": (
|
||||||
|
"Person talking to camera, subtle head nods and natural micro-expressions. "
|
||||||
|
"Gentle head movement, slight shoulder sway. Eye contact with camera. "
|
||||||
|
"Natural blinking. Soft ambient lighting. Smooth cinematic motion."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
fal_key,
|
||||||
|
timeout=300,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"[SaaSShorts] Hailuo response keys: {list(hailuo_result.keys())}")
|
||||||
|
if "video" in hailuo_result:
|
||||||
|
hailuo_video_url = hailuo_result["video"]["url"] if isinstance(hailuo_result["video"], dict) else hailuo_result["video"]
|
||||||
|
elif "video_url" in hailuo_result:
|
||||||
|
hailuo_video_url = hailuo_result["video_url"]
|
||||||
|
elif "output" in hailuo_result:
|
||||||
|
hailuo_video_url = hailuo_result["output"]["url"] if isinstance(hailuo_result["output"], dict) else hailuo_result["output"]
|
||||||
|
else:
|
||||||
|
raise Exception(f"No video in Hailuo result: {hailuo_result}")
|
||||||
|
|
||||||
|
# Save Hailuo clip locally for retry cache
|
||||||
|
with httpx.Client(timeout=180.0) as client:
|
||||||
|
vid_resp = client.get(hailuo_video_url)
|
||||||
|
with open(hailuo_cache_path, "wb") as f:
|
||||||
|
f.write(vid_resp.content)
|
||||||
|
|
||||||
|
print(f"[SaaSShorts] Hailuo 2.3 Fast 6s clip ready (cached for retry).")
|
||||||
|
|
||||||
|
# Step 2: Upload audio for lip-sync
|
||||||
|
audio_url = _fal_upload_file(audio_path, fal_key)
|
||||||
|
|
||||||
|
# Step 3: VEED Lipsync — high quality lip-sync with loop ($0.20 for 30s)
|
||||||
|
lipsync_result = _fal_run(
|
||||||
|
"veed/lipsync",
|
||||||
|
{
|
||||||
|
"video_url": hailuo_video_url,
|
||||||
|
"audio_url": audio_url,
|
||||||
|
},
|
||||||
|
fal_key,
|
||||||
|
timeout=900,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"[SaaSShorts] VEED Lipsync response keys: {list(lipsync_result.keys())}")
|
||||||
|
if "video" in lipsync_result:
|
||||||
|
lipsync_video_url = lipsync_result["video"]["url"] if isinstance(lipsync_result["video"], dict) else lipsync_result["video"]
|
||||||
|
else:
|
||||||
|
raise Exception(f"No video in VEED Lipsync result: {lipsync_result}")
|
||||||
|
|
||||||
|
with httpx.Client(timeout=180.0) as client:
|
||||||
|
vid_resp = client.get(lipsync_video_url)
|
||||||
|
with open(output_path, "wb") as f:
|
||||||
|
f.write(vid_resp.content)
|
||||||
|
|
||||||
|
print(f"[SaaSShorts] ✅ Talking head (low cost): {output_path}")
|
||||||
|
return output_path
|
||||||
|
|
||||||
|
|
||||||
def generate_broll(
|
def generate_broll(
|
||||||
prompt: str, fal_key: str, output_path: str, duration: str = "5"
|
prompt: str, fal_key: str, output_path: str, duration: str = "5"
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
@ -875,7 +965,7 @@ def generate_broll(
|
||||||
"safety_tolerance": 5,
|
"safety_tolerance": 5,
|
||||||
},
|
},
|
||||||
fal_key,
|
fal_key,
|
||||||
timeout=180,
|
timeout=300,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Flux 2 Pro returns images in "images" or "output" key
|
# Flux 2 Pro returns images in "images" or "output" key
|
||||||
|
|
@ -1281,9 +1371,14 @@ def generate_full_video(
|
||||||
log("[2/6] ✅ Using cached assets.")
|
log("[2/6] ✅ Using cached assets.")
|
||||||
|
|
||||||
# ── Step 3: Generate talking head ──
|
# ── Step 3: Generate talking head ──
|
||||||
|
video_mode = config.get("video_mode", "premium")
|
||||||
if not _exists(talking_head):
|
if not _exists(talking_head):
|
||||||
log("[3/6] Generating talking head video (Kling Avatar v2)... This takes 2-5 minutes.")
|
if video_mode == "lowcost":
|
||||||
talking_head = generate_talking_head(actor_img, audio_path, fal_key, talking_head)
|
log("[3/6] Generating talking head (Low Cost: Hailuo + VEED Lipsync)... This takes 2-5 minutes.")
|
||||||
|
talking_head = generate_talking_head_lowcost(actor_img, audio_path, fal_key, talking_head)
|
||||||
|
else:
|
||||||
|
log("[3/6] Generating talking head video (Kling Avatar v2)... This takes 2-5 minutes.")
|
||||||
|
talking_head = generate_talking_head(actor_img, audio_path, fal_key, talking_head)
|
||||||
log("[3/6] Talking head ready.")
|
log("[3/6] Talking head ready.")
|
||||||
else:
|
else:
|
||||||
log("[3/6] ✅ Talking head cached, skipping.")
|
log("[3/6] ✅ Talking head cached, skipping.")
|
||||||
|
|
@ -1350,13 +1445,23 @@ def generate_full_video(
|
||||||
|
|
||||||
# Cost estimate
|
# Cost estimate
|
||||||
audio_duration = _get_media_duration(audio_path)
|
audio_duration = _get_media_duration(audio_path)
|
||||||
cost = {
|
if video_mode == "lowcost":
|
||||||
"actor_image_flux": 0.05,
|
cost = {
|
||||||
"voiceover_elevenlabs": round(len(full_narration) * 0.00003, 3),
|
"actor_image_flux": 0.05,
|
||||||
"talking_head_kling": round(audio_duration * 0.056, 2),
|
"voiceover_elevenlabs": round(len(full_narration) * 0.00003, 3),
|
||||||
"broll_kling": round(len(broll_clips) * 5 * 0.07, 2),
|
"hailuo_img2video": 0.19,
|
||||||
"ffmpeg_compositing": 0.00,
|
"veed_lipsync": 0.20,
|
||||||
}
|
"broll_flux": round(len(broll_clips) * 0.05, 2),
|
||||||
|
"ffmpeg_compositing": 0.00,
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
cost = {
|
||||||
|
"actor_image_flux": 0.05,
|
||||||
|
"voiceover_elevenlabs": round(len(full_narration) * 0.00003, 3),
|
||||||
|
"talking_head_kling": round(audio_duration * 0.056, 2),
|
||||||
|
"broll_kling": round(len(broll_clips) * 5 * 0.07, 2),
|
||||||
|
"ffmpeg_compositing": 0.00,
|
||||||
|
}
|
||||||
cost["total"] = round(sum(cost.values()), 2)
|
cost["total"] = round(sum(cost.values()), 2)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue