Skip to content

Instantly share code, notes, and snippets.

@psymonryan
Created November 11, 2026 01:38
Show Gist options
  • Select an option

  • Save psymonryan/2a3f8a26d99519cde74acc60a0922272 to your computer and use it in GitHub Desktop.

Select an option

Save psymonryan/2a3f8a26d99519cde74acc60a0922272 to your computer and use it in GitHub Desktop.
Semantic Chunker - small local model on long transcripts
#!/opt/local/bin/uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "langchain-openai>=0.3.27",
# "python-dotenv>=1.1.1",
# "scikit-learn>=1.8.0",
# "numpy>=2.3.3",
# ]
# ///
#
# MIT License
#
# Copyright (c) 2026 Simon Ryan
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Semantic Chunker CLI — convert a transcript into structured markdown.
Takes a transcript text file, splits it into paragraph-based chunks, sends
each chunk to an LLM to extract structured dotpoints with cross-chunk topic
continuity, and produces a single markdown document.
Usage:
./semantic_chunker.py <input_file> [options]
Examples:
# Basic usage with defaults (c10 provider, deepcogito-cogito-v1-preview-qwen-32B-8bit)
./semantic_chunker.py transcript.txt
# Specify output file and chunk size
./semantic_chunker.py transcript.txt -o output.md --chunk-size 2000
# Use a different provider
./semantic_chunker.py transcript.txt --provider green:9292
# Use a different model
./semantic_chunker.py transcript.txt -m gptoss
# Use compressed prompt (condenses content)
./semantic_chunker.py transcript.txt --compressed
# Verbose output (stream LLM responses)
./semantic_chunker.py transcript.txt -v
"""
import argparse
import os
import re
import sys
import time
from pathlib import Path
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULT_PROVIDER = "c10"
# DEFAULT_MODEL = "cogito-v1-preview-qwen-32B"
DEFAULT_MODEL = "deepcogito-cogito-v1-preview-qwen-32B-8bit"
DEFAULT_CHUNK_SIZE = 1000
DEFAULT_TIMEOUT = 60 * 8 # 8 minutes per chunk
# Provider hostnames (port defaults to 8012)
PROVIDERS = {
"c144": "http://c144:8012/v1",
"c10": "http://c10:8111/v1",
"green": "http://green:9292/v1",
}
# ---------------------------------------------------------------------------
# Prompts (from the notebook's final chosen configuration)
# ---------------------------------------------------------------------------
PROMPT_NON_COMPRESSED = """
You are an expert in topic identification. You never talk in the third person.
- Divide text into a small number of clearly distinct subtopics. For each:
- Condense to a single terse sentence using only original voice/phrasing.
- List each original sentence as its own separate dot point. Each dot point must be exactly one sentence. Do not merge multiple sentences into a single dot point.
The format to use is:
## [Subtopic heading]
[Condensed subtopic non-third person sentence]
- [single sentence]
- [single sentence]
- [single sentence]
- ...
## ...
"""
PROMPT_COMPRESSED = """
You are an expert in condensing and compressing content. You never talk in the third person.
- Clean the material: remove repeated phrases, correct grammar, remove non-semantic artifacts (e.g., 'yeah', 'um', 'ah', 'like'). Do not reword.
- Divide into a small number of clearly distinct subtopics. For each:
- Condense to a single terse sentence using only original phrases.
- List each cleaned original sentence as its own separate dot point. Each dot point must be exactly one sentence. Do not merge multiple sentences into a single dot point.
The format to use is:
## [Subtopic heading]
[Condensed subtopic sentence]
- [single sentence]
- [single sentence]
- [single sentence]
- ...
## ...
"""
PROMPT_EXTENSION = """
Before you start, read the following text. If the new content is a direct continuation of the same subtopic, repeat the previous topic and add new dotpoints to it. If the content clearly moves to a new or different subtopic, start with a new Subtopic heading. Do not force new content into the previous subtopic if it does not belong there.
"""
# ---------------------------------------------------------------------------
# Utility functions (from local_utils.py)
# ---------------------------------------------------------------------------
def dedupe_string(text: str) -> str:
"""Remove consecutive duplicate substrings (limited to repeats under 100 chars)."""
pattern = re.compile(r"(\b.{1,99}?\b)\1+", flags=re.IGNORECASE)
return pattern.sub(r"\1", text)
def chunk_to_sentences(chunk: str) -> list[str]:
"""Convert a markdown-style text chunk into a list of plain sentences.
Removes list markers, markdown emphasis, surrounding quotes, and leading
header markers. Splits on newlines after deduplicating consecutive ones.
"""
# Remove leading markdown header markers
chunk = re.sub(r"^\s*#{1,3}\s+", "", chunk, flags=re.MULTILINE)
# Remove list markers
chunk = re.sub(r"^\s*[-*+]\s+", "", chunk, flags=re.MULTILINE)
# Remove markdown emphasis
chunk = re.sub(r"[*_`]", "", chunk)
# Remove surrounding quotes from each line
chunk = re.sub(r'(^|[\s])"([^"]+)"', r"\1\2", chunk)
# Deduplicate consecutive newlines
chunk = re.sub(r"\n{2,}", "\n", chunk)
# Split into sentences on newlines
sentences = [s.strip() for s in chunk.split("\n") if s.strip()]
return sentences
def reconstruct_markdown_from_sentence_chunks(sentence_chunks: list[str]) -> str:
"""Reconstruct markdown from a list of plain sentences.
1) First sentence → level 2 heading
2) Second sentence → plain paragraph with blank lines
3) Remaining sentences → dashed dotpoints
"""
if not sentence_chunks:
return ""
heading = f"## {sentence_chunks[0]}"
if len(sentence_chunks) >= 2:
paragraph = f"\n\n{sentence_chunks[1]}\n\n"
else:
paragraph = ""
dotpoints = [f"- {sentence}" for sentence in sentence_chunks[2:]]
dotpoints_section = "\n".join(dotpoints) if dotpoints else ""
return f"{heading}{paragraph}{dotpoints_section}"
def compare_sentences_tfidf(sentences: list[list[str]], combine: bool = True) -> float:
"""Compare two lists of sentences using TF-IDF cosine similarity.
Args:
sentences: [list1, list2] of sentences to compare.
combine: If True, join each list into one string before comparing.
Returns:
Average similarity score between 0.0 and 1.0.
"""
sentences1, sentences2 = sentences
if combine:
sentences1 = [" ".join(sentences1)]
sentences2 = [" ".join(sentences2)]
else:
if not sentences1 or not sentences2 or len(sentences1) != len(sentences2):
return 0.0
vectorizer = TfidfVectorizer()
all_sentences = sentences1 + sentences2
try:
tfidf_matrix = vectorizer.fit_transform(all_sentences)
except ValueError:
# "empty vocabulary" — the inputs contain no comparable tokens (e.g. a
# topic with only a heading and summary, so both sides are blank).
# Nothing to compare means no similarity.
return 0.0
sentences1_vectors = tfidf_matrix[: len(sentences1)]
sentences2_vectors = tfidf_matrix[len(sentences1):]
similarities = []
for i in range(len(sentences1)):
similarity = cosine_similarity(
sentences1_vectors[i: i + 1], sentences2_vectors[i: i + 1]
)[0][0]
similarities.append(similarity)
return float(np.mean(similarities))
def topic_splitter(topics_text: str) -> list[str]:
"""Split a markdown document with level2 headers into separate topics."""
return ["## " + x for x in topics_text.split("## ") if x]
# ---------------------------------------------------------------------------
# LLM interaction (from local_utils.ask_model)
# ---------------------------------------------------------------------------
def ask_model(
model_name: str,
system_prompt: str,
user_prompt: str,
base_url: str,
api_key: str,
verbose: bool = False,
timeout_seconds: int = DEFAULT_TIMEOUT,
max_retries: int = 2,
reasoning_effort: str | None = None,
) -> str:
"""Ask the LLM with timeout protection and automatic retry.
Temperature starts at 0 and increases on retry (0.5, then 0.9).
"""
temperatures = [0, 0.5, 0.9]
for attempt in range(max_retries + 1):
temperature = temperatures[min(attempt, len(temperatures) - 1)]
llm_kwargs = {
"model": model_name,
"temperature": temperature,
"openai_api_base": base_url,
"openai_api_key": api_key,
}
# Only send reasoning_effort when explicitly asked for. It is not a
# standard OpenAI parameter, and endpoints that don't understand it
# reject the whole request with a 400.
if reasoning_effort:
llm_kwargs["reasoning_effort"] = reasoning_effort
llm = ChatOpenAI(**llm_kwargs)
messages = [("system", system_prompt), ("human", user_prompt)]
result = ""
start_time = time.time()
timed_out = False
try:
stream = llm.stream(messages)
if verbose:
print(f"\n[Attempt {attempt + 1}/{max_retries + 1}, temperature={temperature}]\n")
for chunk in stream:
result += chunk.content
if verbose:
print(chunk.content, flush=True, end="")
if timeout_seconds is not None:
elapsed = time.time() - start_time
if elapsed > timeout_seconds:
if verbose:
last_50 = result[-50:] if len(result) >= 50 else result
print(f"\n[TIMEOUT after {elapsed:.1f}s - cutting off generation]")
print(f"[Last 50 chars: ...{repr(last_50)}]")
timed_out = True
break
except Exception as e:
# Always surface errors on stderr (not just in verbose mode) so
# callers running us as a subprocess can diagnose failures.
print(
f"\n[Error on attempt {attempt + 1}/{max_retries + 1}: "
f"{type(e).__name__}: {e}]",
file=sys.stderr,
)
if attempt == max_retries:
raise
continue
if not timed_out:
result = result.replace("<think", "", 1)
return result
if attempt < max_retries and verbose:
print("\n[Retrying with increased temperature...]")
# All retries exhausted — return partial result
result = result.replace("<think", "", 1)
if verbose:
print(f"\n[Returning partial result after {max_retries + 1} attempts]")
return result
# ---------------------------------------------------------------------------
# Core processing logic
# ---------------------------------------------------------------------------
def _join_lines(text: str) -> str:
"""Join line-wrapped text into a continuous stream."""
return re.sub(r"\s*\n\s*", " ", text)
def _split_into_sentences(text: str) -> list[str]:
"""Split text into sentences using punctuation boundaries."""
pattern = r"(?<=[.!?])\s+(?=[A-Z])"
sentences = re.split(pattern, text)
return [s.strip() for s in sentences if s.strip()]
def _group_sentences_into_chunks(
sentences: list[str], target_chunk_size: int
) -> list[str]:
"""Group sentences into chunks of approximately target_chunk_size chars."""
chunks: list[str] = []
current: list[str] = []
current_size = 0
for sentence in sentences:
sentence_size = len(sentence) + 1
if current and current_size + sentence_size > target_chunk_size:
chunks.append(" ".join(current))
current = []
current_size = 0
current.append(sentence)
current_size += sentence_size
if current:
chunks.append(" ".join(current))
return chunks
def split_text_into_chunks(file_content: str, min_chunk_size: int) -> list[str]:
"""Split text into sentence-aware chunks.
1. Join line-wrapped text into a continuous stream.
2. Tokenize into sentences on punctuation boundaries.
3. Group sentences into chunks of ~min_chunk_size chars.
"""
continuous = _join_lines(file_content)
sentences = _split_into_sentences(continuous)
chunks = _group_sentences_into_chunks(sentences, min_chunk_size)
print(f"Sentences: {len(sentences)}, Chunks: {len(chunks)}", file=sys.stderr)
return chunks
def process_chunks(
docs: list[str],
model_name: str,
base_url: str,
api_key: str,
system_prompt: str,
verbose: bool = False,
reasoning_effort: str | None = None,
) -> list[list[str]]:
"""Process each chunk through the LLM and assemble topics.
Handles cross-chunk continuity: on each iteration after the first, the
last topic from the previous chunk is passed to the LLM as an extension
prompt. If the LLM moves on to a new topic (detected via low TF-IDF
similarity), the previous topic is kept separately.
Returns a list of topics, where each topic is a list of plain sentences.
"""
topics: list[list[str]] = []
for idx, doc in enumerate(docs):
_last_topic_md = ""
_last_topic: list[str] = []
if idx == 0 or not topics:
# Nothing accumulated yet (first chunk, or every earlier chunk came
# back empty) — no previous topic to extend.
_extend_prompt = ""
else:
_last_topic = topics[-1]
_last_topic_md = reconstruct_markdown_from_sentence_chunks(_last_topic)
_extend_prompt = PROMPT_EXTENSION + "\n---\n" + _last_topic_md + "\n---\n"
# Remove last topic; trust that next iteration preserves it (or we add it back)
topics.pop()
print(f"\n{'=' * 60}", file=sys.stderr)
print(f"Processing chunk {idx + 1}/{len(docs)} ({len(doc)} chars)", file=sys.stderr)
print(f"{'=' * 60}", file=sys.stderr)
all_topics = ask_model(
model_name,
system_prompt + _extend_prompt,
doc,
base_url,
api_key,
verbose=verbose,
timeout_seconds=DEFAULT_TIMEOUT,
reasoning_effort=reasoning_effort,
)
_split_topics = topic_splitter(all_topics)
if not _split_topics:
# The model returned nothing usable (empty response, or it timed out
# before emitting a "## " heading). Don't crash the whole run over
# one bad chunk — restore the topic we popped and move on.
print(
f" [Warning] no topics parsed from chunk {idx + 1}; skipping it",
file=sys.stderr,
)
if idx != 0 and _last_topic:
topics.append(_last_topic)
continue
_first_topic = chunk_to_sentences(_split_topics[0])
if idx != 0 and _last_topic:
# Compare first few sentences of new first topic vs last topic
# Skip heading (0) and summary (1), compare sentences 2-5
_sstart = 2
_send = 6
_compare = [
_first_topic[_sstart:_send],
_last_topic[_sstart:_send],
]
_score = compare_sentences_tfidf(_compare)
print(f" Similarity score: tfidf={_score:.2f}", file=sys.stderr)
# If low similarity, the LLM moved on — keep the skipped topic
if _score < 0.5:
print(" → Keeping skipped subtopic (topic changed)", file=sys.stderr)
topics.extend([chunk_to_sentences(_last_topic_md)])
topics.extend([chunk_to_sentences(topic) for topic in _split_topics])
# Graceful stop: create a file called 'stop' in the current directory
if os.path.isfile("stop"):
print("\n[Stop file detected — breaking out gracefully]", file=sys.stderr)
os.unlink("stop")
break
return topics
# ---------------------------------------------------------------------------
# Provider resolution
# ---------------------------------------------------------------------------
def resolve_provider(provider_arg: str | None) -> str:
"""Resolve a provider argument into a base URL.
Accepts:
- Known provider name: "c144", "c10", "green"
- Provider with port: "c144:8012", "green:9292"
- Full URL: "http://c144:8012/v1"
"""
if provider_arg is None:
return PROVIDERS[DEFAULT_PROVIDER]
# Full URL
if provider_arg.startswith("http://") or provider_arg.startswith("https://"):
return provider_arg
# Provider name with optional port
if ":" in provider_arg:
name, port = provider_arg.split(":", 1)
else:
name = provider_arg
port = None
# Try exact match first
if name in PROVIDERS:
base_url = PROVIDERS[name]
if port:
# Replace the port in the URL
base_url = re.sub(r":\d+/", f":{port}/", base_url)
return base_url
# Unknown provider — treat as hostname
if port:
return f"http://{name}:{port}/v1"
else:
return f"http://{name}:8012/v1"
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Semantic chunker: convert a transcript into structured markdown.",
)
parser.add_argument("input_file", help="Path to the transcript text file")
parser.add_argument(
"-o", "--output", help="Output markdown file path (default: <input>.md)"
)
parser.add_argument(
"-m",
"--model",
default=DEFAULT_MODEL,
help=f"LLM model name (default: {DEFAULT_MODEL})",
)
parser.add_argument(
"--provider",
default=None,
help=f"Model provider: name (c144, c10, green), name:port, or full URL (default: {DEFAULT_PROVIDER})",
)
parser.add_argument(
"--chunk-size",
type=int,
default=DEFAULT_CHUNK_SIZE,
help=f"Minimum chunk size in characters (default: {DEFAULT_CHUNK_SIZE})",
)
parser.add_argument(
"--compressed",
action="store_true",
help="Use compressed prompt (condenses content, removes artifacts)",
)
parser.add_argument(
"--reasoning-effort",
default=None,
choices=["low", "medium", "high"],
help="Send a reasoning_effort hint to the model. Omitted by default, "
"because most non-reasoning endpoints reject it with a 400.",
)
parser.add_argument(
"--env-file",
default=None,
help="Path to .env file to load (default: ~/.env then ./.env)",
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Verbose output (stream LLM responses)",
)
args = parser.parse_args()
# --- Load environment ---
# .env files may only FILL IN variables not already set in the real
# environment (e.g. docker `environment:`) — a stray .env with
# OPENAI_API_KEY=dummy must not clobber the key we actually send.
# Precedence: real env > ./.env > ~/.env
if args.env_file:
load_dotenv(args.env_file, override=False)
else:
if Path(".env").exists():
load_dotenv(".env", override=False)
load_dotenv(os.path.expanduser("~/.env"), override=False)
else:
load_dotenv(os.path.expanduser("~/.env"), override=False)
# --- Resolve provider ---
base_url = resolve_provider(args.provider)
# No hardcoded fallback: a default key in the source would be a credential
# published with the code. Local OpenAI-compatible servers usually ignore
# the key, but they still need a non-empty one — any value will do there.
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
print(
"Error: OPENAI_API_KEY is not set.\n"
" Export it, or put it in ./.env or ~/.env.\n"
" For a local server that ignores auth, any value works:\n"
" export OPENAI_API_KEY=local",
file=sys.stderr,
)
sys.exit(1)
model_name = args.model
# --- Read input ---
input_path = Path(args.input_file)
if not input_path.exists():
print(f"Error: file not found: {input_path}", file=sys.stderr)
sys.exit(1)
print(f"Reading: {input_path}", file=sys.stderr)
with open(input_path, "r", encoding="utf-8") as f:
file_content = dedupe_string(f.read())
word_count = len(file_content.split())
print(f" Size: {len(file_content)} bytes, {word_count} words", file=sys.stderr)
# --- Select prompt ---
system_prompt = PROMPT_COMPRESSED if args.compressed else PROMPT_NON_COMPRESSED
prompt_type = "compressed" if args.compressed else "non-compressed"
print(f" Prompt: {prompt_type}", file=sys.stderr)
print(f" Model: {model_name}", file=sys.stderr)
print(f" Provider: {base_url}", file=sys.stderr)
print(f" Chunk size: {args.chunk_size}", file=sys.stderr)
# Confirm a key is present without echoing any part of it.
print(f" API key: set (len {len(api_key)})", file=sys.stderr)
# --- Split into chunks ---
docs = split_text_into_chunks(file_content, args.chunk_size)
# --- Process through LLM ---
topics = process_chunks(
docs,
model_name=model_name,
base_url=base_url,
api_key=api_key,
system_prompt=system_prompt,
verbose=args.verbose,
reasoning_effort=args.reasoning_effort,
)
# --- Reconstruct markdown ---
sections_document = "\n\n".join(
[reconstruct_markdown_from_sentence_chunks(chunk) for chunk in topics]
)
# --- Write output ---
output_path = Path(args.output) if args.output else input_path.with_suffix(".md")
with open(output_path, "w", encoding="utf-8") as f:
f.write(sections_document)
print(f"\n{'=' * 60}", file=sys.stderr)
print(f"Done! Output written to: {output_path}", file=sys.stderr)
print(f" {len(topics)} topics extracted", file=sys.stderr)
print(f" {len(sections_document)} bytes output", file=sys.stderr)
print(f"{'=' * 60}", file=sys.stderr)
if __name__ == "__main__":
main()
@psymonryan

psymonryan commented Nov 14, 2026 •

Copy link
Copy Markdown
Author

This is useful for 'summarising' a long transcript (eg: a Meeting) even if you are using a small local model without much context.

I've chosen the deepcogito-cogito-v1-preview-qwen-32B model as it is one of the very few instruction tuned models that can reliably preserve the original 'voice' rather than summarising as a third person.

It also preserves the sentances as verbatim dot points (unless you use the compress option)
I find this is a great way to review a meeting and them copy paste the 'in original voice' parts into my actual notes so it reads as a summary by the person that made the comment.

There is nothing worse than summarisers that give you vauge third person summaries like: "The speaker discussed... some vague topic" - what we want from a summariser is not a summary that loses what was said, we want "what was said" in "the way it was said" (but with less surrounding fluff)

It also 'chunks' since most models suffer from 'lost in the middle' issues. By chunking with overlap this code also tries to preserve topics across chunk boundaries using some simple techniques. This is not perfect, but it is good enough to turn lecture or meeting notes into a reliable summary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment