Spaces:
Runtime error
Runtime error
Commit ·
ef94785
1
Parent(s): 648d620
Prompt improvement, UI, better engineering, error checking, andmore UI
Browse filesLLAMA 3.2 might just become the main model that I use. It's so much faster and smarter. And doesn't randomly start hallucinating like phi-mini
Worked on the things that are mentioned.
- README.md +1 -1
- backend/app.py +48 -4
- backend/helpers/transcript.py +2 -2
- backend/ollama.py +137 -35
- backend/schemas.py +5 -0
- backend/youtube.py +1 -1
- frontend/src/App.css +82 -8
- frontend/src/App.jsx +124 -49
- frontend/src/components/InlineResult.jsx +1 -0
- frontend/src/hooks/useStreaming.js +15 -5
README.md
CHANGED
|
@@ -76,7 +76,7 @@ Scripts live in `scripts/`. The project has been tested primarily with **phi4-mi
|
|
| 76 |
|
| 77 |
```bash
|
| 78 |
ollama pull phi4-mini:latest
|
| 79 |
-
ollama pull
|
| 80 |
```
|
| 81 |
|
| 82 |
---
|
|
|
|
| 76 |
|
| 77 |
```bash
|
| 78 |
ollama pull phi4-mini:latest
|
| 79 |
+
ollama pull llama3.1:latest
|
| 80 |
```
|
| 81 |
|
| 82 |
---
|
backend/app.py
CHANGED
|
@@ -15,7 +15,7 @@ from config import (
|
|
| 15 |
API_KEY,
|
| 16 |
MAX_UPLOAD_BYTES,
|
| 17 |
)
|
| 18 |
-
from schemas import TranscriptRequest, YouTubeRequest
|
| 19 |
from ollama import stream_summary
|
| 20 |
from helpers.transcript import transcript as fetch_yt_transcript
|
| 21 |
|
|
@@ -93,13 +93,24 @@ async def list_models():
|
|
| 93 |
r.raise_for_status()
|
| 94 |
payload = r.json() if r.content else {}
|
| 95 |
installed = [m.get("name") for m in payload.get("models", []) if m.get("name")]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
if installed:
|
| 97 |
default = DEFAULT_MODEL if DEFAULT_MODEL in installed else installed[0]
|
| 98 |
-
return {"default": default, "available": installed}
|
| 99 |
except Exception:
|
| 100 |
pass
|
| 101 |
|
| 102 |
-
return {"default": DEFAULT_MODEL, "available": AVAILABLE_MODELS}
|
| 103 |
|
| 104 |
|
| 105 |
@app.post("/warmup")
|
|
@@ -109,7 +120,7 @@ async def warmup_model(model: Optional[str] = None):
|
|
| 109 |
Per the Ollama API docs: sending a generate request with an empty
|
| 110 |
prompt (no 'prompt' key at all) causes Ollama to load the model into
|
| 111 |
memory and return once it is ready. stream=False means this endpoint
|
| 112 |
-
only returns *after* the model is fully loaded
|
| 113 |
it to know exactly when the model is warm.
|
| 114 |
"""
|
| 115 |
keep_alive = os.getenv("OLLAMA_KEEP_ALIVE", "30m")
|
|
@@ -149,6 +160,39 @@ async def warmup_status(model: Optional[str] = None):
|
|
| 149 |
return {"model": target, "loaded": False}
|
| 150 |
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
@app.post("/summarize/transcript")
|
| 153 |
async def summarize_transcript(
|
| 154 |
request: TranscriptRequest,
|
|
|
|
| 15 |
API_KEY,
|
| 16 |
MAX_UPLOAD_BYTES,
|
| 17 |
)
|
| 18 |
+
from schemas import TranscriptRequest, YouTubeRequest, UnloadRequest
|
| 19 |
from ollama import stream_summary
|
| 20 |
from helpers.transcript import transcript as fetch_yt_transcript
|
| 21 |
|
|
|
|
| 93 |
r.raise_for_status()
|
| 94 |
payload = r.json() if r.content else {}
|
| 95 |
installed = [m.get("name") for m in payload.get("models", []) if m.get("name")]
|
| 96 |
+
|
| 97 |
+
# Fetch currently running/loaded models
|
| 98 |
+
running = []
|
| 99 |
+
try:
|
| 100 |
+
ps_r = await client.get(f"{OLLAMA_BASE_URL}/api/ps")
|
| 101 |
+
if ps_r.status_code == 200:
|
| 102 |
+
ps_payload = ps_r.json() if ps_r.content else {}
|
| 103 |
+
running = [m.get("name") for m in ps_payload.get("models", []) if m.get("name")]
|
| 104 |
+
except Exception:
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
if installed:
|
| 108 |
default = DEFAULT_MODEL if DEFAULT_MODEL in installed else installed[0]
|
| 109 |
+
return {"default": default, "available": installed, "running": running}
|
| 110 |
except Exception:
|
| 111 |
pass
|
| 112 |
|
| 113 |
+
return {"default": DEFAULT_MODEL, "available": AVAILABLE_MODELS, "running": []}
|
| 114 |
|
| 115 |
|
| 116 |
@app.post("/warmup")
|
|
|
|
| 120 |
Per the Ollama API docs: sending a generate request with an empty
|
| 121 |
prompt (no 'prompt' key at all) causes Ollama to load the model into
|
| 122 |
memory and return once it is ready. stream=False means this endpoint
|
| 123 |
+
only returns *after* the model is fully loaded.
|
| 124 |
it to know exactly when the model is warm.
|
| 125 |
"""
|
| 126 |
keep_alive = os.getenv("OLLAMA_KEEP_ALIVE", "30m")
|
|
|
|
| 160 |
return {"model": target, "loaded": False}
|
| 161 |
|
| 162 |
|
| 163 |
+
@app.post("/unload")
|
| 164 |
+
async def unload_model(request: UnloadRequest):
|
| 165 |
+
"""Unload a model from Ollama VRAM by sending keep_alive: 0.
|
| 166 |
+
If no model is specified, it unloads all currently loaded models.
|
| 167 |
+
"""
|
| 168 |
+
targets = []
|
| 169 |
+
if request.model:
|
| 170 |
+
targets.append(request.model)
|
| 171 |
+
else:
|
| 172 |
+
try:
|
| 173 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 174 |
+
r = await client.get(f"{OLLAMA_BASE_URL}/api/ps")
|
| 175 |
+
if r.status_code == 200:
|
| 176 |
+
payload = r.json() if r.content else {}
|
| 177 |
+
targets = [m.get("name") for m in payload.get("models", []) if m.get("name")]
|
| 178 |
+
except Exception:
|
| 179 |
+
pass
|
| 180 |
+
|
| 181 |
+
unloaded = []
|
| 182 |
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 183 |
+
for target in targets:
|
| 184 |
+
try:
|
| 185 |
+
await client.post(
|
| 186 |
+
f"{OLLAMA_BASE_URL}/api/generate",
|
| 187 |
+
json={"model": target, "keep_alive": 0, "stream": False},
|
| 188 |
+
)
|
| 189 |
+
unloaded.append(target)
|
| 190 |
+
except Exception:
|
| 191 |
+
pass
|
| 192 |
+
return {"unloaded": unloaded}
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
|
| 196 |
@app.post("/summarize/transcript")
|
| 197 |
async def summarize_transcript(
|
| 198 |
request: TranscriptRequest,
|
backend/helpers/transcript.py
CHANGED
|
@@ -56,7 +56,7 @@ def _extract_video_id(url: str) -> str:
|
|
| 56 |
|
| 57 |
|
| 58 |
def _fetch_transcript_sync(video_id: str) -> str:
|
| 59 |
-
"""Blocking transcript fetch
|
| 60 |
ytt = YouTubeTranscriptApi()
|
| 61 |
try:
|
| 62 |
t = ytt.fetch(video_id, languages=_LANG_PREFS)
|
|
@@ -117,7 +117,7 @@ async def transcript(url: str) -> tuple[Optional[str], str]:
|
|
| 117 |
video_id = _extract_video_id(url)
|
| 118 |
|
| 119 |
# Run the blocking transcript fetch in a thread while the async title
|
| 120 |
-
# fetch runs on the event loop
|
| 121 |
title_task = asyncio.create_task(_fetch_title(video_id))
|
| 122 |
text = await asyncio.to_thread(_fetch_transcript_sync, video_id)
|
| 123 |
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def _fetch_transcript_sync(video_id: str) -> str:
|
| 59 |
+
"""Blocking transcript fetch. Always call via ``asyncio.to_thread``."""
|
| 60 |
ytt = YouTubeTranscriptApi()
|
| 61 |
try:
|
| 62 |
t = ytt.fetch(video_id, languages=_LANG_PREFS)
|
|
|
|
| 117 |
video_id = _extract_video_id(url)
|
| 118 |
|
| 119 |
# Run the blocking transcript fetch in a thread while the async title
|
| 120 |
+
# fetch runs on the event loop (parallel).
|
| 121 |
title_task = asyncio.create_task(_fetch_title(video_id))
|
| 122 |
text = await asyncio.to_thread(_fetch_transcript_sync, video_id)
|
| 123 |
|
backend/ollama.py
CHANGED
|
@@ -13,27 +13,34 @@ from config import (
|
|
| 13 |
|
| 14 |
|
| 15 |
def build_prompt(title: Optional[str], text: str) -> str:
|
| 16 |
-
"""
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
# Optional title block
|
| 23 |
title_block = f"### Title: {title}\n" if title else ""
|
| 24 |
|
| 25 |
instruction = \
|
| 26 |
-
"Before proceeding, remember that you must follow these
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
"
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
return (
|
| 39 |
f"{instruction}\n"
|
|
@@ -44,24 +51,19 @@ def build_prompt(title: Optional[str], text: str) -> str:
|
|
| 44 |
)
|
| 45 |
|
| 46 |
|
| 47 |
-
# Cache for installed models to avoid repeated network calls
|
| 48 |
-
_installed_models_cache: Optional[list] = None
|
| 49 |
-
|
| 50 |
async def resolve_model(model: Optional[str]) -> str:
|
| 51 |
requested = model or ""
|
| 52 |
|
| 53 |
-
# Prefer what Ollama actually has installed,
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
_installed_models_cache = []
|
| 64 |
-
installed = _installed_models_cache
|
| 65 |
|
| 66 |
if installed:
|
| 67 |
if not requested:
|
|
@@ -105,7 +107,12 @@ async def ensure_ollama_reachable() -> None:
|
|
| 105 |
|
| 106 |
|
| 107 |
async def ollama_stream(prompt: str, model: str):
|
| 108 |
-
"""Async generator: yields NDJSON lines from Ollama
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
keep_alive = os.getenv("OLLAMA_KEEP_ALIVE", "30m")
|
| 110 |
# Set num_predict high so thinking tokens don't limit output.
|
| 111 |
num_predict = MAX_SUMMARY_TOKENS * 3
|
|
@@ -119,22 +126,116 @@ async def ollama_stream(prompt: str, model: str):
|
|
| 119 |
"temperature": TEMPERATURE,
|
| 120 |
},
|
| 121 |
}
|
|
|
|
|
|
|
|
|
|
| 122 |
async with httpx.AsyncClient(timeout=300.0) as client:
|
| 123 |
try:
|
| 124 |
async with client.stream(
|
| 125 |
"POST", f"{OLLAMA_BASE_URL}/api/generate", json=payload,
|
| 126 |
) as resp:
|
| 127 |
resp.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
async for line in resp.aiter_lines():
|
| 129 |
if not line:
|
| 130 |
continue
|
| 131 |
try:
|
| 132 |
chunk = json.loads(line)
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
except json.JSONDecodeError:
|
| 137 |
yield line + "\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
except httpx.ConnectError:
|
| 139 |
error_line = json.dumps({
|
| 140 |
"error": "Cannot reach Ollama. Make sure `ollama serve` is running.",
|
|
@@ -142,7 +243,7 @@ async def ollama_stream(prompt: str, model: str):
|
|
| 142 |
yield error_line + "\n"
|
| 143 |
except httpx.TimeoutException:
|
| 144 |
error_line = json.dumps({
|
| 145 |
-
"error": "Ollama timed out. The model may still be loading
|
| 146 |
})
|
| 147 |
yield error_line + "\n"
|
| 148 |
except httpx.HTTPError as exc:
|
|
@@ -152,6 +253,7 @@ async def ollama_stream(prompt: str, model: str):
|
|
| 152 |
yield error_line + "\n"
|
| 153 |
|
| 154 |
|
|
|
|
| 155 |
async def stream_summary(
|
| 156 |
text: str,
|
| 157 |
title: Optional[str] = None,
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def build_prompt(title: Optional[str], text: str) -> str:
|
| 16 |
+
"""The summarization prompt sent to Ollama.
|
| 17 |
|
| 18 |
+
I need it to handle all cases and ensure clean summaries that are *as short as possible*.
|
| 19 |
+
|
| 20 |
+
Remember:
|
| 21 |
+
- Needs three features: brevity, brevity, and brevity
|
| 22 |
+
- Ensure output begins with the first word of the summary
|
| 23 |
+
- Omit fluff that's not related to the title (OR overriding theme)
|
| 24 |
+
- No meta-commentary
|
| 25 |
"""
|
| 26 |
# Optional title block
|
| 27 |
title_block = f"### Title: {title}\n" if title else ""
|
| 28 |
|
| 29 |
instruction = \
|
| 30 |
+
"Before proceeding, remember that you are an expert summarizer and must follow these instructions: \n" \
|
| 31 |
+
"The objective is to take the given text and produce a compendious summary. \n" \
|
| 32 |
+
"The priorities of the summary are as follows: \n" \
|
| 33 |
+
" 1) Make direct, declarative sentences while speaking with perfect, proper grammar. "\
|
| 34 |
+
" 2) If a title is provided, let it be an inspiration for the summary. If the title contains a question, answer it directly in the summary.\n" \
|
| 35 |
+
" 3) Ignore ads, channel plugs, affiliate links, channel/author descriptions, sponsors, supporter shoutouts, and all other info not pertinent to the specific topic at hand.\n" \
|
| 36 |
+
" 4) With every sentence, get straight to the point. Exclude opinions ('some think...'), mistakes ('um', 'like', etc.), uncertainty ('may suggests that...', etc.), transitions ('The video provides...'), commentary, or context (like 'the text states...', 'the author thinks', or anything like \that) are allowed.\n" \
|
| 37 |
+
" 5) Only state the most obvious, objective, and conclusive points from the text.\n" \
|
| 38 |
+
" 6) Keep sentences to <= 100 characters and paragraphs to <= 3 sentences. Make use of point form and lists in order to break up large chunks of text.\n" \
|
| 39 |
+
" 7) Most importantly, be 'in and out' with the facts. State only the most crucial high-level points and move on. This means, never introduce what is about to be said, i.e. don't say things like, `in this historical analysis, `, or `before proceeding`, or anything like that. Ensure sentences are short and ONLY discuss the topic at hand.\n" \
|
| 40 |
+
" 8) Never state who you are, what you do, what you just did, or what you're about to do. Do not mention this or any other prompt. Strictly stick to the content of the material given. \n" \
|
| 41 |
+
"No matter what is asked. Never break the fourth wall. Never refer to yourself in any way. Never speak in first person. Never refer to anything outside the given text or title in any way.\n" \
|
| 42 |
+
"The goal of the summary is to produce a compendious summary so that the user can save time." \
|
| 43 |
+
"Now, I need you to summarize the following text.\n" \
|
| 44 |
|
| 45 |
return (
|
| 46 |
f"{instruction}\n"
|
|
|
|
| 51 |
)
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
| 54 |
async def resolve_model(model: Optional[str]) -> str:
|
| 55 |
requested = model or ""
|
| 56 |
|
| 57 |
+
# Prefer what Ollama actually has installed, queried live.
|
| 58 |
+
installed = []
|
| 59 |
+
try:
|
| 60 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 61 |
+
r = await client.get(f"{OLLAMA_BASE_URL}/api/tags")
|
| 62 |
+
r.raise_for_status()
|
| 63 |
+
payload = r.json() if r.content else {}
|
| 64 |
+
installed = [m.get("name") for m in payload.get("models", []) if m.get("name")]
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
|
|
|
|
|
|
| 67 |
|
| 68 |
if installed:
|
| 69 |
if not requested:
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
async def ollama_stream(prompt: str, model: str):
|
| 110 |
+
"""Async generator: yields NDJSON lines from Ollama.
|
| 111 |
+
|
| 112 |
+
Parses standard output response stream to isolate <think>...</think> blocks
|
| 113 |
+
on the backend, yielding separate 'thinking' and 'response' events. This
|
| 114 |
+
ensures compatibility across all Ollama versions and avoids 400 Bad Request errors.
|
| 115 |
+
"""
|
| 116 |
keep_alive = os.getenv("OLLAMA_KEEP_ALIVE", "30m")
|
| 117 |
# Set num_predict high so thinking tokens don't limit output.
|
| 118 |
num_predict = MAX_SUMMARY_TOKENS * 3
|
|
|
|
| 126 |
"temperature": TEMPERATURE,
|
| 127 |
},
|
| 128 |
}
|
| 129 |
+
if "r1" in model.lower() or "deepseek" in model.lower():
|
| 130 |
+
payload["think"] = True
|
| 131 |
+
|
| 132 |
async with httpx.AsyncClient(timeout=300.0) as client:
|
| 133 |
try:
|
| 134 |
async with client.stream(
|
| 135 |
"POST", f"{OLLAMA_BASE_URL}/api/generate", json=payload,
|
| 136 |
) as resp:
|
| 137 |
resp.raise_for_status()
|
| 138 |
+
|
| 139 |
+
in_thinking = False
|
| 140 |
+
buffer = ""
|
| 141 |
+
# To track if we started native thinking
|
| 142 |
+
native_thinking_active = False
|
| 143 |
+
|
| 144 |
async for line in resp.aiter_lines():
|
| 145 |
if not line:
|
| 146 |
continue
|
| 147 |
try:
|
| 148 |
chunk = json.loads(line)
|
| 149 |
+
native_thinking = chunk.get("thinking") or ""
|
| 150 |
+
native_response = chunk.get("response") or ""
|
| 151 |
+
|
| 152 |
+
if native_thinking:
|
| 153 |
+
if not native_thinking_active:
|
| 154 |
+
yield json.dumps({"response": "> *Model Reasoning:*\n> \n> "}) + "\n"
|
| 155 |
+
native_thinking_active = True
|
| 156 |
+
|
| 157 |
+
formatted = native_thinking.replace("\n", "\n> ")
|
| 158 |
+
yield json.dumps({"response": formatted}) + "\n"
|
| 159 |
+
continue
|
| 160 |
+
|
| 161 |
+
if not native_response:
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
+
# If native thinking just ended
|
| 165 |
+
if native_thinking_active:
|
| 166 |
+
yield json.dumps({"response": "\n\n---\n\n"}) + "\n"
|
| 167 |
+
native_thinking_active = False
|
| 168 |
+
|
| 169 |
+
buffer += native_response
|
| 170 |
+
|
| 171 |
+
# Extract <think>...</think> tags dynamically
|
| 172 |
+
while True:
|
| 173 |
+
if not in_thinking:
|
| 174 |
+
idx = buffer.find("<think>")
|
| 175 |
+
if idx != -1:
|
| 176 |
+
before = buffer[:idx]
|
| 177 |
+
if before:
|
| 178 |
+
yield json.dumps({"response": before}) + "\n"
|
| 179 |
+
in_thinking = True
|
| 180 |
+
yield json.dumps({"response": "\n> *Model Reasoning:*\n> \n> "}) + "\n"
|
| 181 |
+
buffer = buffer[idx + 7:]
|
| 182 |
+
else:
|
| 183 |
+
# Check for partial match of "<think>" at the end of the buffer
|
| 184 |
+
partial_len = 0
|
| 185 |
+
for i in range(6, 0, -1):
|
| 186 |
+
if buffer.endswith("<think>"[:i]):
|
| 187 |
+
partial_len = i
|
| 188 |
+
break
|
| 189 |
+
if partial_len > 0:
|
| 190 |
+
to_yield = buffer[:-partial_len]
|
| 191 |
+
if to_yield:
|
| 192 |
+
yield json.dumps({"response": to_yield}) + "\n"
|
| 193 |
+
buffer = buffer[-partial_len:]
|
| 194 |
+
break
|
| 195 |
+
else:
|
| 196 |
+
yield json.dumps({"response": buffer}) + "\n"
|
| 197 |
+
buffer = ""
|
| 198 |
+
break
|
| 199 |
+
else:
|
| 200 |
+
idx = buffer.find("</think>")
|
| 201 |
+
if idx != -1:
|
| 202 |
+
thinking_content = buffer[:idx]
|
| 203 |
+
if thinking_content:
|
| 204 |
+
formatted = thinking_content.replace("\n", "\n> ")
|
| 205 |
+
yield json.dumps({"response": formatted}) + "\n"
|
| 206 |
+
in_thinking = False
|
| 207 |
+
yield json.dumps({"response": "\n\n---\n\n"}) + "\n"
|
| 208 |
+
buffer = buffer[idx + 8:]
|
| 209 |
+
else:
|
| 210 |
+
# Check for partial match of "</think>" at the end of the buffer
|
| 211 |
+
partial_len = 0
|
| 212 |
+
for i in range(7, 0, -1):
|
| 213 |
+
if buffer.endswith("</think>"[:i]):
|
| 214 |
+
partial_len = i
|
| 215 |
+
break
|
| 216 |
+
if partial_len > 0:
|
| 217 |
+
to_yield = buffer[:-partial_len]
|
| 218 |
+
if to_yield:
|
| 219 |
+
formatted = to_yield.replace("\n", "\n> ")
|
| 220 |
+
yield json.dumps({"response": formatted}) + "\n"
|
| 221 |
+
buffer = buffer[-partial_len:]
|
| 222 |
+
break
|
| 223 |
+
else:
|
| 224 |
+
formatted = buffer.replace("\n", "\n> ")
|
| 225 |
+
yield json.dumps({"response": formatted}) + "\n"
|
| 226 |
+
buffer = ""
|
| 227 |
+
break
|
| 228 |
except json.JSONDecodeError:
|
| 229 |
yield line + "\n"
|
| 230 |
+
|
| 231 |
+
# Yield remainder
|
| 232 |
+
if buffer:
|
| 233 |
+
if in_thinking:
|
| 234 |
+
formatted = buffer.replace("\n", "\n> ")
|
| 235 |
+
yield json.dumps({"response": formatted}) + "\n"
|
| 236 |
+
else:
|
| 237 |
+
yield json.dumps({"response": buffer}) + "\n"
|
| 238 |
+
|
| 239 |
except httpx.ConnectError:
|
| 240 |
error_line = json.dumps({
|
| 241 |
"error": "Cannot reach Ollama. Make sure `ollama serve` is running.",
|
|
|
|
| 243 |
yield error_line + "\n"
|
| 244 |
except httpx.TimeoutException:
|
| 245 |
error_line = json.dumps({
|
| 246 |
+
"error": "Ollama timed out. The model may still be loading. Try again in a moment.",
|
| 247 |
})
|
| 248 |
yield error_line + "\n"
|
| 249 |
except httpx.HTTPError as exc:
|
|
|
|
| 253 |
yield error_line + "\n"
|
| 254 |
|
| 255 |
|
| 256 |
+
|
| 257 |
async def stream_summary(
|
| 258 |
text: str,
|
| 259 |
title: Optional[str] = None,
|
backend/schemas.py
CHANGED
|
@@ -13,3 +13,8 @@ class TranscriptRequest(BaseModel):
|
|
| 13 |
text: str = Field(min_length=1, max_length=MAX_TRANSCRIPT_CHARS)
|
| 14 |
title: Optional[str] = None
|
| 15 |
model: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
text: str = Field(min_length=1, max_length=MAX_TRANSCRIPT_CHARS)
|
| 14 |
title: Optional[str] = None
|
| 15 |
model: Optional[str] = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class UnloadRequest(BaseModel):
|
| 19 |
+
model: Optional[str] = None
|
| 20 |
+
|
backend/youtube.py
CHANGED
|
@@ -23,7 +23,7 @@ def extract_video_id(url: str) -> str:
|
|
| 23 |
|
| 24 |
|
| 25 |
def fetch_transcript(video_id: str) -> str:
|
| 26 |
-
"""Synchronous transcript fetch
|
| 27 |
ytt = YouTubeTranscriptApi()
|
| 28 |
try:
|
| 29 |
transcript = ytt.fetch(video_id, languages=["en", "en-US", "en-GB"])
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
def fetch_transcript(video_id: str) -> str:
|
| 26 |
+
"""Synchronous transcript fetch. Call via asyncio.to_thread."""
|
| 27 |
ytt = YouTubeTranscriptApi()
|
| 28 |
try:
|
| 29 |
transcript = ytt.fetch(video_id, languages=["en", "en-US", "en-GB"])
|
frontend/src/App.css
CHANGED
|
@@ -248,10 +248,18 @@
|
|
| 248 |
.action-row {
|
| 249 |
display: flex;
|
| 250 |
align-items: center;
|
|
|
|
| 251 |
gap: 12px;
|
| 252 |
-
padding:
|
| 253 |
border-top: 1px solid var(--color-border-muted);
|
| 254 |
-
margin-top: var(--spacing-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
}
|
| 256 |
|
| 257 |
.btn-generate {
|
|
@@ -262,18 +270,18 @@
|
|
| 262 |
}
|
| 263 |
|
| 264 |
.action-hint {
|
| 265 |
-
font-size:
|
| 266 |
color: var(--color-fg-subtle);
|
| 267 |
-
margin
|
| 268 |
}
|
| 269 |
|
| 270 |
.action-hint kbd {
|
| 271 |
font-family: inherit;
|
| 272 |
-
font-size:
|
| 273 |
background: var(--color-canvas-inset);
|
| 274 |
border: 1px solid var(--color-border-muted);
|
| 275 |
border-radius: 4px;
|
| 276 |
-
padding: 0
|
| 277 |
color: var(--color-fg-muted);
|
| 278 |
}
|
| 279 |
|
|
@@ -495,10 +503,76 @@
|
|
| 495 |
|
| 496 |
.footer a:hover { color: var(--color-fg-muted); }
|
| 497 |
|
| 498 |
-
/*
|
| 499 |
.fade-in { animation: fadeUp 0.25s ease-out both; }
|
| 500 |
|
| 501 |
-
/*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
@media (max-width: 768px) {
|
| 503 |
.logo {
|
| 504 |
gap: 16px;
|
|
|
|
| 248 |
.action-row {
|
| 249 |
display: flex;
|
| 250 |
align-items: center;
|
| 251 |
+
justify-content: flex-end;
|
| 252 |
gap: 12px;
|
| 253 |
+
padding: 12px 24px;
|
| 254 |
border-top: 1px solid var(--color-border-muted);
|
| 255 |
+
margin-top: var(--spacing-3);
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
.generate-wrapper {
|
| 259 |
+
display: flex;
|
| 260 |
+
flex-direction: column;
|
| 261 |
+
align-items: center;
|
| 262 |
+
gap: 4px;
|
| 263 |
}
|
| 264 |
|
| 265 |
.btn-generate {
|
|
|
|
| 270 |
}
|
| 271 |
|
| 272 |
.action-hint {
|
| 273 |
+
font-size: 10px;
|
| 274 |
color: var(--color-fg-subtle);
|
| 275 |
+
margin: 0;
|
| 276 |
}
|
| 277 |
|
| 278 |
.action-hint kbd {
|
| 279 |
font-family: inherit;
|
| 280 |
+
font-size: 9px;
|
| 281 |
background: var(--color-canvas-inset);
|
| 282 |
border: 1px solid var(--color-border-muted);
|
| 283 |
border-radius: 4px;
|
| 284 |
+
padding: 0 4px;
|
| 285 |
color: var(--color-fg-muted);
|
| 286 |
}
|
| 287 |
|
|
|
|
| 503 |
|
| 504 |
.footer a:hover { color: var(--color-fg-muted); }
|
| 505 |
|
| 506 |
+
/* Fade-in */
|
| 507 |
.fade-in { animation: fadeUp 0.25s ease-out both; }
|
| 508 |
|
| 509 |
+
/* Tooltips (Desktop Only) */
|
| 510 |
+
@media (hover: hover) and (min-width: 769px) {
|
| 511 |
+
[data-tooltip] {
|
| 512 |
+
position: relative;
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
[data-tooltip]::after {
|
| 516 |
+
content: attr(data-tooltip);
|
| 517 |
+
position: absolute;
|
| 518 |
+
bottom: 125%;
|
| 519 |
+
left: 50%;
|
| 520 |
+
transform: translateX(-50%) translateY(4px);
|
| 521 |
+
background-color: #24292f;
|
| 522 |
+
color: #ffffff;
|
| 523 |
+
font-size: 11px;
|
| 524 |
+
font-family: var(--font-family-sans);
|
| 525 |
+
font-weight: 500;
|
| 526 |
+
padding: 5px 8px;
|
| 527 |
+
border-radius: 6px;
|
| 528 |
+
border: 1px solid #30363d;
|
| 529 |
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
| 530 |
+
white-space: nowrap;
|
| 531 |
+
opacity: 0;
|
| 532 |
+
pointer-events: none;
|
| 533 |
+
transition: opacity 0.12s ease, transform 0.12s ease;
|
| 534 |
+
z-index: 100;
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
[data-tooltip]::before {
|
| 538 |
+
content: "";
|
| 539 |
+
position: absolute;
|
| 540 |
+
bottom: 115%;
|
| 541 |
+
left: 50%;
|
| 542 |
+
transform: translateX(-50%) translateY(4px);
|
| 543 |
+
border-width: 5px;
|
| 544 |
+
border-style: solid;
|
| 545 |
+
border-color: #24292f transparent transparent transparent;
|
| 546 |
+
opacity: 0;
|
| 547 |
+
pointer-events: none;
|
| 548 |
+
transition: opacity 0.12s ease, transform 0.12s ease;
|
| 549 |
+
z-index: 100;
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
[data-tooltip]:hover::after,
|
| 553 |
+
[data-tooltip]:hover::before {
|
| 554 |
+
opacity: 1;
|
| 555 |
+
transform: translateX(-50%) translateY(0);
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
/* Align Generate tooltip to the right edge to prevent card overflow clipping */
|
| 559 |
+
.btn-generate[data-tooltip]::after {
|
| 560 |
+
left: auto;
|
| 561 |
+
right: 0;
|
| 562 |
+
transform: translateY(4px);
|
| 563 |
+
}
|
| 564 |
+
.btn-generate[data-tooltip]::before {
|
| 565 |
+
left: auto;
|
| 566 |
+
right: 20px;
|
| 567 |
+
transform: translateY(4px);
|
| 568 |
+
}
|
| 569 |
+
.btn-generate[data-tooltip]:hover::after,
|
| 570 |
+
.btn-generate[data-tooltip]:hover::before {
|
| 571 |
+
transform: translateY(0);
|
| 572 |
+
}
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
/* Media Queries (Mobile Friendly) */
|
| 576 |
@media (max-width: 768px) {
|
| 577 |
.logo {
|
| 578 |
gap: 16px;
|
frontend/src/App.jsx
CHANGED
|
@@ -23,25 +23,38 @@ function App() {
|
|
| 23 |
const streaming = { youtube: ytStreaming, transcript: textStreaming, file: fileStreaming }
|
| 24 |
const active = streaming[activeTab]
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
useEffect(() => {
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
const available = Array.isArray(data.available) ? data.available : []
|
| 35 |
-
setModels(available)
|
| 36 |
-
const serverDefault = typeof data.default === 'string' ? data.default : ''
|
| 37 |
-
setSelectedModel((prev) => prev || serverDefault || available[0] || '')
|
| 38 |
-
} catch { /* non-fatal */ }
|
| 39 |
-
})()
|
| 40 |
-
return () => { cancelled = true }
|
| 41 |
}, [])
|
| 42 |
|
| 43 |
useEffect(() => {
|
| 44 |
if (!selectedModel) return
|
|
|
|
| 45 |
if (warmupAbortRef.current) warmupAbortRef.current.abort()
|
| 46 |
const controller = new AbortController()
|
| 47 |
warmupAbortRef.current = controller
|
|
@@ -62,14 +75,32 @@ function App() {
|
|
| 62 |
} catch { /* ignore */ }
|
| 63 |
if (!controller.signal.aborted) pollTimer = setTimeout(poll, 2000)
|
| 64 |
}
|
| 65 |
-
poll()
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
return () => { controller.abort(); clearTimeout(pollTimer) }
|
| 75 |
}, [selectedModel])
|
|
@@ -94,9 +125,38 @@ function App() {
|
|
| 94 |
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
| 95 |
}
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
const TABS = [
|
| 102 |
{ key: 'youtube', label: 'YouTube' },
|
|
@@ -148,7 +208,6 @@ function App() {
|
|
| 148 |
placeholder="https://www.youtube.com/watch?v=…"
|
| 149 |
value={youtubeUrl}
|
| 150 |
onChange={(e) => setYoutubeUrl(e.target.value)}
|
| 151 |
-
onKeyDown={ctrlEnter}
|
| 152 |
/>
|
| 153 |
</div>
|
| 154 |
<InlineResult
|
|
@@ -157,8 +216,8 @@ function App() {
|
|
| 157 |
response={ytStreaming.response}
|
| 158 |
streamingText={ytStreaming.streamingText}
|
| 159 |
selectedModel={selectedModel}
|
| 160 |
-
loadingLabel={ytStreaming.
|
| 161 |
-
placeholderText=
|
| 162 |
/>
|
| 163 |
</div>
|
| 164 |
|
|
@@ -171,7 +230,6 @@ function App() {
|
|
| 171 |
placeholder="Paste your article or transcript here…"
|
| 172 |
value={transcript}
|
| 173 |
onChange={(e) => setTranscript(e.target.value)}
|
| 174 |
-
onKeyDown={ctrlEnter}
|
| 175 |
/>
|
| 176 |
</div>
|
| 177 |
<InlineResult
|
|
@@ -228,8 +286,8 @@ function App() {
|
|
| 228 |
response={fileStreaming.response}
|
| 229 |
streamingText={fileStreaming.streamingText}
|
| 230 |
selectedModel={selectedModel}
|
| 231 |
-
loadingLabel=
|
| 232 |
-
placeholderText=
|
| 233 |
/>
|
| 234 |
</div>
|
| 235 |
</div>
|
|
@@ -237,30 +295,37 @@ function App() {
|
|
| 237 |
{/* Action row */}
|
| 238 |
<div className="action-row">
|
| 239 |
{active.loading && (
|
| 240 |
-
<button className="btn btn-cancel" onClick={active.cancel}>
|
| 241 |
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
| 242 |
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
|
| 243 |
</svg>
|
| 244 |
Cancel
|
| 245 |
</button>
|
| 246 |
)}
|
| 247 |
-
<
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
</div>
|
| 265 |
|
| 266 |
</div>
|
|
@@ -271,9 +336,19 @@ function App() {
|
|
| 271 |
className={`model-select${modelReady === true ? ' model-select--ready' : modelReady === false ? ' model-select--warming' : ''}`}
|
| 272 |
value={selectedModel}
|
| 273 |
onChange={(e) => setSelectedModel(e.target.value)}
|
|
|
|
| 274 |
disabled={active.loading || models.length === 0}
|
| 275 |
>
|
| 276 |
-
{models.map((m) =>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
</select>
|
| 278 |
</div>
|
| 279 |
|
|
|
|
| 23 |
const streaming = { youtube: ytStreaming, transcript: textStreaming, file: fileStreaming }
|
| 24 |
const active = streaming[activeTab]
|
| 25 |
|
| 26 |
+
const [runningModels, setRunningModels] = useState([])
|
| 27 |
+
const isMounted = useRef(true)
|
| 28 |
+
const prevModelRef = useRef(null)
|
| 29 |
+
|
| 30 |
+
const fetchModels = async () => {
|
| 31 |
+
try {
|
| 32 |
+
const res = await fetch(`${API_BASE}/models`)
|
| 33 |
+
if (!res.ok) return
|
| 34 |
+
const data = await res.json()
|
| 35 |
+
if (!isMounted.current) return
|
| 36 |
+
const available = Array.isArray(data.available) ? data.available : []
|
| 37 |
+
const running = Array.isArray(data.running) ? data.running : []
|
| 38 |
+
setModels(available)
|
| 39 |
+
setRunningModels(running)
|
| 40 |
+
const serverDefault = typeof data.default === 'string' ? data.default : ''
|
| 41 |
+
setSelectedModel((prev) => prev || serverDefault || available[0] || '')
|
| 42 |
+
} catch { /* non-fatal */ }
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
useEffect(() => {
|
| 46 |
+
isMounted.current = true
|
| 47 |
+
fetchModels()
|
| 48 |
+
const interval = setInterval(fetchModels, 10000)
|
| 49 |
+
return () => {
|
| 50 |
+
isMounted.current = false
|
| 51 |
+
clearInterval(interval)
|
| 52 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
}, [])
|
| 54 |
|
| 55 |
useEffect(() => {
|
| 56 |
if (!selectedModel) return
|
| 57 |
+
|
| 58 |
if (warmupAbortRef.current) warmupAbortRef.current.abort()
|
| 59 |
const controller = new AbortController()
|
| 60 |
warmupAbortRef.current = controller
|
|
|
|
| 75 |
} catch { /* ignore */ }
|
| 76 |
if (!controller.signal.aborted) pollTimer = setTimeout(poll, 2000)
|
| 77 |
}
|
|
|
|
| 78 |
|
| 79 |
+
const startSequence = async () => {
|
| 80 |
+
if (prevModelRef.current && prevModelRef.current !== selectedModel) {
|
| 81 |
+
try {
|
| 82 |
+
await fetch(`${API_BASE}/unload`, {
|
| 83 |
+
method: 'POST',
|
| 84 |
+
headers: { 'Content-Type': 'application/json' },
|
| 85 |
+
body: JSON.stringify({ model: prevModelRef.current }),
|
| 86 |
+
signal: controller.signal,
|
| 87 |
+
})
|
| 88 |
+
fetchModels()
|
| 89 |
+
} catch { /* ignore */ }
|
| 90 |
+
}
|
| 91 |
+
prevModelRef.current = selectedModel
|
| 92 |
+
|
| 93 |
+
poll()
|
| 94 |
+
|
| 95 |
+
fetch(`${API_BASE}/warmup`, {
|
| 96 |
+
method: 'POST',
|
| 97 |
+
headers: { 'Content-Type': 'application/json' },
|
| 98 |
+
body: JSON.stringify({ model: selectedModel }),
|
| 99 |
+
signal: controller.signal,
|
| 100 |
+
}).then(() => setModelReady(true)).catch(() => {})
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
startSequence()
|
| 104 |
|
| 105 |
return () => { controller.abort(); clearTimeout(pollTimer) }
|
| 106 |
}, [selectedModel])
|
|
|
|
| 125 |
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
| 126 |
}
|
| 127 |
|
| 128 |
+
useEffect(() => {
|
| 129 |
+
const handleKeyDown = (e) => {
|
| 130 |
+
// Ctrl + Enter to generate
|
| 131 |
+
if (e.ctrlKey && e.key === 'Enter') {
|
| 132 |
+
if (!active.loading) {
|
| 133 |
+
e.preventDefault()
|
| 134 |
+
handleSubmit()
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
// Ctrl + Alt + C to copy YouTube URL
|
| 138 |
+
if (e.ctrlKey && e.altKey && (e.key === 'c' || e.key === 'C')) {
|
| 139 |
+
e.preventDefault()
|
| 140 |
+
if (youtubeUrl) {
|
| 141 |
+
navigator.clipboard.writeText(youtubeUrl).catch(() => {})
|
| 142 |
+
}
|
| 143 |
+
return
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Ctrl + C to cancel (only when loading, and no text selected)
|
| 147 |
+
if (e.ctrlKey && !e.shiftKey && (e.key === 'c' || e.key === 'C')) {
|
| 148 |
+
if (active.loading) {
|
| 149 |
+
const selection = window.getSelection()?.toString()
|
| 150 |
+
if (!selection) {
|
| 151 |
+
e.preventDefault()
|
| 152 |
+
active.cancel()
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
window.addEventListener('keydown', handleKeyDown)
|
| 158 |
+
return () => window.removeEventListener('keydown', handleKeyDown)
|
| 159 |
+
}, [active, handleSubmit])
|
| 160 |
|
| 161 |
const TABS = [
|
| 162 |
{ key: 'youtube', label: 'YouTube' },
|
|
|
|
| 208 |
placeholder="https://www.youtube.com/watch?v=…"
|
| 209 |
value={youtubeUrl}
|
| 210 |
onChange={(e) => setYoutubeUrl(e.target.value)}
|
|
|
|
| 211 |
/>
|
| 212 |
</div>
|
| 213 |
<InlineResult
|
|
|
|
| 216 |
response={ytStreaming.response}
|
| 217 |
streamingText={ytStreaming.streamingText}
|
| 218 |
selectedModel={selectedModel}
|
| 219 |
+
loadingLabel={ytStreaming.isGenerating ? 'Generating…' : 'Fetching transcript…'}
|
| 220 |
+
placeholderText={ytStreaming.isGenerating ? 'Waiting for model…' : 'Fetching transcript…'}
|
| 221 |
/>
|
| 222 |
</div>
|
| 223 |
|
|
|
|
| 230 |
placeholder="Paste your article or transcript here…"
|
| 231 |
value={transcript}
|
| 232 |
onChange={(e) => setTranscript(e.target.value)}
|
|
|
|
| 233 |
/>
|
| 234 |
</div>
|
| 235 |
<InlineResult
|
|
|
|
| 286 |
response={fileStreaming.response}
|
| 287 |
streamingText={fileStreaming.streamingText}
|
| 288 |
selectedModel={selectedModel}
|
| 289 |
+
loadingLabel={fileStreaming.isGenerating ? 'Generating…' : 'Reading file…'}
|
| 290 |
+
placeholderText={fileStreaming.isGenerating ? 'Waiting for model…' : 'Reading file…'}
|
| 291 |
/>
|
| 292 |
</div>
|
| 293 |
</div>
|
|
|
|
| 295 |
{/* Action row */}
|
| 296 |
<div className="action-row">
|
| 297 |
{active.loading && (
|
| 298 |
+
<button className="btn btn-cancel" onClick={active.cancel} data-tooltip="Ctrl + C">
|
| 299 |
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
|
| 300 |
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
|
| 301 |
</svg>
|
| 302 |
Cancel
|
| 303 |
</button>
|
| 304 |
)}
|
| 305 |
+
<div className="generate-wrapper">
|
| 306 |
+
<button
|
| 307 |
+
className="btn btn-primary btn-generate"
|
| 308 |
+
onClick={handleSubmit}
|
| 309 |
+
disabled={active.loading}
|
| 310 |
+
data-tooltip="Ctrl + Enter"
|
| 311 |
+
>
|
| 312 |
+
{active.loading ? (
|
| 313 |
+
<><span className="loading-spinner" style={{ width: 15, height: 15 }} /> Processing…</>
|
| 314 |
+
) : (
|
| 315 |
+
<>
|
| 316 |
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
| 317 |
+
<path d="M22 2L11 13" /><path d="M22 2L15 22l-4-9-9-4L22 2z" />
|
| 318 |
+
</svg>
|
| 319 |
+
Generate
|
| 320 |
+
</>
|
| 321 |
+
)}
|
| 322 |
+
</button>
|
| 323 |
+
<span className="action-hint">
|
| 324 |
+
{!active.loading && (
|
| 325 |
+
<>or <kbd>Ctrl</kbd>+<kbd>Enter</kbd></>
|
| 326 |
+
)}
|
| 327 |
+
</span>
|
| 328 |
+
</div>
|
| 329 |
</div>
|
| 330 |
|
| 331 |
</div>
|
|
|
|
| 336 |
className={`model-select${modelReady === true ? ' model-select--ready' : modelReady === false ? ' model-select--warming' : ''}`}
|
| 337 |
value={selectedModel}
|
| 338 |
onChange={(e) => setSelectedModel(e.target.value)}
|
| 339 |
+
onFocus={fetchModels}
|
| 340 |
disabled={active.loading || models.length === 0}
|
| 341 |
>
|
| 342 |
+
{models.map((m) => {
|
| 343 |
+
const isRunning = runningModels.some(
|
| 344 |
+
(r) => r === m || r.startsWith(m + ':') || m.startsWith(r + ':')
|
| 345 |
+
)
|
| 346 |
+
return (
|
| 347 |
+
<option key={m} value={m}>
|
| 348 |
+
{m}{isRunning ? ' (active)' : ''}
|
| 349 |
+
</option>
|
| 350 |
+
)
|
| 351 |
+
})}
|
| 352 |
</select>
|
| 353 |
</div>
|
| 354 |
|
frontend/src/components/InlineResult.jsx
CHANGED
|
@@ -42,6 +42,7 @@ export default function InlineResult({ error, loading, response, streamingText,
|
|
| 42 |
)}
|
| 43 |
<span className="response-badge" style={{ marginLeft: 'auto' }}>{response.model ?? selectedModel}</span>
|
| 44 |
</div>
|
|
|
|
| 45 |
<div className="inline-result__text">
|
| 46 |
<ReactMarkdown>{response.summary}</ReactMarkdown>
|
| 47 |
</div>
|
|
|
|
| 42 |
)}
|
| 43 |
<span className="response-badge" style={{ marginLeft: 'auto' }}>{response.model ?? selectedModel}</span>
|
| 44 |
</div>
|
| 45 |
+
|
| 46 |
<div className="inline-result__text">
|
| 47 |
<ReactMarkdown>{response.summary}</ReactMarkdown>
|
| 48 |
</div>
|
frontend/src/hooks/useStreaming.js
CHANGED
|
@@ -6,6 +6,7 @@ export function useStreaming() {
|
|
| 6 |
const [response, setResponse] = useState(null)
|
| 7 |
const [error, setError] = useState(null)
|
| 8 |
const [streamingText, setStreamingText] = useState('')
|
|
|
|
| 9 |
const abortRef = useRef(null)
|
| 10 |
// Tracks accumulated text in real-time so cancel() can save it as a response
|
| 11 |
const accumulatedRef = useRef('')
|
|
@@ -81,6 +82,7 @@ export function useStreaming() {
|
|
| 81 |
throw new Error(detail)
|
| 82 |
}
|
| 83 |
|
|
|
|
| 84 |
return readNDJSONStream(res)
|
| 85 |
}
|
| 86 |
|
|
@@ -94,6 +96,7 @@ export function useStreaming() {
|
|
| 94 |
setError(null)
|
| 95 |
setResponse(null)
|
| 96 |
setStreamingText('')
|
|
|
|
| 97 |
accumulatedRef.current = ''
|
| 98 |
|
| 99 |
try {
|
|
@@ -115,22 +118,29 @@ export function useStreaming() {
|
|
| 115 |
if (submitIdRef.current !== myId) return // superseded by a newer submit
|
| 116 |
setResponse({ summary, success: true, source_type: activeTab, model: selectedModel })
|
| 117 |
} catch (err) {
|
| 118 |
-
if (submitIdRef.current !== myId) return // superseded
|
| 119 |
if (err.name === 'AbortError') {
|
| 120 |
-
// User cancelled
|
| 121 |
const partial = accumulatedRef.current.trim()
|
| 122 |
if (partial) {
|
| 123 |
-
setResponse({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
}
|
| 125 |
// If nothing was generated yet, just reset silently (no error shown)
|
| 126 |
return
|
| 127 |
}
|
| 128 |
setError(err.message || 'An error occurred')
|
| 129 |
} finally {
|
| 130 |
-
// Only the current submit should clear loading
|
| 131 |
if (submitIdRef.current === myId) {
|
| 132 |
setLoading(false)
|
| 133 |
setStreamingText('')
|
|
|
|
| 134 |
}
|
| 135 |
}
|
| 136 |
}
|
|
@@ -139,5 +149,5 @@ export function useStreaming() {
|
|
| 139 |
abortRef.current?.abort()
|
| 140 |
}
|
| 141 |
|
| 142 |
-
return { loading, response, error, streamingText, submit, cancel }
|
| 143 |
}
|
|
|
|
| 6 |
const [response, setResponse] = useState(null)
|
| 7 |
const [error, setError] = useState(null)
|
| 8 |
const [streamingText, setStreamingText] = useState('')
|
| 9 |
+
const [isGenerating, setIsGenerating] = useState(false)
|
| 10 |
const abortRef = useRef(null)
|
| 11 |
// Tracks accumulated text in real-time so cancel() can save it as a response
|
| 12 |
const accumulatedRef = useRef('')
|
|
|
|
| 82 |
throw new Error(detail)
|
| 83 |
}
|
| 84 |
|
| 85 |
+
setIsGenerating(true)
|
| 86 |
return readNDJSONStream(res)
|
| 87 |
}
|
| 88 |
|
|
|
|
| 96 |
setError(null)
|
| 97 |
setResponse(null)
|
| 98 |
setStreamingText('')
|
| 99 |
+
setIsGenerating(false)
|
| 100 |
accumulatedRef.current = ''
|
| 101 |
|
| 102 |
try {
|
|
|
|
| 118 |
if (submitIdRef.current !== myId) return // superseded by a newer submit
|
| 119 |
setResponse({ summary, success: true, source_type: activeTab, model: selectedModel })
|
| 120 |
} catch (err) {
|
| 121 |
+
if (submitIdRef.current !== myId) return // superseded: don't touch state
|
| 122 |
if (err.name === 'AbortError') {
|
| 123 |
+
// User cancelled: keep whatever was generated so far as the result
|
| 124 |
const partial = accumulatedRef.current.trim()
|
| 125 |
if (partial) {
|
| 126 |
+
setResponse({
|
| 127 |
+
summary: partial,
|
| 128 |
+
success: true,
|
| 129 |
+
source_type: activeTab,
|
| 130 |
+
model: selectedModel,
|
| 131 |
+
cancelled: true
|
| 132 |
+
})
|
| 133 |
}
|
| 134 |
// If nothing was generated yet, just reset silently (no error shown)
|
| 135 |
return
|
| 136 |
}
|
| 137 |
setError(err.message || 'An error occurred')
|
| 138 |
} finally {
|
| 139 |
+
// Only the current submit should clear loading: stale ones must not interfere
|
| 140 |
if (submitIdRef.current === myId) {
|
| 141 |
setLoading(false)
|
| 142 |
setStreamingText('')
|
| 143 |
+
setIsGenerating(false)
|
| 144 |
}
|
| 145 |
}
|
| 146 |
}
|
|
|
|
| 149 |
abortRef.current?.abort()
|
| 150 |
}
|
| 151 |
|
| 152 |
+
return { loading, response, error, streamingText, isGenerating, submit, cancel }
|
| 153 |
}
|