Skip to content

AutoShorts is a local-first desktop application for turning long-form video or audio recordings into high-impact, vertical short-form clip candidates (9:16 portrait) with AI-powered viral moment ranking.

Rust

feat: implement local llm support

JayWebtechb0bac590608b
diff --git a/README.md b/README.md
index bbe8215..b30219a 100644
--- a/README.md
+++ b/README.md
@@ -82,10 +82,33 @@ Download the correct package matching your system from the latest [GitHub Releas
./autoshorts_*.AppImage
```
-### 🔑 Configure API Credentials
-Once installed, open the application and click **API Settings** in the top bar:
-1. Paste your API keys for **Deepgram** (transcription) and **Claude** and/or **DeepSeek** (viral candidate moments).
-2. The UI will show a green `(Active)` badge next to your active LLM and notify you if credentials are missing.
+### 🚀 First-Launch Onboarding & AI Configuration
+
+When you first launch the application, you will be greeted by an **Onboarding Wizard** that lets you choose your preferred workflow:
+
+#### Option A: Fully Offline (Ollama + Whisper)
+1. **Ollama Setup**: Select a local model card (`llama3.2 3B`, `qwen2.5 3B`, or `qwen2.5 7B`). The application will check if Ollama is running and automatically pull the model weights, showing a downloader progress bar.
+2. **Local Whisper**: Follow the prompt instructions to verify Python is installed and run `pip3 install openai-whisper` to enable fully offline transcription.
+
+#### Option B: Cloud API Keys
+1. Enter your API credentials for:
+ * **Deepgram**: For fast, accurate cloud transcription.
+ * **DeepSeek**: (Highly Recommended) For cheap, high-quality cloud moment detection.
+ * **Claude**: For premium copywriting, hooks, and moment detection.
+2. Click **Save & Start** to immediately load the dashboard.
+
+---
+
+### ⚙️ Modifying Settings & Resetting Onboarding
+
+* **Update Credentials**: Click the **API Settings** gear icon in the top right of your app dashboard to switch engines, select different local models, or update API keys.
+* **Reset Onboarding**: If you want to switch from Cloud to Offline (or vice-versa) and start setup from scratch, click the **Reset App Configuration & Onboarding** button at the bottom of the API Settings panel.
+
+> [!TIP]
+> **LLM Provider Recommendation (Local vs. Cloud)**:
+> - **Local Models (Ollama)**: While AutoShorts supports fully offline moments analysis via local Ollama models (like LLaMA 3.2 3B or Qwen 2.5 3B/7B), **local models are generally not recommended for viral moment detection**. Smaller 3B/7B models lack the context reasoning and mathematical capabilities needed to evaluate long transcripts and calculate accurate segment timestamps (often outputting fragments that are too short).
+> - **DeepSeek (Highly Recommended)**: We strongly suggest using **DeepSeek** for moment detection. It offers top-tier reasoning capabilities (matching GPT-4/Claude 3.5 Sonnet) at a **fraction of a cent per run** (under $0.001 per transcript). You can get an API key instantly at [platform.deepseek.com](https://platform.deepseek.com).
+> - **Claude (Premium Option)**: Claude 3.5 Sonnet provides the absolute best hooks copywriting and emotional resonance, but is slightly more expensive than DeepSeek (typically $0.01 – $0.05 per run).
---
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 1702b8c..2f8c6c5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -7,7 +7,7 @@ mod transcription;
use std::path::PathBuf;
use anyhow::{anyhow, Context, Result};
-use tauri::Manager;
+use tauri::{Emitter, Manager};
use db::Database;
use models::{
@@ -15,6 +15,14 @@ use models::{
Transcript, TranscriptWord,
};
+#[derive(Clone, serde::Serialize)]
+struct PullProgressPayload {
+ status: String,
+ completed: Option<u64>,
+ total: Option<u64>,
+ percentage: Option<f64>,
+}
+
#[derive(Clone)]
struct AppState {
db: Database,
@@ -22,11 +30,25 @@ struct AppState {
}
#[tauri::command]
-fn environment_status(state: tauri::State<'_, AppState>) -> EnvironmentStatus {
+async fn environment_status(state: tauri::State<'_, AppState>) -> Result<EnvironmentStatus, String> {
let llm_provider = std::env::var("LLM_PROVIDER")
.unwrap_or_else(|_| "deepseek".to_string())
.to_lowercase();
- EnvironmentStatus {
+
+ let has_local_whisper_model = std::process::Command::new("python3")
+ .args(["-c", "import whisper"])
+ .output()
+ .map(|out| out.status.success())
+ .unwrap_or(false);
+
+ let has_ollama = reqwest::Client::new()
+ .get("http://localhost:11434")
+ .timeout(std::time::Duration::from_millis(1000))
+ .send()
+ .await
+ .is_ok();
+
+ Ok(EnvironmentStatus {
data_dir: state.data_dir.to_string_lossy().to_string(),
has_ffmpeg: media::command_exists("ffmpeg"),
has_ffprobe: media::command_exists("ffprobe"),
@@ -34,7 +56,222 @@ fn environment_status(state: tauri::State<'_, AppState>) -> EnvironmentStatus {
has_anthropic_key: std::env::var("ANTHROPIC_API_KEY").is_ok(),
has_deepseek_key: std::env::var("DEEPSEEK_API_KEY").is_ok(),
llm_provider,
+ has_local_whisper_model,
+ has_ollama,
+ })
+}
+
+#[tauri::command]
+async fn pull_ollama_model(
+ app: tauri::AppHandle,
+ model_name: String,
+) -> Result<(), String> {
+ let client = reqwest::Client::new();
+
+ let mut response = client
+ .post("http://localhost:11434/api/pull")
+ .json(&serde_json::json!({
+ "name": model_name,
+ "stream": true,
+ }))
+ .send()
+ .await
+ .map_err(|e| format!("Failed to connect to Ollama: {e}"))?;
+
+ if !response.status().is_success() {
+ let status = response.status();
+ let text = response.text().await.unwrap_or_default();
+ return Err(format!("Ollama pull returned status {status}: {text}"));
}
+
+ let mut buffer = String::new();
+ while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
+ let chunk_str = String::from_utf8_lossy(&chunk);
+ buffer.push_str(&chunk_str);
+
+ // Process lines in buffer
+ while let Some(pos) = buffer.find('\n') {
+ let line = buffer[..pos].trim().to_string();
+ buffer = buffer[pos + 1..].to_string();
+
+ if line.is_empty() {
+ continue;
+ }
+
+ if let Ok(val) = serde_json::from_str::<serde_json::Value>(&line) {
+ if let Some(err_msg) = val.get("error").and_then(|v| v.as_str()) {
+ return Err(err_msg.to_string());
+ }
+
+ let completed = val.get("completed").and_then(|v| v.as_u64());
+ let total = val.get("total").and_then(|v| v.as_u64());
+
+ let mut status = val.get("status")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Downloading...")
+ .to_string();
+
+ if status.starts_with("downloading ") {
+ if let (Some(c), Some(t)) = (completed, total) {
+ let c_mb = c as f64 / 1024.0 / 1024.0;
+ let t_mb = t as f64 / 1024.0 / 1024.0;
+ if t_mb > 100.0 {
+ status = format!("Downloading weights: {:.1} MB / {:.1} MB", c_mb, t_mb);
+ } else {
+ status = format!("Downloading model components: {:.1} MB / {:.1} MB", c_mb, t_mb);
+ }
+ } else {
+ status = "Downloading model components...".to_string();
+ }
+ }
+
+ let percentage = if let (Some(c), Some(t)) = (completed, total) {
+ if t > 0 {
+ Some((c as f64 / t as f64) * 100.0)
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let payload = PullProgressPayload {
+ status,
+ completed,
+ total,
+ percentage,
+ };
+
+ let _ = app.emit("ollama-pull-progress", payload);
+ }
+ }
+ }
+
+ Ok(())
+}
+
+#[tauri::command]
+async fn install_ollama(app: tauri::AppHandle) -> Result<(), String> {
+ let _ = app.emit("ollama-install-status", "Checking if Ollama is already installed...");
+ let launch = std::process::Command::new("open")
+ .args(["-a", "Ollama"])
+ .output();
+
+ if let Ok(out) = launch {
+ if out.status.success() {
+ let _ = app.emit("ollama-install-status", "Ollama is installed. Launching...");
+ for _ in 0..12 {
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ if reqwest::Client::new().get("http://localhost:11434").send().await.is_ok() {
+ let _ = app.emit("ollama-install-status", "Ollama started successfully!");
+ return Ok(());
+ }
+ }
+ }
+ }
+
+ let brew_path = if std::path::Path::new("/opt/homebrew/bin/brew").exists() {
+ Some("/opt/homebrew/bin/brew")
+ } else if std::path::Path::new("/usr/local/bin/brew").exists() {
+ Some("/usr/local/bin/brew")
+ } else {
+ None
+ };
+
+ if let Some(path) = brew_path {
+ let _ = app.emit("ollama-install-status", "Installing Ollama via Homebrew Cask...");
+
+ let output = std::process::Command::new(path)
+ .args(["install", "--cask", "ollama"])
+ .output()
+ .map_err(|e| format!("Failed to run brew command: {e}"))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+ if !stderr.contains("already installed") {
+ return Err(format!("Brew install failed: {}", stderr));
+ }
+ }
+
+ let _ = app.emit("ollama-install-status", "Starting Ollama.app...");
+ let launch = std::process::Command::new("open")
+ .args(["-a", "Ollama"])
+ .output();
+
+ if let Ok(out) = launch {
+ if out.status.success() {
+ for _ in 0..12 {
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ if reqwest::Client::new().get("http://localhost:11434").send().await.is_ok() {
+ let _ = app.emit("ollama-install-status", "Ollama started successfully!");
+ return Ok(());
+ }
+ }
+ }
+ }
+ }
+
+ let _ = app.emit("ollama-install-status", "Downloading Ollama zip from official source...");
+ let temp_dir = std::env::temp_dir();
+ let zip_path = temp_dir.join("Ollama-darwin.zip");
+
+ let response = reqwest::get("https://ollama.com/download/Ollama-darwin.zip")
+ .await
+ .map_err(|e| format!("Failed to download Ollama: {e}"))?;
+
+ let bytes = response.bytes().await.map_err(|e| format!("Failed to read Ollama bytes: {e}"))?;
+ std::fs::write(&zip_path, bytes).map_err(|e| format!("Failed to save Ollama zip: {e}"))?;
+
+ let _ = app.emit("ollama-install-status", "Unzipping Ollama package...");
+ let unzip_output = std::process::Command::new("unzip")
+ .args(["-o", &zip_path.to_string_lossy().to_string(), "-d", &temp_dir.to_string_lossy().to_string()])
+ .output()
+ .map_err(|e| format!("Failed to unzip Ollama: {e}"))?;
+
+ if !unzip_output.status.success() {
+ return Err(format!("Failed to unzip: {}", String::from_utf8_lossy(&unzip_output.stderr)));
+ }
+
+ let _ = app.emit("ollama-install-status", "Installing to Applications folder...");
+ let app_src = temp_dir.join("Ollama.app");
+
+ let mv_output = std::process::Command::new("mv")
+ .args([&app_src.to_string_lossy().to_string(), "/Applications/"])
+ .output()
+ .map_err(|e| format!("Failed to move Ollama to Applications: {e}"))?;
+
+ if !mv_output.status.success() {
+ let user_apps = dirs::home_dir()
+ .ok_or_else(|| "Could not find home directory".to_string())?
+ .join("Applications");
+ std::fs::create_dir_all(&user_apps).map_err(|e| format!("Failed to create ~/Applications: {e}"))?;
+
+ let mv_user_output = std::process::Command::new("mv")
+ .args([&app_src.to_string_lossy().to_string(), &user_apps.to_string_lossy().to_string()])
+ .output()
+ .map_err(|e| format!("Failed to move Ollama to ~/Applications: {e}"))?;
+
+ if !mv_user_output.status.success() {
+ return Err(format!("Failed to install Ollama to Applications folder: {}", String::from_utf8_lossy(&mv_user_output.stderr)));
+ }
+ }
+
+ let _ = app.emit("ollama-install-status", "Starting Ollama...");
+ let launch = std::process::Command::new("open")
+ .args(["-a", "Ollama"])
+ .output();
+
+ if launch.is_ok() {
+ for _ in 0..12 {
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ if reqwest::Client::new().get("http://localhost:11434").send().await.is_ok() {
+ let _ = app.emit("ollama-install-status", "Ollama started successfully!");
+ return Ok(());
+ }
+ }
+ }
+
+ Err("Ollama installed but could not be automatically started. Please open Ollama from your Applications folder.".to_string())
}
#[tauri::command]
@@ -136,7 +373,22 @@ async fn transcribe_project(
.map_err(to_command_error)?
}
"local" => {
- return Err("Local whisper-rs transcription is reserved for the native model integration pass. Use Deepgram for this MVP build.".to_string());
+ let has_python_whisper = std::process::Command::new("python3")
+ .args(["-c", "import whisper"])
+ .output()
+ .map(|out| out.status.success())
+ .unwrap_or(false);
+ if !has_python_whisper {
+ return Err("Python package 'openai-whisper' is not installed. Please run 'pip3 install openai-whisper' in your terminal.".to_string());
+ }
+ let audio_path = media::extract_audio(
+ &project.source_path,
+ &data_dir.join("projects").join(&project_id),
+ )
+ .map_err(to_command_error)?;
+ transcription::transcribe_local(&audio_path.to_string_lossy(), &data_dir.to_string_lossy())
+ .await
+ .map_err(to_command_error)?
}
other => return Err(format!("Unsupported transcription provider: {other}")),
};
@@ -178,6 +430,8 @@ async fn generate_candidates(
state: tauri::State<'_, AppState>,
project_id: String,
api_key: Option<String>,
+ provider: Option<String>,
+ model_name: Option<String>,
_allow_demo: bool,
) -> Result<Vec<Candidate>, String> {
let db = state.db.clone();
@@ -188,11 +442,12 @@ async fn generate_candidates(
let normalized: NormalizedTranscript =
serde_json::from_str(&transcript.raw_json).map_err(to_command_error)?;
- let provider = std::env::var("LLM_PROVIDER")
- .unwrap_or_else(|_| "deepseek".to_string())
+ let active_provider = provider
+ .or_else(|| std::env::var("LLM_PROVIDER").ok())
+ .unwrap_or_else(|| "deepseek".to_string())
.to_lowercase();
- let drafts = match provider.as_str() {
+ let drafts = match active_provider.as_str() {
"claude" => {
let key = api_key
.or_else(|| std::env::var("ANTHROPIC_API_KEY").ok())
@@ -201,6 +456,14 @@ async fn generate_candidates(
.await
.map_err(to_command_error)?
}
+ "local" | "ollama" => {
+ let model = model_name
+ .or_else(|| std::env::var("OLLAMA_MODEL").ok())
+ .unwrap_or_else(|| "llama3.2".to_string());
+ llm::detect_candidates_with_local_llm(&normalized, &model)
+ .await
+ .map_err(to_command_error)?
+ }
_ => {
let key = api_key
.or_else(|| std::env::var("DEEPSEEK_API_KEY").ok())
@@ -376,12 +639,15 @@ pub fn run() {
.app_data_dir()
.context("resolving app data directory")?;
std::fs::create_dir_all(&data_dir).context("creating app data directory")?;
+ std::fs::create_dir_all(data_dir.join("models")).context("creating models directory")?;
let db = Database::open(&data_dir.join("autoshorts.sqlite"))?;
app.manage(AppState { db, data_dir });
Ok(())
})
.invoke_handler(tauri::generate_handler![
environment_status,
+ pull_ollama_model,
+ install_ollama,
create_project_from_path,
list_projects,
get_project_detail,
diff --git a/src-tauri/src/llm.rs b/src-tauri/src/llm.rs
index 6b7b6fb..27907a3 100644
--- a/src-tauri/src/llm.rs
+++ b/src-tauri/src/llm.rs
@@ -4,10 +4,6 @@ use serde_json::json;
use crate::models::{CandidateDraft, NormalizedTranscript, TranscriptSegment};
-#[derive(Debug, Deserialize)]
-struct CandidateEnvelope {
- candidates: Vec<CandidateDraft>,
-}
#[derive(Debug, Deserialize)]
struct AnthropicMessage {
@@ -82,7 +78,12 @@ Avoid rambling setup, context-dependent references, and pure filler. Return up t
.map(|c| c.message.content.clone())
.ok_or_else(|| anyhow!("DeepSeek response did not include choices content"))?;
- parse_candidate_json(&text)
+ let min_duration = if transcript.duration < 60.0 {
+ (transcript.duration * 0.5).max(5.0)
+ } else {
+ 30.0
+ };
+ parse_candidate_json(&text, min_duration)
}
#[derive(Debug, Serialize)]
@@ -140,7 +141,98 @@ Avoid rambling setup, context-dependent references, and pure filler. Return up t
.find_map(|content| content.text)
.ok_or_else(|| anyhow!("Claude response did not include text content"))?;
- parse_candidate_json(&text)
+ let min_duration = if transcript.duration < 60.0 {
+ (transcript.duration * 0.5).max(5.0)
+ } else {
+ 30.0
+ };
+ parse_candidate_json(&text, min_duration)
+}
+
+#[derive(Debug, Deserialize)]
+struct OllamaMessage {
+ content: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct OllamaResponse {
+ message: OllamaMessage,
+}
+
+pub async fn detect_candidates_with_local_llm(
+ transcript: &NormalizedTranscript,
+ model_name: &str,
+) -> Result<Vec<CandidateDraft>> {
+ let segments = compact_segments(&transcript.segments);
+
+ let system_instructions = "You are identifying the most viral moments and strongest short-form clip candidates from a long-form transcript. \
+For each candidate, the clip must be self-contained, starting with an extremely engaging hook within the first 3 seconds (to capture immediate attention on social feeds), \
+30-90 seconds long, and cut at clean sentence/thought boundaries. \
+CRITICAL: Each clip candidate MUST have a duration between 30 and 90 seconds (i.e. 'end' minus 'start' must be between 30.0 and 90.0). \
+Do NOT return short clips of less than 30 seconds. Combine multiple adjacent sentences to build a meaningful segment of 30-90 seconds. \
+Favor highly shareable content: concrete stories, strong opinions, emotional turns, surprising or counter-intuitive claims, clear payoffs, and high-energy/dramatic peaks. \
+Avoid rambling setup, context-dependent references, and pure filler. \
+You MUST identify and return at least 3-5 candidates (up to 10 candidates). Do not return an empty candidates list. \
+Ensure the 'start' and 'end' values correspond to actual timestamps in the transcript. Do not output 0.0 for start and end times.";
+
+ let user_content = format!("Transcript:\n{}", segments);
+
+ let response = reqwest::Client::new()
+ .post("http://localhost:11434/api/chat")
+ .json(&json!({
+ "model": model_name,
+ "messages": [
+ {
+ "role": "system",
+ "content": system_instructions,
+ },
+ {
+ "role": "user",
+ "content": user_content,
+ }
+ ],
+ "stream": false,
+ "options": {
+ "temperature": 0.2
+ },
+ "format": {
+ "type": "object",
+ "properties": {
+ "candidates": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "start": { "type": "number" },
+ "end": { "type": "number" },
+ "score": { "type": "number" },
+ "hook": { "type": "string" },
+ "rationale": { "type": "string" }
+ },
+ "required": ["start", "end", "score", "hook", "rationale"]
+ }
+ }
+ },
+ "required": ["candidates"]
+ }
+ }))
+ .send()
+ .await
+ .context("calling local Ollama")?;
+
+ if !response.status().is_success() {
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ return Err(anyhow!("Local Ollama request failed ({status}): {body}"));
+ }
+
+ let res_body: OllamaResponse = response.json().await.context("parsing local Ollama response")?;
+ let min_duration = if transcript.duration < 60.0 {
+ (transcript.duration * 0.5).max(5.0)
+ } else {
+ 30.0
+ };
+ parse_candidate_json(&res_body.message.content, min_duration)
}
pub fn demo_candidates(transcript: &NormalizedTranscript) -> Vec<CandidateDraft> {
@@ -193,7 +285,7 @@ fn compact_segments(segments: &[TranscriptSegment]) -> String {
.join("\n")
}
-fn parse_candidate_json(text: &str) -> Result<Vec<CandidateDraft>> {
+fn parse_candidate_json(text: &str, min_duration: f64) -> Result<Vec<CandidateDraft>> {
let trimmed = text
.trim()
.trim_start_matches("```json")
@@ -201,20 +293,141 @@ fn parse_candidate_json(text: &str) -> Result<Vec<CandidateDraft>> {
.trim_end_matches("```")
.trim();
- let envelope: CandidateEnvelope =
- serde_json::from_str(trimmed).context("parsing candidate JSON")?;
+ let val: serde_json::Value = serde_json::from_str(trimmed).context("parsing candidate JSON")?;
+
+ let candidates_arr = if val.is_array() {
+ val.as_array().cloned()
+ } else if val.is_object() {
+ let mut found_arr = None;
+ for key in &["candidates", "Candidates", "moments", "clips", "segments", "results"] {
+ if let Some(arr) = val.get(*key).and_then(|v| v.as_array()) {
+ found_arr = Some(arr.clone());
+ break;
+ }
+ }
+ if found_arr.is_none() {
+ if let Some(obj) = val.as_object() {
+ for (_key, value) in obj {
+ if let Some(arr) = value.as_array() {
+ found_arr = Some(arr.clone());
+ break;
+ }
+ }
+ }
+ }
+ if found_arr.is_some() {
+ found_arr
+ } else if val.get("start").is_some() && val.get("end").is_some() {
+ Some(vec![val.clone()])
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let concrete_arr = candidates_arr.ok_or_else(|| {
+ anyhow!(
+ "Ollama output does not contain a candidates array. Raw output: {}",
+ trimmed
+ )
+ })?;
+
+ let mut drafts = Vec::new();
+ for item in &concrete_arr {
+ let start = match item.get("start") {
+ Some(v) => {
+ if let Some(f) = v.as_f64() {
+ f
+ } else if let Some(s) = v.as_str() {
+ s.parse::<f64>().unwrap_or(0.0)
+ } else if let Some(i) = v.as_i64() {
+ i as f64
+ } else {
+ 0.0
+ }
+ }
+ None => 0.0,
+ };
+
+ let end = match item.get("end") {
+ Some(v) => {
+ if let Some(f) = v.as_f64() {
+ f
+ } else if let Some(s) = v.as_str() {
+ s.parse::<f64>().unwrap_or(0.0)
+ } else if let Some(i) = v.as_i64() {
+ i as f64
+ } else {
+ 0.0
+ }
+ }
+ None => 0.0,
+ };
+
+ let mut score = match item.get("score") {
+ Some(v) => {
+ if let Some(f) = v.as_f64() {
+ f
+ } else if let Some(s) = v.as_str() {
+ s.parse::<f64>().unwrap_or(0.8)
+ } else if let Some(i) = v.as_i64() {
+ i as f64
+ } else {
+ 0.8
+ }
+ }
+ None => 0.8,
+ };
+
+ if score > 1.0 && score <= 10.0 {
+ score /= 10.0;
+ } else if score > 10.0 && score <= 100.0 {
+ score /= 100.0;
+ } else if score > 100.0 {
+ score = 1.0;
+ } else if score < 0.0 {
+ score = 0.0;
+ }
- let mut candidates = envelope
- .candidates
+ let hook = item.get("hook")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let rationale = item.get("rationale")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ drafts.push(CandidateDraft {
+ start,
+ end,
+ score,
+ hook,
+ rationale,
+ });
+ }
+
+ let mut candidates = drafts
+ .clone()
.into_iter()
.filter(|candidate| {
- candidate.end > candidate.start
- && candidate.score >= 0.0
- && candidate.score <= 1.0
+ (candidate.end - candidate.start) >= min_duration
&& !candidate.hook.trim().is_empty()
})
.collect::<Vec<_>>();
+ if candidates.is_empty() {
+ candidates = drafts
+ .into_iter()
+ .filter(|candidate| {
+ (candidate.end - candidate.start) >= 5.0
+ && !candidate.hook.trim().is_empty()
+ })
+ .collect::<Vec<_>>();
+ }
+
candidates.sort_by(|a, b| b.score.total_cmp(&a.score));
candidates.truncate(10);
Ok(candidates)
diff --git a/src-tauri/src/models.rs b/src-tauri/src/models.rs
index c4e2fd0..c6c1e46 100644
--- a/src-tauri/src/models.rs
+++ b/src-tauri/src/models.rs
@@ -10,6 +10,8 @@ pub struct EnvironmentStatus {
pub has_anthropic_key: bool,
pub has_deepseek_key: bool,
pub llm_provider: String,
+ pub has_local_whisper_model: bool,
+ pub has_ollama: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/src-tauri/src/transcription.rs b/src-tauri/src/transcription.rs
index acf6e70..980a3af 100644
--- a/src-tauri/src/transcription.rs
+++ b/src-tauri/src/transcription.rs
@@ -136,3 +136,98 @@ pub fn build_segments(words: &[TranscriptWord]) -> Vec<TranscriptSegment> {
segments
}
+
+pub async fn transcribe_local(audio_path: &str, model_path: &str) -> Result<NormalizedTranscript> {
+ let audio_path = audio_path.to_string();
+ let model_path = model_path.to_string();
+
+ // Resolve the directory where the model lives. We'll put transcribe.py there.
+ let model_dir = std::path::Path::new(&model_path)
+ .parent()
+ .ok_or_else(|| anyhow!("Invalid model path"))?;
+
+ let script_path = model_dir.join("transcribe.py");
+ if !script_path.exists() {
+ let script_content = r#"import sys
+import json
+import whisper
+
+def main():
+ if len(sys.argv) < 3:
+ print("Usage: transcribe.py <audio_path> <output_json_path> [model_name]")
+ sys.exit(1)
+
+ audio_path = sys.argv[1]
+ output_json_path = sys.argv[2]
+ model_name = sys.argv[3] if len(sys.argv) > 3 else "base"
+
+ # Load model. Automatically uses MPS on Apple Silicon if PyTorch supports it.
+ model = whisper.load_model(model_name)
+
+ # Transcribe with word-level timestamps
+ result = model.transcribe(audio_path, word_timestamps=True)
+
+ normalized = {
+ "language": result.get("language", "en"),
+ "duration": result.get("segments", [])[-1]["end"] if result.get("segments") else 0.0,
+ "speakers": ["S1"],
+ "words": [],
+ "segments": []
+ }
+
+ for segment in result.get("segments", []):
+ normalized["segments"].append({
+ "start": segment["start"],
+ "end": segment["end"],
+ "speaker": "S1",
+ "text": segment["text"].strip()
+ })
+
+ for word in segment.get("words", []):
+ cleaned_text = word["word"].strip()
+ normalized["words"].append({
+ "text": cleaned_text,
+ "start": word["start"],
+ "end": word["end"],
+ "speaker": "S1"
+ })
+
+ with open(output_json_path, "w", encoding="utf-8") as f:
+ json.dump(normalized, f, indent=2, ensure_ascii=False)
+
+if __name__ == "__main__":
+ main()
+"#;
+ std::fs::write(&script_path, script_content).context("writing transcribe.py script")?;
+ }
+
+ let output_json_path = model_dir.join(format!("temp_transcript_{}.json", uuid::Uuid::new_v4()));
+ let script_path_str = script_path.to_string_lossy().to_string();
+ let output_json_path_str = output_json_path.to_string_lossy().to_string();
+
+ tokio::task::spawn_blocking(move || {
+ let output = std::process::Command::new("python3")
+ .arg(&script_path_str)
+ .arg(&audio_path)
+ .arg(&output_json_path_str)
+ .arg("base") // default model size
+ .output()
+ .context("executing python3 transcribe.py")?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+ let stdout = String::from_utf8_lossy(&output.stdout).to_string();
+ return Err(anyhow!("Python transcription script failed:\nStderr: {}\nStdout: {}", stderr, stdout));
+ }
+
+ let json_bytes = std::fs::read(&output_json_path_str).context("reading output transcript JSON")?;
+ let transcript: NormalizedTranscript = serde_json::from_slice(&json_bytes).context("parsing output transcript JSON")?;
+
+ // Cleanup temp file
+ let _ = std::fs::remove_file(&output_json_path_str);
+
+ Ok(transcript)
+ })
+ .await
+ .context("spawn_blocking failed")?
+}
diff --git a/src/main.tsx b/src/main.tsx
index 12c8ab0..4e25abe 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -2,6 +2,7 @@ import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
+import { listen } from "@tauri-apps/api/event";
import {
AudioLines,
BadgeCheck,
@@ -18,6 +19,9 @@ import {
SlidersHorizontal,
Sparkles,
Wand2,
+ Copy,
+ Database,
+ Cloud,
} from "lucide-react";
import "./styles.css";
@@ -29,6 +33,8 @@ type EnvironmentStatus = {
hasAnthropicKey: boolean;
hasDeepseekKey: boolean;
llmProvider: string;
+ hasLocalWhisperModel: boolean;
+ hasOllama: boolean;
};
type Project = {
@@ -108,15 +114,37 @@ function App() {
const [detail, setDetail] = useState<ProjectDetail | null>(null);
const [busy, setBusy] = useState<BusyState>("idle");
const [error, setError] = useState<string | null>(null);
- const [deepgramKey, setDeepgramKey] = useState("");
- const [anthropicKey, setAnthropicKey] = useState("");
- const [deepseekKey, setDeepseekKey] = useState("");
const [showSettings, setShowSettings] = useState(false);
const [renderingCandidateId, setRenderingCandidateId] = useState<string | null>(null);
const [showStyleModal, setShowStyleModal] = useState(false);
const [selectedStyle, setSelectedStyle] = useState("modern-box");
const [mediaPathToImport, setMediaPathToImport] = useState<string | null>(null);
+ // Persistence logic from localStorage
+ const [isOnboarded, setIsOnboarded] = useState<boolean | null>(null);
+ const [transcriptionEngine, setTranscriptionEngine] = useState<"deepgram" | "local">(() => {
+ return (localStorage.getItem("autoshorts_transcription_engine") as "deepgram" | "local") || "local";
+ });
+ const [llmEngine, setLlmEngine] = useState<"claude" | "deepseek" | "local">(() => {
+ return (localStorage.getItem("autoshorts_llm_engine") as "claude" | "deepseek" | "local") || "local";
+ });
+ const [localLlmModel, setLocalLlmModel] = useState(() => {
+ return localStorage.getItem("autoshorts_local_llm_model") || "llama3.2";
+ });
+ const [deepgramKey, setDeepgramKey] = useState(() => {
+ return localStorage.getItem("autoshorts_deepgram_key") || "";
+ });
+ const [anthropicKey, setAnthropicKey] = useState(() => {
+ return localStorage.getItem("autoshorts_anthropic_key") || "";
+ });
+ const [deepseekKey, setDeepseekKey] = useState(() => {
+ return localStorage.getItem("autoshorts_deepseek_key") || "";
+ });
+
+ const [downloadingModelName, setDownloadingModelName] = useState<string | null>(null);
+ const [modelDownloadStatus, setModelDownloadStatus] = useState("");
+ const [modelDownloadProgress, setModelDownloadProgress] = useState(0);
+
const transcript = useMemo(() => {
if (!detail?.transcript) return null;
try {
@@ -143,13 +171,77 @@ function App() {
const canUseClaude = environment?.hasAnthropicKey || anthropicKey.trim().length > 0;
const canUseDeepseek = environment?.hasDeepseekKey || deepseekKey.trim().length > 0;
- const activeLlmProvider = environment?.llmProvider || "deepseek";
- const canUseActiveLlm = activeLlmProvider === "claude" ? canUseClaude : canUseDeepseek;
+ const canTranscribe = transcriptionEngine === "local"
+ ? Boolean(environment?.hasLocalWhisperModel)
+ : canUseCloudKey;
+
+ const canUseActiveLlm = llmEngine === "local"
+ ? Boolean(environment?.hasOllama)
+ : (llmEngine === "claude" ? canUseClaude : canUseDeepseek);
useEffect(() => {
void refresh();
+ const value = localStorage.getItem("autoshorts_onboarded");
+ if (value === "true") {
+ setIsOnboarded(true);
+ } else {
+ setIsOnboarded(false);
+ }
}, []);
+ useEffect(() => {
+ localStorage.setItem("autoshorts_transcription_engine", transcriptionEngine);
+ }, [transcriptionEngine]);
+
+ useEffect(() => {
+ localStorage.setItem("autoshorts_llm_engine", llmEngine);
+ }, [llmEngine]);
+
+ useEffect(() => {
+ localStorage.setItem("autoshorts_local_llm_model", localLlmModel);
+ }, [localLlmModel]);
+
+ useEffect(() => {
+ localStorage.setItem("autoshorts_deepgram_key", deepgramKey);
+ }, [deepgramKey]);
+
+ useEffect(() => {
+ localStorage.setItem("autoshorts_anthropic_key", anthropicKey);
+ }, [anthropicKey]);
+
+ useEffect(() => {
+ localStorage.setItem("autoshorts_deepseek_key", deepseekKey);
+ }, [deepseekKey]);
+
+ const pullModelDirectly = async (modelName: string) => {
+ setDownloadingModelName(modelName);
+ setModelDownloadProgress(0);
+ setModelDownloadStatus("Connecting to Ollama...");
+ try {
+ const unlisten = await listen<{
+ status: string;
+ completed?: number;
+ total?: number;
+ percentage?: number;
+ }>("ollama-pull-progress", (event) => {
+ const payload = event.payload;
+ setModelDownloadStatus(payload.status);
+ if (payload.percentage !== undefined && payload.percentage !== null) {
+ setModelDownloadProgress(Math.round(payload.percentage));
+ }
+ });
+
+ await invoke("pull_ollama_model", { modelName });
+ unlisten();
+ setModelDownloadStatus("Download complete!");
+ setModelDownloadProgress(100);
+ setTimeout(() => setDownloadingModelName(null), 500);
+ } catch (err) {
+ alert("Failed to download model: " + String(err));
+ setDownloadingModelName(null);
+ }
+ };
+
async function refresh(nextProjectId?: string) {
setError(null);
const [env, projectList] = await Promise.all([
@@ -204,7 +296,7 @@ function App() {
await run("import", async () => {
const project = await invoke<Project>("create_project_from_path", {
path: selected,
- transcriptionMode: "cloud",
+ transcriptionMode: transcriptionEngine === "local" ? "local" : "cloud",
captionStyle: style,
});
newProjectId = project.id;
@@ -219,15 +311,34 @@ function App() {
async function runAutoPipeline(projectId: string) {
setError(null);
const env = await invoke<EnvironmentStatus>("environment_status");
- const hasDG = env.hasDeepgramKey || deepgramKey.trim().length > 0;
- const activeLlm = env.llmProvider || "deepseek";
- const hasActiveLlm = activeLlm === "claude"
- ? (env.hasAnthropicKey || anthropicKey.trim().length > 0)
- : (env.hasDeepseekKey || deepseekKey.trim().length > 0);
-
- if (!hasDG) {
- setError("Import successful. Deepgram key is missing. Please add it to start transcription.");
- return;
+
+ if (transcriptionEngine === "local") {
+ if (!env.hasLocalWhisperModel) {
+ setError("Import successful. Local Whisper GGML model (ggml-base.bin) is missing in your models directory. Please add it to start transcription.");
+ return;
+ }
+ } else {
+ const hasDG = env.hasDeepgramKey || deepgramKey.trim().length > 0;
+ if (!hasDG) {
+ setError("Import successful. Deepgram key is missing. Please add it to start transcription.");
+ return;
+ }
+ }
+
+ if (llmEngine === "local") {
+ if (!env.hasOllama) {
+ setError("Import successful. Local Ollama server is not running at http://localhost:11434. Please start it to find viral moments.");
+ return;
+ }
+ } else {
+ const activeKey = llmEngine === "claude" ? anthropicKey : deepseekKey;
+ const hasActiveKey = llmEngine === "claude"
+ ? (env.hasAnthropicKey || activeKey.trim().length > 0)
+ : (env.hasDeepseekKey || activeKey.trim().length > 0);
+ if (!hasActiveKey) {
+ setError(`Transcription complete. ${llmEngine === "claude" ? "Claude" : "DeepSeek"} API Key is missing. Please add it in settings to analyze viral moments.`);
+ return;
+ }
}
// 1. Transcription
@@ -235,8 +346,8 @@ function App() {
setBusy("transcribe");
await invoke<Transcript>("transcribe_project", {
projectId,
- provider: "deepgram",
- apiKey: deepgramKey.trim() || null,
+ provider: transcriptionEngine,
+ apiKey: transcriptionEngine === "deepgram" ? (deepgramKey.trim() || null) : null,
});
await refresh(projectId);
} catch (err) {
@@ -245,23 +356,30 @@ function App() {
return;
}
- if (!hasActiveLlm) {
- setError(`Transcription complete. ${activeLlm === "claude" ? "Claude" : "DeepSeek"} API Key is missing. Please add it in settings to analyze viral moments.`);
- setBusy("idle");
- return;
- }
-
// 2. LLM Moments
try {
setBusy("moments");
- const activeKey = activeLlm === "claude" ? anthropicKey.trim() : deepseekKey.trim();
+ const activeKey = llmEngine === "claude" ? anthropicKey.trim() : (llmEngine === "deepseek" ? deepseekKey.trim() : "");
await invoke<Candidate[]>("generate_candidates", {
projectId,
apiKey: activeKey || null,
+ provider: llmEngine,
+ modelName: llmEngine === "local" ? localLlmModel.trim() : null,
allowDemo: false,
});
await refresh(projectId);
} catch (err) {
+ const errMsg = String(err);
+ if (llmEngine === "local" && (errMsg.includes("not found") || errMsg.includes("404"))) {
+ if (window.confirm(`Ollama model "${localLlmModel}" is not downloaded. Would you like to download it now?`)) {
+ setTimeout(() => {
+ void pullModelDirectly(localLlmModel).then(() => {
+ void refresh(projectId);
+ });
+ }, 100);
+ return;
+ }
+ }
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy("idle");
@@ -312,8 +430,8 @@ function App() {
await run("transcribe", async () => {
await invoke<Transcript>("transcribe_project", {
projectId: detail.project.id,
- provider: "deepgram",
- apiKey: deepgramKey.trim() || null,
+ provider: transcriptionEngine,
+ apiKey: transcriptionEngine === "deepgram" ? (deepgramKey.trim() || null) : null,
});
await refresh(detail.project.id);
});
@@ -322,13 +440,30 @@ function App() {
async function moments(allowDemo: boolean) {
if (!detail) return;
await run("moments", async () => {
- const activeKey = activeLlmProvider === "claude" ? anthropicKey.trim() : deepseekKey.trim();
- await invoke<Candidate[]>("generate_candidates", {
- projectId: detail.project.id,
- apiKey: activeKey || null,
- allowDemo,
- });
- await refresh(detail.project.id);
+ const activeKey = llmEngine === "claude" ? anthropicKey.trim() : (llmEngine === "deepseek" ? deepseekKey.trim() : "");
+ try {
+ await invoke<Candidate[]>("generate_candidates", {
+ projectId: detail.project.id,
+ apiKey: activeKey || null,
+ provider: llmEngine,
+ modelName: llmEngine === "local" ? localLlmModel.trim() : null,
+ allowDemo,
+ });
+ await refresh(detail.project.id);
+ } catch (err) {
+ const errMsg = String(err);
+ if (llmEngine === "local" && (errMsg.includes("not found") || errMsg.includes("404"))) {
+ if (window.confirm(`Ollama model "${localLlmModel}" is not downloaded. Would you like to download it now?`)) {
+ setTimeout(() => {
+ void pullModelDirectly(localLlmModel).then(() => {
+ void refresh(detail.project.id);
+ });
+ }, 100);
+ return;
+ }
+ }
+ throw err;
+ }
});
}
@@ -377,6 +512,33 @@ function App() {
}
}
+ if (isOnboarded === null) {
+ return (
+ <div className="onboarding-loading" style={{ display: 'grid', placeItems: 'center', height: '100vh', background: 'var(--bg-base)' }}>
+ <Loader2 className="spin" size={32} color="var(--accent-primary)" />
+ </div>
+ );
+ }
+
+ if (isOnboarded === false) {
+ return (
+ <Onboarding
+ environment={environment}
+ onComplete={() => setIsOnboarded(true)}
+ setTranscriptionEngine={setTranscriptionEngine}
+ setLlmEngine={setLlmEngine}
+ setLocalLlmModel={setLocalLlmModel}
+ setDeepgramKey={setDeepgramKey}
+ setAnthropicKey={setAnthropicKey}
+ setDeepseekKey={setDeepseekKey}
+ deepgramKey={deepgramKey}
+ anthropicKey={anthropicKey}
+ deepseekKey={deepseekKey}
+ refreshEnv={() => refresh()}
+ />
+ );
+ }
+
return (
<div className="app-shell-container">
<main className="app-shell">
@@ -452,36 +614,95 @@ function App() {
<div className="settings-panel">
<div className="key-stack-horizontal">
<label>
- <span>Deepgram API Key</span>
- <input
- value={deepgramKey}
- onChange={(event) => setDeepgramKey(event.target.value)}
- placeholder={environment?.hasDeepgramKey ? "Loaded from env" : "Optional (Deepgram API Key)"}
- type="password"
- />
+ <span>Transcription Engine</span>
+ <select
+ value={transcriptionEngine}
+ onChange={(event) => setTranscriptionEngine(event.target.value as "deepgram" | "local")}
+ >
+ <option value="local">Local Whisper (Offline)</option>
+ <option value="deepgram">Deepgram (Cloud)</option>
+ </select>
</label>
<label>
- <span>
- Claude API Key {activeLlmProvider === "claude" && <strong style={{ color: "var(--accent-primary)" }}>(Active)</strong>}
- </span>
- <input
- value={anthropicKey}
- onChange={(event) => setAnthropicKey(event.target.value)}
- placeholder={environment?.hasAnthropicKey ? "Loaded from env" : "Optional (Claude API Key)"}
- type="password"
- />
- </label>
- <label>
- <span>
- DeepSeek API Key {activeLlmProvider === "deepseek" && <strong style={{ color: "var(--accent-primary)" }}>(Active)</strong>}
- </span>
- <input
- value={deepseekKey}
- onChange={(event) => setDeepseekKey(event.target.value)}
- placeholder={environment?.hasDeepseekKey ? "Loaded from env" : "Optional (DeepSeek API Key)"}
- type="password"
- />
+ <span>LLM Engine</span>
+ <select
+ value={llmEngine}
+ onChange={(event) => setLlmEngine(event.target.value as "claude" | "deepseek" | "local")}
+ >
+ <option value="local">Ollama (Offline Local)</option>
+ <option value="claude">Claude (Cloud)</option>
+ <option value="deepseek">DeepSeek (Cloud)</option>
+ </select>
</label>
+ {transcriptionEngine === "deepgram" && (
+ <label>
+ <span>Deepgram API Key</span>
+ <input
+ value={deepgramKey}
+ onChange={(event) => setDeepgramKey(event.target.value)}
+ placeholder={environment?.hasDeepgramKey ? "Loaded from env" : "Optional (Deepgram API Key)"}
+ type="password"
+ />
+ </label>
+ )}
+ {llmEngine === "claude" && (
+ <label>
+ <span>Claude API Key</span>
+ <input
+ value={anthropicKey}
+ onChange={(event) => setAnthropicKey(event.target.value)}
+ placeholder={environment?.hasAnthropicKey ? "Loaded from env" : "Optional (Claude API Key)"}
+ type="password"
+ />
+ </label>
+ )}
+ {llmEngine === "deepseek" && (
+ <label>
+ <span>DeepSeek API Key</span>
+ <input
+ value={deepseekKey}
+ onChange={(event) => setDeepseekKey(event.target.value)}
+ placeholder={environment?.hasDeepseekKey ? "Loaded from env" : "Optional (DeepSeek API Key)"}
+ type="password"
+ />
+ </label>
+ )}
+ {llmEngine === "local" && (
+ <label>
+ <span>Ollama Model Name</span>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <input
+ value={localLlmModel}
+ onChange={(event) => setLocalLlmModel(event.target.value)}
+ placeholder="e.g. llama3.2, qwen2.5:7b"
+ type="text"
+ />
+ <button
+ type="button"
+ className="icon-button"
+ style={{ minHeight: '36px', height: '36px' }}
+ onClick={() => pullModelDirectly(localLlmModel)}
+ >
+ <Download size={14} /> Pull
+ </button>
+ </div>
+ </label>
+ )}
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '16px', borderTop: '1px solid var(--border-color)', paddingTop: '16px' }}>
+ <button
+ type="button"
+ className="icon-button"
+ style={{ background: 'rgba(239, 68, 68, 0.08)', borderColor: 'rgba(239, 68, 68, 0.2)', color: '#f87171' }}
+ onClick={() => {
+ if (window.confirm("Are you sure you want to reset your configuration and restart onboarding from scratch?")) {
+ localStorage.clear();
+ window.location.reload();
+ }
+ }}
+ >
+ Reset App Configuration & Onboarding
+ </button>
</div>
</div>
)}
@@ -504,16 +725,18 @@ function App() {
<p>{transcript ? `${transcript.segments.length} segments` : "No transcript"}</p>
</div>
<div className="button-pair">
- <button onClick={transcribe} disabled={busy !== "idle" || !canUseCloudKey}>
+ <button onClick={transcribe} disabled={busy !== "idle" || !canTranscribe}>
{busy === "transcribe" ? <Loader2 className="spin" size={16} /> : <AudioLines size={16} />}
Transcribe
</button>
</div>
</div>
- {!canUseCloudKey && (
+ {!canTranscribe && (
<div className="api-warning">
- ⚠️ Deepgram API Key is missing. Transcribing will not work. Please add your key in <strong>API Settings</strong>.
+ {transcriptionEngine === "local"
+ ? `⚠️ Local Whisper (Python package 'openai-whisper') is not installed. Run 'pip3 install openai-whisper' in your terminal.`
+ : "⚠️ Deepgram API Key is missing. Transcribing will not work. Please add your key in API Settings."}
</div>
)}
@@ -547,7 +770,9 @@ function App() {
{!canUseActiveLlm && (
<div className="api-warning">
- ⚠️ {activeLlmProvider === "claude" ? "Claude" : "DeepSeek"} API Key is missing. Viral moment identification will not work. Please add your key in <strong>API Settings</strong>.
+ {llmEngine === "local"
+ ? "⚠️ Ollama local server is not running at http://localhost:11434. Moment detection will not work."
+ : `⚠️ ${llmEngine === "claude" ? "Claude" : "DeepSeek"} API Key is missing. Viral moment identification will not work. Please add your key in API Settings.`}
</div>
)}
@@ -694,6 +919,8 @@ function App() {
<div className="status-indicators">
<span className={`indicator ${environment?.hasFfmpeg ? "active" : ""}`} title="FFmpeg status">ffmpeg</span>
<span className={`indicator ${environment?.hasFfprobe ? "active" : ""}`} title="FFprobe status">ffprobe</span>
+ <span className={`indicator ${environment?.hasLocalWhisperModel ? "active" : ""}`} title="Whisper Model status">Whisper Model</span>
+ <span className={`indicator ${environment?.hasOllama ? "active" : ""}`} title="Ollama status">Ollama</span>
<span className={`indicator ${canUseCloudKey ? "active" : ""}`} title="Deepgram Key status">Deepgram</span>
<span className={`indicator ${canUseClaude ? "active" : ""}`} title="Claude Key status">Claude</span>
<span className={`indicator ${canUseDeepseek ? "active" : ""}`} title="DeepSeek Key status">DeepSeek</span>
@@ -799,6 +1026,31 @@ function App() {
</div>
</div>
)}
+ {downloadingModelName && (
+ <div className="onboarding-overlay" style={{ zIndex: 20000 }}>
+ <div className="onboarding-card" style={{ maxWidth: '480px', textAlign: 'center' }}>
+ <div className="onboarding-header compact" style={{ textAlign: 'center' }}>
+ <h2>Downloading Ollama Model</h2>
+ <p>Downloading model weights for "{downloadingModelName}". Please do not close the app.</p>
+ </div>
+
+ <div className="download-progress-container">
+ <div className="download-loader">
+ <Loader2 className="spin" size={48} />
+ </div>
+
+ <div className="progress-bar-container">
+ <div className="progress-bar-fill" style={{ width: `${modelDownloadProgress}%` }}></div>
+ </div>
+
+ <div className="download-stats">
+ <span className="download-status">{modelDownloadStatus}</span>
+ <span className="download-percentage">{modelDownloadProgress}%</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
</div>
);
}
@@ -840,6 +1092,363 @@ function formatTime(seconds: number) {
return `${minutes}:${remaining.toString().padStart(2, "0")}`;
}
+interface OnboardingProps {
+ environment: EnvironmentStatus | null;
+ onComplete: () => void;
+ setTranscriptionEngine: (engine: "deepgram" | "local") => void;
+ setLlmEngine: (engine: "claude" | "deepseek" | "local") => void;
+ setLocalLlmModel: (model: string) => void;
+ setDeepgramKey: (key: string) => void;
+ setAnthropicKey: (key: string) => void;
+ setDeepseekKey: (key: string) => void;
+ deepgramKey: string;
+ anthropicKey: string;
+ deepseekKey: string;
+ refreshEnv: () => Promise<void>;
+}
+
+function Onboarding({
+ environment,
+ onComplete,
+ setTranscriptionEngine,
+ setLlmEngine,
+ setLocalLlmModel,
+ setDeepgramKey,
+ setAnthropicKey,
+ setDeepseekKey,
+ deepgramKey: initialDeepgramKey,
+ anthropicKey: initialAnthropicKey,
+ deepseekKey: initialDeepseekKey,
+ refreshEnv,
+}: OnboardingProps) {
+ const [setupMode, setSetupMode] = useState<"choose" | "local" | "cloud" | "downloading">("choose");
+ const [selectedModel, setSelectedModel] = useState<string>("llama3.2");
+
+ const [dgKey, setDgKey] = useState(initialDeepgramKey);
+ const [antKey, setAntKey] = useState(initialAnthropicKey);
+ const [dsKey, setDsKey] = useState(initialDeepseekKey);
+
+ const [downloadStatus, setDownloadStatus] = useState("Initializing download...");
+ const [downloadProgress, setDownloadProgress] = useState(0);
+ const [error, setError] = useState<string | null>(null);
+ const [checkingOllama, setCheckingOllama] = useState(false);
+ const [copied, setCopied] = useState(false);
+
+ const copyWhisperCommand = () => {
+ navigator.clipboard.writeText("pip3 install -U openai-whisper");
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ const handleCloudSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!dgKey.trim()) {
+ setError("Deepgram API Key is required for cloud mode.");
+ return;
+ }
+ if (!antKey.trim() && !dsKey.trim()) {
+ setError("Please provide at least one LLM Key (Claude or DeepSeek).");
+ return;
+ }
+
+ setTranscriptionEngine("deepgram");
+ setDeepgramKey(dgKey.trim());
+ localStorage.setItem("autoshorts_deepgram_key", dgKey.trim());
+ localStorage.setItem("autoshorts_transcription_engine", "deepgram");
+
+ if (antKey.trim()) {
+ setLlmEngine("claude");
+ setAnthropicKey(antKey.trim());
+ localStorage.setItem("autoshorts_anthropic_key", antKey.trim());
+ localStorage.setItem("autoshorts_llm_engine", "claude");
+ } else if (dsKey.trim()) {
+ setLlmEngine("deepseek");
+ setDeepseekKey(dsKey.trim());
+ localStorage.setItem("autoshorts_deepseek_key", dsKey.trim());
+ localStorage.setItem("autoshorts_llm_engine", "deepseek");
+ }
+
+ localStorage.setItem("autoshorts_onboarded", "true");
+ onComplete();
+ };
+
+ const startLocalSetup = async () => {
+ setError(null);
+ setCheckingOllama(true);
+ setDownloadProgress(0);
+
+ await refreshEnv();
+
+ let isOllamaRunning = false;
+ try {
+ const currentEnv = await invoke<EnvironmentStatus>("environment_status");
+ isOllamaRunning = currentEnv.hasOllama;
+ } catch (e) {
+ // ignore
+ }
+
+ setCheckingOllama(false);
+
+ if (!isOllamaRunning) {
+ setSetupMode("downloading");
+ setDownloadStatus("Ollama not found. Starting automatic installer...");
+
+ try {
+ const unlistenInstall = await listen<string>("ollama-install-status", (event) => {
+ setDownloadStatus(event.payload);
+ });
+
+ await invoke("install_ollama");
+ unlistenInstall();
+ } catch (err) {
+ setError("Automatic installation failed: " + String(err) + ". Please install it manually from ollama.com.");
+ setSetupMode("local");
+ return;
+ }
+ }
+
+ setSetupMode("downloading");
+ setDownloadStatus("Ollama connected. Initiating model download...");
+
+ try {
+ const unlisten = await listen<{
+ status: string;
+ completed?: number;
+ total?: number;
+ percentage?: number;
+ }>("ollama-pull-progress", (event) => {
+ const payload = event.payload;
+ setDownloadStatus(payload.status);
+ if (payload.percentage !== undefined && payload.percentage !== null) {
+ setDownloadProgress(Math.round(payload.percentage));
+ }
+ });
+
+ await invoke("pull_ollama_model", { modelName: selectedModel });
+
+ unlisten();
+
+ setTranscriptionEngine("local");
+ setLlmEngine("local");
+ setLocalLlmModel(selectedModel);
+
+ localStorage.setItem("autoshorts_transcription_engine", "local");
+ localStorage.setItem("autoshorts_llm_engine", "local");
+ localStorage.setItem("autoshorts_local_llm_model", selectedModel);
+ localStorage.setItem("autoshorts_onboarded", "true");
+
+ onComplete();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ setSetupMode("local");
+ }
+ };
+
+ return (
+ <div className="onboarding-overlay">
+ <div className="onboarding-card">
+ {setupMode === "choose" && (
+ <>
+ <div className="onboarding-header">
+ <div className="brand-mark large">
+ <Clapperboard size={36} />
+ </div>
+ <h2>Welcome to AutoShorts</h2>
+ <p>Long recording in. Short clips out. Select how you would like to run the studio.</p>
+ </div>
+
+ <div className="onboarding-choices">
+ <div className="choice-card clickable" onClick={() => setSetupMode("local")}>
+ <div className="choice-icon">
+ <Database size={28} />
+ </div>
+ <h3>Fully Offline & Private</h3>
+ <p>Process everything locally on your computer. Private, secure, and completely free.</p>
+ <div className="choice-badge local">Offline (Ollama)</div>
+ </div>
+
+ <div className="choice-card clickable" onClick={() => setSetupMode("cloud")}>
+ <div className="choice-icon">
+ <Cloud size={28} />
+ </div>
+ <h3>Cloud APIs</h3>
+ <p>Use high-speed cloud services for transcription and analysis. No local GPU needed.</p>
+ <div className="choice-badge cloud">API Keys Required</div>
+ </div>
+ </div>
+ </>
+ )}
+
+ {setupMode === "local" && (
+ <div className="local-setup-flow">
+ <div className="onboarding-header compact">
+ <h2>Configure Offline Mode</h2>
+ <p>Follow these steps to set up your local studio.</p>
+ </div>
+
+ {error && <div className="error-banner" style={{ marginBottom: "16px" }}>{error}</div>}
+
+ <div className="setup-steps">
+ <div className="setup-step">
+ <div className="step-num">1</div>
+ <div className="step-body">
+ <h4>Install Python Whisper</h4>
+ <p>Open your terminal and run the following command to install the transcription engine:</p>
+ <div className="code-block-container">
+ <code>pip3 install -U openai-whisper</code>
+ <button type="button" className="copy-btn" onClick={copyWhisperCommand}>
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ {copied ? "Copied!" : "Copy"}
+ </button>
+ </div>
+ {environment?.hasLocalWhisperModel ? (
+ <span className="step-check success"><BadgeCheck size={14} /> Whisper installed in Python!</span>
+ ) : (
+ <span className="step-check warning">⚠️ Python package 'whisper' not detected yet. Run the command above.</span>
+ )}
+ </div>
+ </div>
+
+ <div className="setup-step">
+ <div className="step-num">2</div>
+ <div className="step-body">
+ <h4>Set up local LLM (Ollama)</h4>
+ <p>
+ Ollama must be installed and running on your machine.
+ If you don't have it installed, you can download it from <a href="https://ollama.com" target="_blank" rel="noreferrer" style={{ color: 'var(--accent-primary)', textDecoration: 'underline' }}>ollama.com</a>.
+ </p>
+ <p>Select a model to download:</p>
+
+ <div className="model-cards">
+ <div
+ className={`model-card ${selectedModel === "llama3.2" ? "active" : ""}`}
+ onClick={() => setSelectedModel("llama3.2")}
+ >
+ <div className="model-card-header">
+ <h5>LLaMA 3.2 3B</h5>
+ <span className="model-size">1.9 GB</span>
+ </div>
+ <p>Requires 8GB+ RAM. Recommended for standard setups. Fast and efficient.</p>
+ </div>
+
+ <div
+ className={`model-card ${selectedModel === "qwen2.5:3b" ? "active" : ""}`}
+ onClick={() => setSelectedModel("qwen2.5:3b")}
+ >
+ <div className="model-card-header">
+ <h5>Qwen 2.5 3B</h5>
+ <span className="model-size">2.0 GB</span>
+ </div>
+ <p>Requires 8GB+ RAM. Excellent coding and logical reasoning abilities.</p>
+ </div>
+
+ <div
+ className={`model-card ${selectedModel === "qwen2.5:7b" ? "active" : ""}`}
+ onClick={() => setSelectedModel("qwen2.5:7b")}
+ >
+ <div className="model-card-header">
+ <h5>Qwen 2.5 7B</h5>
+ <span className="model-size">4.7 GB</span>
+ </div>
+ <p>Requires 16GB+ RAM. High-quality moment detection and hook precision.</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="onboarding-actions">
+ <button type="button" className="icon-button" onClick={() => setSetupMode("choose")}>Back</button>
+ <button
+ type="button"
+ className="primary-action compact"
+ onClick={startLocalSetup}
+ disabled={checkingOllama}
+ >
+ {checkingOllama ? <Loader2 className="spin" size={18} /> : null}
+ {checkingOllama ? "Checking Ollama..." : "Download & Start Setup"}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {setupMode === "cloud" && (
+ <form className="cloud-setup-flow" onSubmit={handleCloudSubmit}>
+ <div className="onboarding-header compact">
+ <h2>Configure Cloud APIs</h2>
+ <p>Add your keys below. AutoShorts will route transcription and analysis to the cloud.</p>
+ </div>
+
+ {error && <div className="error-banner" style={{ marginBottom: "16px" }}>{error}</div>}
+
+ <div className="form-stack">
+ <div className="input-group">
+ <label>Deepgram API Key *</label>
+ <input
+ type="password"
+ value={dgKey}
+ onChange={(e) => setDgKey(e.target.value)}
+ placeholder="Insert your Deepgram API Key (for transcription)"
+ />
+ </div>
+
+ <div className="input-group">
+ <label>Claude API Key</label>
+ <input
+ type="password"
+ value={antKey}
+ onChange={(e) => setAntKey(e.target.value)}
+ placeholder="Insert your Anthropic API Key (moment detection)"
+ />
+ </div>
+
+ <div className="input-group">
+ <label>DeepSeek API Key</label>
+ <input
+ type="password"
+ value={dsKey}
+ onChange={(e) => setDsKey(e.target.value)}
+ placeholder="Insert your DeepSeek API Key (alternative moment detection)"
+ />
+ </div>
+ <p className="form-help">* Deepgram Key + at least one LLM Key (Claude or DeepSeek) is required.</p>
+ </div>
+
+ <div className="onboarding-actions">
+ <button type="button" className="icon-button" onClick={() => setSetupMode("choose")}>Back</button>
+ <button type="submit" className="primary-action compact">Save & Start</button>
+ </div>
+ </form>
+ )}
+
+ {setupMode === "downloading" && (
+ <div className="downloading-flow">
+ <div className="onboarding-header compact">
+ <h2>Downloading Local Model</h2>
+ <p>Please wait while your local environment is downloaded. Do not close the application.</p>
+ </div>
+
+ <div className="download-progress-container">
+ <div className="download-loader">
+ <Loader2 className="spin" size={48} />
+ </div>
+
+ <div className="progress-bar-container">
+ <div className="progress-bar-fill" style={{ width: `${downloadProgress}%` }}></div>
+ </div>
+
+ <div className="download-stats">
+ <span className="download-status">{downloadStatus}</span>
+ <span className="download-percentage">{downloadProgress}%</span>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
diff --git a/src/styles.css b/src/styles.css
index cae9fd3..a856eef 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1277,3 +1277,440 @@ button:disabled {
to { transform: scale(1); opacity: 1; }
}
+.key-stack-horizontal select {
+ width: 100%;
+ min-height: 36px;
+ padding: 0 12px;
+ color: var(--text-primary);
+ background: var(--bg-input);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ outline: none;
+ font-size: 13px;
+ transition: all 0.2s ease;
+ cursor: pointer;
+}
+
+.key-stack-horizontal select:focus {
+ border-color: var(--border-color-focus);
+}
+
+.key-stack-horizontal select option {
+ background: var(--bg-sidebar);
+ color: var(--text-primary);
+}
+
+
+/* Onboarding styles */
+.onboarding-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100vw;
+ height: 100vh;
+ background: radial-gradient(circle at center, rgba(19, 22, 28, 0.96) 0%, var(--bg-base) 100%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 10000;
+ padding: 24px;
+ overflow-y: auto;
+}
+
+.onboarding-card {
+ width: 100%;
+ max-width: 720px;
+ background: var(--bg-panel);
+ border: 1px solid var(--border-color);
+ border-radius: 16px;
+ padding: 40px;
+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.4);
+ animation: scaleIn 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
+}
+
+.onboarding-header {
+ text-align: center;
+ margin-bottom: 36px;
+}
+
+.onboarding-header.compact {
+ text-align: left;
+ margin-bottom: 24px;
+}
+
+.onboarding-header h2 {
+ font-size: 28px;
+ font-weight: 800;
+ letter-spacing: -0.75px;
+ margin: 16px 0 8px;
+ color: var(--text-primary);
+}
+
+.onboarding-header p {
+ color: var(--text-secondary);
+ font-size: 14.5px;
+ margin: 0;
+ line-height: 1.5;
+}
+
+.brand-mark.large {
+ width: 72px;
+ height: 72px;
+ margin: 0 auto;
+ border-radius: 16px;
+ background: var(--accent-primary);
+ color: var(--accent-text);
+ display: grid;
+ place-items: center;
+ box-shadow: 0 8px 24px rgba(142, 230, 199, 0.25);
+}
+
+.onboarding-choices {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 20px;
+ margin-top: 12px;
+}
+
+.choice-card {
+ padding: 32px 24px;
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px solid var(--border-color);
+ border-radius: 12px;
+ text-align: center;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
+ cursor: pointer;
+}
+
+.choice-card:hover {
+ background: rgba(255, 255, 255, 0.04);
+ border-color: rgba(255, 255, 255, 0.15);
+ transform: translateY(-4px);
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
+}
+
+.choice-icon {
+ width: 56px;
+ height: 56px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.03);
+ display: grid;
+ place-items: center;
+ color: var(--text-secondary);
+ transition: all 0.2s ease;
+}
+
+.choice-card:hover .choice-icon {
+ background: rgba(142, 230, 199, 0.1);
+ color: var(--accent-primary);
+}
+
+.choice-card h3 {
+ margin: 0;
+ font-size: 18px;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.choice-card p {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--text-muted);
+}
+
+.choice-badge {
+ margin-top: auto;
+ font-size: 10px;
+ font-weight: 800;
+ text-transform: uppercase;
+ padding: 4px 10px;
+ border-radius: 100px;
+ letter-spacing: 0.5px;
+}
+
+.choice-badge.local {
+ background: rgba(142, 230, 199, 0.08);
+ color: var(--accent-primary);
+}
+
+.choice-badge.cloud {
+ background: rgba(255, 255, 255, 0.05);
+ color: var(--text-secondary);
+}
+
+/* Local Setup Steps */
+.local-setup-flow,
+.cloud-setup-flow {
+ display: flex;
+ flex-direction: column;
+}
+
+.setup-steps {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+ margin-bottom: 24px;
+}
+
+.setup-step {
+ display: grid;
+ grid-template-columns: 32px 1fr;
+ gap: 16px;
+}
+
+.step-num {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--border-color);
+ color: var(--text-secondary);
+ font-weight: 700;
+ font-size: 14px;
+ display: grid;
+ place-items: center;
+}
+
+.step-body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.step-body h4 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.step-body p {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.45;
+ color: var(--text-muted);
+}
+
+.code-block-container {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ background: var(--bg-input);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 8px 12px;
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 12.5px;
+ color: var(--accent-primary);
+}
+
+.copy-btn {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ padding: 4px 8px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-secondary);
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.copy-btn:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--text-primary);
+}
+
+.step-check {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11.5px;
+ font-weight: 700;
+}
+
+.step-check.success {
+ color: var(--color-success-text);
+}
+
+.step-check.warning {
+ color: var(--text-muted);
+}
+
+/* Local Model Cards */
+.model-cards {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 12px;
+ margin-top: 8px;
+}
+
+.model-card {
+ background: rgba(255, 255, 255, 0.01);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ padding: 16px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.model-card:hover {
+ background: rgba(255, 255, 255, 0.03);
+ border-color: rgba(255, 255, 255, 0.15);
+}
+
+.model-card.active {
+ background: rgba(142, 230, 199, 0.03);
+ border-color: var(--accent-primary);
+}
+
+.model-card-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 8px;
+}
+
+.model-card h5 {
+ margin: 0;
+ font-size: 13.5px;
+ font-weight: 700;
+ color: var(--text-primary);
+}
+
+.model-card.active h5 {
+ color: var(--accent-primary);
+}
+
+.model-size {
+ font-size: 10px;
+ font-weight: 800;
+ color: var(--text-muted);
+ background: rgba(255, 255, 255, 0.05);
+ padding: 2px 6px;
+ border-radius: 4px;
+}
+
+.model-card p {
+ margin: 0;
+ font-size: 11.5px;
+ line-height: 1.4;
+ color: var(--text-muted);
+}
+
+/* Cloud Form Styling */
+.form-stack {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ margin-bottom: 24px;
+}
+
+.input-group {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.input-group label {
+ font-size: 12px;
+ font-weight: 700;
+ text-transform: uppercase;
+ color: var(--text-secondary);
+ letter-spacing: 0.5px;
+}
+
+.input-group input {
+ min-height: 40px;
+ padding: 0 14px;
+ color: var(--text-primary);
+ background: var(--bg-input);
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ outline: none;
+ font-size: 13.5px;
+ transition: all 0.2s ease;
+}
+
+.input-group input:focus {
+ border-color: var(--border-color-focus);
+}
+
+.form-help {
+ margin: 0;
+ font-size: 11.5px;
+ color: var(--text-muted);
+}
+
+/* Onboarding actions footer */
+.onboarding-actions {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-top: 16px;
+ padding-top: 16px;
+ border-top: 1px solid var(--border-color);
+}
+
+/* Download Screen styling */
+.downloading-flow {
+ text-align: center;
+}
+
+.download-progress-container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 20px;
+ margin: 24px 0;
+}
+
+.download-loader {
+ color: var(--accent-primary);
+ animation: pulsePlay 2s infinite ease-in-out;
+}
+
+.progress-bar-container {
+ width: 100%;
+ height: 8px;
+ background: rgba(255, 255, 255, 0.05);
+ border-radius: 100px;
+ overflow: hidden;
+}
+
+.progress-bar-fill {
+ height: 100%;
+ background: linear-gradient(90deg, #51cfb3 0%, var(--accent-primary) 100%);
+ border-radius: 100px;
+ transition: width 0.3s ease;
+}
+
+.download-stats {
+ width: 100%;
+ display: flex;
+ justify-content: space-between;
+ font-size: 12.5px;
+ color: var(--text-muted);
+}
+
+.download-status {
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ max-width: 80%;
+ color: var(--text-secondary);
+}
+
+.download-percentage {
+ font-weight: 700;
+ color: var(--accent-primary);
+}