reafactor readme added instructions and texts

This commit is contained in:
juancarlos.cavero 2025-12-20 04:59:38 +01:00
parent c40e5aaa1d
commit d60c376013
4 changed files with 275 additions and 242 deletions

119
README.md
View file

@ -1,108 +1,103 @@
# OpenShorts 🚀🎬
# OpenShorts.app 🚀🎬
OpenShorts is an open-source tool designed to automate the creation of viral vertical content. It transforms long YouTube videos or local files into multiple short clips optimized for **TikTok**, **Instagram Reels**, and **YouTube Shorts**.
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**.
![OpenShorts Demo](https://github.com/kamilstanuch/Autocrop-vertical/blob/main/churchil_queen_vertical_short.gif?raw=true)
*(The demo shows the smart crop process, now powered by AI clip selection)*
---
## ✨ Key Features
OpenShorts goes beyond simple cropping. It combines the power of Artificial Intelligence to understand your video and extract pure gold:
OpenShorts leverages state-of-the-art AI to handle the entire content lifecycle:
1. **🧠 AI Virality Detection (Gemini + Whisper):**
* Automatically transcribes video audio using **OpenAI Whisper**.
* Analyzes content with **Google Gemini 1.5 Flash** to identify moments with the highest viral potential (hooks, jokes, impactful conclusions).
* Generates SEO-optimized titles and descriptions for social media.
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 Cropping (Auto-Crop):**
* Detects people and faces using **YOLOv8** and **OpenCV**.
* Keeps the subject always in the center of the vertical frame (9:16).
* Automatically applies *letterboxing* if multiple people are detected far apart to preserve context.
2. **✂️ Smart AI Cropping:**
* **YOLOv8 + OpenCV**: intelligent subject tracking that keeps people/faces centered in the 9:16 frame.
* **Dynamic Letterboxing**: Automatically handles multiple subjects to preserve context when they are far apart.
3. **⚡ Fast Processing:**
* Downloads YouTube videos in the best compatible quality.
* Performs precise cuts based on exact timestamps dictated by AI.
* Uses FFmpeg for efficient rendering.
3. **📲 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.
4. **🎨 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.
---
## 🛠️ Requirements
* **Docker** and **Docker Compose** installed on your machine.
* A **Google Gemini API Key** (Free at [Google AI Studio](https://aistudio.google.com/app/apikey)).
* **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).
### 📲 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.
![Upload-Post Setup Guide](file:///Users/juancarlos.cavero/.gemini/antigravity/brain/d72ee29e-ee3b-45f0-b00b-fe2d705bb56f/uploaded_image_1766201890395.png)
---
## 🚀 Quick Start
## 🚀 Getting Started
The easiest way to run OpenShorts is using Docker Compose.
### 1. Setup
Clone the repository and configure your API key:
```bash
# 1. Clone the repo
git clone https://github.com/your-username/OpenShorts.git
cd OpenShorts
# 2. Configure environment variables
cp .env.example .env
# 3. Edit .env and paste your GEMINI_API_KEY (must start with 'AIza...')
nano .env
```
### 2. Run with Docker
No need to install Python or libraries on your system, everything runs in a container.
**From a YouTube video:**
The system will download the video, search for viral clips, and deliver multiple vertical files ready for upload.
### 2. Launch the Application
```bash
docker compose run --rm autocrop -u "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"
docker compose up --build
```
**From a local file:**
Place your video in the `videos/input/` folder.
### 3. Access the Dashboard
Open your browser and navigate to:
**`http://localhost:5173`**
```bash
docker compose run --rm autocrop -i /videos/input/my_video.mp4
```
### 3. Results
Generated clips will appear in the `videos/` folder (or wherever you specified). Additionally, you'll find a `.json` file with the viral titles and descriptions suggested by AI for each clip.
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!
---
## ⚙️ Advanced Options
## 🏗️ Technical Pipeline
| Flag | Description |
| :--- | :--- |
| `-u`, `--url` | YouTube URL to download and process. |
| `-i`, `--input` | Path to the local video file (inside the container). |
| `-o`, `--output` | Output directory or specific filename. |
| `--keep-original` | Keeps the original downloaded video after processing. |
| `--skip-analysis` | **Classic Mode:** Skips Gemini/Whisper AI and converts the ENTIRE video to flat vertical format. |
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. **Distribution**: One-click posting via Upload-Post API.
---
## 🏗️ How It Works (Pipeline)
## 🔒 Security & Performance
1. **Download/Input**: Gets the source video in high quality.
2. **Transcription (Whisper)**: Converts all audio to text with word-level timestamps.
3. **Analysis (Gemini)**: AI reads the transcript and identifies the 3-15 most interesting segments, returning exact timestamps and metadata.
4. **Extraction**: Selected segments are cut from the original video.
5. **Vertical Conversion**: Each clip goes through the visual detection engine (YOLO) to dynamically reframe the action to 9:16 format.
* **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.
---
## 🤝 Contributions
Contributions are welcome! If you have ideas to improve clip detection or cropping, feel free to open a PR.
Contributions are welcome! Whether it's adding new AI models or improving the cropping engine, feel free to open a PR.
## 📄 License
MIT License. Feel free to use it for your personal or commercial projects.
MIT License. OpenShorts is yours to use, modify, and scale.

2
app.py
View file

@ -23,7 +23,7 @@ os.makedirs(OUTPUT_DIR, exist_ok=True)
# Configuration
# Default to 1 if not set, but user can set higher for powerful servers
MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "1"))
MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "5"))
MAX_FILE_SIZE_MB = 500 # 500 MB limit
JOB_RETENTION_SECONDS = 3600 # 1 hour retention

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal } from 'lucide-react';
import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
@ -9,6 +9,7 @@ import { getApiUrl } from './config';
// Enhanced "Encryption" using XOR + Base64 with a Salt
// This is better than plain Base64 but still client-side.
const SECRET_KEY = import.meta.env.VITE_ENCRYPTION_KEY || "OpenShorts-Secret-Key-2025-V1";
const ENCRYPTION_PREFIX = "ENC:";
const encrypt = (text) => {
if (!text) return '';
@ -16,7 +17,7 @@ const encrypt = (text) => {
const xor = text.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length))
).join('');
return btoa(xor);
return ENCRYPTION_PREFIX + btoa(xor);
} catch (e) {
console.error("Encryption failed", e);
return text;
@ -25,17 +26,23 @@ const encrypt = (text) => {
const decrypt = (text) => {
if (!text) return '';
if (text.startsWith(ENCRYPTION_PREFIX)) {
try {
const raw = text.slice(ENCRYPTION_PREFIX.length);
// Check if it's plain base64 or our custom XOR (simple try)
const xor = atob(text);
const xor = atob(raw);
const result = xor.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length))
).join('');
return result;
} catch (e) {
// Fallback if decryption fails (might be old plain text)
return text;
return '';
}
}
// Backward compatibility: If no prefix, assume old plain text (or return empty if you want to force re-login)
// For migration: Return text as is, so it populates the field, and next save will encrypt it.
return text;
};
// Simple TikTok icon sine Lucide might not have it or it varies
@ -122,7 +129,7 @@ function App() {
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Social API State - Load encrypted or plain
const [uploadPostKey, setUploadPostKey] = useState(() => {
const stored = localStorage.getItem('uploadPostKey_v2'); // Changed key to force re-login or fresh start if needed
const stored = localStorage.getItem('uploadPostKey_v3');
if (stored) return decrypt(stored);
return '';
});
@ -138,12 +145,14 @@ function App() {
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
useEffect(() => {
// Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well.
// For now keeping gemini plain for compatibility unless requested.
if (apiKey) localStorage.setItem('gemini_key', apiKey);
}, [apiKey]);
useEffect(() => {
if (uploadPostKey) {
localStorage.setItem('uploadPostKey_v2', encrypt(uploadPostKey));
localStorage.setItem('uploadPostKey_v3', encrypt(uploadPostKey));
}
if (uploadUserId) {
localStorage.setItem('uploadUserId', uploadUserId);
@ -260,8 +269,8 @@ function App() {
const Sidebar = () => (
<div className="w-20 lg:w-64 bg-surface border-r border-white/5 flex flex-col h-full shrink-0 transition-all duration-300">
<div className="p-6 flex items-center gap-3">
<div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shrink-0">
<Sparkles size={18} className="text-white" />
<div className="w-8 h-8 bg-white/5 rounded-lg flex items-center justify-center shrink-0 overflow-hidden border border-white/5">
<img src="/logo-openshorts.png" alt="Logo" className="w-full h-full object-cover" />
</div>
<span className="font-bold text-lg text-white hidden lg:block tracking-tight">OpenShorts</span>
</div>
@ -350,7 +359,12 @@ function App() {
{/* View: Settings */}
{activeTab === 'settings' && (
<div className="h-full overflow-y-auto p-8 max-w-2xl mx-auto animate-[fadeIn_0.3s_ease-out]">
<h1 className="text-2xl font-bold mb-8">Settings</h1>
<div className="flex items-center justify-between mb-8">
<h1 className="text-2xl font-bold">Settings</h1>
<div className="px-3 py-1 bg-green-500/10 border border-green-500/20 rounded-full text-[10px] text-green-400 font-medium flex items-center gap-2">
<Shield size={12} /> Privacy: keys only live in your browser (sent to backend just to process)
</div>
</div>
<KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className="glass-panel p-6 mt-8">
@ -369,10 +383,26 @@ function App() {
Connect
</button>
</div>
<p className="text-xs text-zinc-500">
<p className="text-xs text-zinc-500 leading-relaxed">
Connect your Upload-Post account to enable one-click publishing.
<div className="mt-3 grid grid-cols-1 sm:grid-cols-3 gap-2">
<a href="https://app.upload-post.com/login" target="_blank" rel="noopener noreferrer" className="p-2 border border-white/5 rounded-lg hover:bg-white/5 transition-colors flex flex-col gap-1">
<span className="text-zinc-400 font-medium">1. Login</span>
<span className="text-[10px] text-zinc-600">Register account</span>
</a>
<a href="https://app.upload-post.com/manage-users" target="_blank" rel="noopener noreferrer" className="p-2 border border-white/5 rounded-lg hover:bg-white/5 transition-colors flex flex-col gap-1">
<span className="text-zinc-400 font-medium">2. Profiles</span>
<span className="text-[10px] text-zinc-600">Create & Connect</span>
</a>
<a href="https://app.upload-post.com/api-keys" target="_blank" rel="noopener noreferrer" className="p-2 border border-white/5 rounded-lg hover:bg-white/5 transition-colors flex flex-col gap-1">
<span className="text-zinc-400 font-medium">3. API Key</span>
<span className="text-[10px] text-zinc-600">Generate key</span>
</a>
</div>
<br />
<span className="text-zinc-600 italic">Key stored encrypted locally.</span>
<span className="text-zinc-600 italic">
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.
</span>
</p>
</div>
</div>
@ -414,8 +444,7 @@ function App() {
<Activity className={`text-primary ${status === 'processing' ? 'animate-pulse' : ''}`} size={20} />
Live Analysis
</h2>
<span className={`text-xs px-2 py-1 rounded-full border ${
status === 'processing' ? 'bg-primary/10 border-primary/20 text-primary' :
<span className={`text-xs px-2 py-1 rounded-full border ${status === 'processing' ? 'bg-primary/10 border-primary/20 text-primary' :
status === 'complete' ? 'bg-green-500/10 border-green-500/20 text-green-400' :
'bg-red-500/10 border-red-500/20 text-red-400'
}`}>

View file

@ -58,6 +58,15 @@ export default function KeyInput({ onKeySet, savedKey }) {
</div>
<p className="mt-3 text-xs text-zinc-500">
Your key is stored locally in your browser for convenience.
<br />
<a
href="https://aistudio.google.com/app/apikey"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline mt-1 inline-block"
>
Get your free Gemini API Key here →
</a>
</p>
</div>
);