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