API reference · Kjarni 0.2.7

kjarni

Kjarni: run transformer models inside your program.

Embeddings, classification, reranking, search, chat, speech-to-text, summarization, translation and image search, on a native engine whose output matches PyTorch. Models download on first use and are cached, so everything after that works offline.

from kjarni import Embedder

e = Embedder("minilm-l6-v2")
print(e.similarity("doctor", "physician"))  # 0.8598

Modules:

  • chat – High-level Chat API.
  • classifier – High-level Classifier API.
  • embedder – High-level Embedder API.
  • image_index – High-level image search API.
  • indexer – High-level Indexer API for Kjarni.
  • reranker – High-level Reranker API.
  • searcher – High-level Searcher API for Kjarni.
  • summarizer – High-level Summarizer API.
  • transcriber – High-level Transcriber API.
  • translator – High-level Translator API.

Classes:

  • CancelToken – Token to cancel long-running operations.
  • Chat – Chat with a local language model.
  • Classifier – Text classification model.
  • Conversation – A conversation whose history is kept by the engine between messages.
  • Embedder – Text embedding model.
  • ImageHit – An image matching a search.
  • ImageIndex – Photos searched by description, with CLIP.
  • IndexInfo – Information about an existing index.
  • IndexStats – Statistics returned after indexing operations.
  • Indexer – Document indexer for RAG applications.
  • KjarniException – Exception raised by Kjarni operations.
  • Progress – Progress update during indexing operations.
  • RerankResult – Single rerank result.
  • Reranker – Text reranking model using cross-encoders.
  • ScanReport – What scanning a directory did.
  • SearchMode – Search mode determining how queries are processed.
  • SearchResult – A single search result.
  • Searcher – Document searcher for RAG applications.
  • Segment – One timed piece of a transcript, in seconds from the start.
  • Summarizer – Summarizes article-length text.
  • Transcriber – Speech to text with Whisper.
  • Transcript – The result of transcribing audio.
  • Translator – Translates text between languages.
  • Turn – One message of a transcript: role is "system", "user" or "assistant".

Functions:

  • version – Get Kjarni version.

kjarni.CancelToken

CancelToken()

Token to cancel long-running operations.

Create a token and pass it to indexing operations. Call cancel() from another thread to request cancellation.

Example

token = CancelToken()

In another thread:

token.cancel()

The indexing operation will stop and raise an exception

Functions:

  • cancel – Request cancellation of the associated operation.
  • reset – Reset the token for reuse with another operation.

Attributes:

  • is_cancelled (bool) – Check if cancellation has been requested.

kjarni.CancelToken.cancel

cancel()

Request cancellation of the associated operation.

kjarni.CancelToken.is_cancelled

is_cancelled: bool

Check if cancellation has been requested.

kjarni.CancelToken.reset

reset()

Reset the token for reuse with another operation.

kjarni.Chat

Chat(model, system_prompt=None, mode='default', device='cpu', cache_dir=None, quiet=False, quantized=False)

Chat with a local language model.

Example

chat = Chat("qwen2.5-0.5b-instruct") print(chat.send("What is the capital of France?")) chat.stream("Tell me a story", on_token=lambda t: print(t, end="", flush=True))

Functions:

  • conversation – Start a conversation that keeps its own history.
  • send – Send one message and return the whole reply. Keeps no history.
  • send_with_history – Reply to message given prior (role, content) turns, oldest first.
  • stream – Stream a reply, calling on_token with each piece; return False from it to stop.
  • stream_with_history – send_with_history, streamed through on_token.

Attributes:

  • context_size (int) –
  • model_name (str) –

Parameters:

  • model (str) – e.g. "qwen2.5-0.5b-instruct" or "llama3.2-1b-instruct"
  • system_prompt (Optional[str]) – Instructions for the assistant
  • mode (str) – "default", "creative" or "reasoning"
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • quiet (bool) – Suppress progress output
  • quantized (bool) – Load the 4-bit GGUF weights instead of full precision: a fraction of the memory and several times faster to generate on a CPU

kjarni.Chat.context_size

context_size: int

kjarni.Chat.conversation

conversation()

Start a conversation that keeps its own history.

kjarni.Chat.model_name

model_name: str

kjarni.Chat.send

send(message, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

Send one message and return the whole reply. Keeps no history.

kjarni.Chat.send_with_history

send_with_history(history, message, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

Reply to message given prior (role, content) turns, oldest first.

For callers that own the transcript and replay it every turn. A system turn replaces the system prompt given at construction.

kjarni.Chat.stream

stream(message, on_token=None, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

Stream a reply, calling on_token with each piece; return False from it to stop.

Returns the text generated, including the piece that stopped it.

kjarni.Chat.stream_with_history

stream_with_history(history, message, on_token=None, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

send_with_history, streamed through on_token.

kjarni.Classifier

Classifier(model, device='cpu', cache_dir=None, labels=None, multi_label=False, quiet=False)

Text classification model.

Example

classifier = Classifier("distilbert-sentiment") result = classifier.classify("I love this product!") print(result.label, result.score) POSITIVE 0.9998

Functions:

  • classify – Classify a single text.
  • classify_batch – Classify several texts in one call, which is much faster than one at a time.

Attributes:

  • device (str) – Get the device (cpu or gpu).
  • has_custom_labels (bool) – Check if using custom labels.
  • model_id (str) – Get the model identifier.
  • num_labels (int) – Get number of classification labels.

Parameters:

  • model (str) – Model name (e.g., "distilbert-sentiment", "roberta-sentiment")
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • labels (Optional[List[str]]) – Custom labels (overrides model defaults)
  • multi_label (bool) – Enable multi-label classification (sigmoid vs softmax)
  • quiet (bool) – Suppress progress output

kjarni.Classifier.classify

classify(text)

Classify a single text.

Parameters:

  • text (str) – Input text

Returns:

  • ClassificationResult – ClassificationResult with label, score, and all_scores

kjarni.Classifier.classify_batch

classify_batch(texts)

Classify several texts in one call, which is much faster than one at a time.

Parameters:

  • texts (List[str]) – Input texts

Returns:

  • List[ClassificationResult] – One ClassificationResult per text, in order

kjarni.Classifier.device

device: str

Get the device (cpu or gpu).

kjarni.Classifier.has_custom_labels

has_custom_labels: bool

Check if using custom labels.

kjarni.Classifier.model_id

model_id: str

Get the model identifier.

kjarni.Classifier.num_labels

num_labels: int

Get number of classification labels.

kjarni.Conversation

Conversation(chat)

A conversation whose history is kept by the engine between messages.

Functions:

  • clear – Forget the history, keeping the system prompt unless told otherwise.
  • send – Send a message and return the whole reply. Both are added to the history.
  • stream – Stream a reply through on_token, as Chat.stream does, and add both to the history.

kjarni.Conversation.clear

clear(keep_system=True)

Forget the history, keeping the system prompt unless told otherwise.

kjarni.Conversation.send

send(message, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

Send a message and return the whole reply. Both are added to the history.

kjarni.Conversation.stream

stream(message, on_token=None, *, temperature=None, top_k=None, top_p=None, min_p=None, repetition_penalty=None, max_new_tokens=None, do_sample=None)

Stream a reply through on_token, as Chat.stream does, and add both to the history.

kjarni.Embedder

Embedder(model=None, device='cpu', cache_dir=None, normalize=True, quiet=False)

Text embedding model.

Example

embedder = Embedder() embedding = embedder.encode("Hello, world!") print(len(embedding)) 384

sim = embedder.similarity("cat", "dog") print(f"Similarity: {sim:.3f}")

Functions:

  • encode – Encode a single text to an embedding vector.
  • encode_batch – Encode multiple texts.
  • similarity – Compute cosine similarity between two texts.

Attributes:

  • dim (int) – Get the embedding dimension.

Parameters:

  • model (Optional[str]) – Model name (e.g., "minilm-l6-v2", "mpnet-base-v2")
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • normalize (bool) – L2-normalize embeddings
  • quiet (bool) – Suppress progress output

kjarni.Embedder.dim

dim: int

Get the embedding dimension.

kjarni.Embedder.encode

encode(text)

Encode a single text to an embedding vector.

Parameters:

  • text (str) – Input text

Returns:

  • List[float] – Embedding vector as list of floats

kjarni.Embedder.encode_batch

encode_batch(texts)

Encode multiple texts.

Parameters:

  • texts (Sequence[str]) – List of input texts

Returns:

  • ndarray | list[list[float]] – One vector per text: a (len(texts), dim) array when numpy is installed, otherwise a list of lists.

kjarni.Embedder.similarity

similarity(text1, text2)

Compute cosine similarity between two texts.

Parameters:

  • text1 (str) – First text
  • text2 (str) – Second text

Returns:

  • float – Cosine similarity score (-1 to 1)

kjarni.ImageHit

Bases: NamedTuple

An image matching a search.

Attributes:

  • path (str) –
  • score (float) –

kjarni.ImageHit.path

path: str

kjarni.ImageHit.score

score: float

kjarni.ImageIndex

ImageIndex(model_dir=None)

Photos searched by description, with CLIP.

Example

index = ImageIndex() index.add_directory("~/Pictures") for hit in index.search("a dog on a beach", top_k=5): ... print(hit.path)

Functions:

  • add – Index one JPEG or PNG.
  • add_directory – Index every JPEG and PNG under directory.
  • load – Restore vectors written by save; returns how many.
  • save – Write the vectors (not the images) to path.
  • search – The top_k images best matching query.

Parameters:

  • model_dir (Optional[str]) – A CLIP model directory; None uses clip-vit-base-32, downloaded on first use

kjarni.ImageIndex.add

add(path)

Index one JPEG or PNG.

kjarni.ImageIndex.add_directory

add_directory(directory)

Index every JPEG and PNG under directory.

kjarni.ImageIndex.load

load(path)

Restore vectors written by save; returns how many.

kjarni.ImageIndex.save

save(path)

Write the vectors (not the images) to path.

search(query, top_k=10)

The top_k images best matching query.

kjarni.IndexInfo

IndexInfo(path, document_count, segment_count, dimension, size_bytes, embedding_model)

Information about an existing index.

Attributes:

  • path (str) – Path to the index directory
  • document_count (int) – Total number of documents in the index
  • segment_count (int) – Number of index segments
  • dimension (int) – Embedding dimension
  • size_bytes (int) – Total size on disk
  • embedding_model (Optional[str]) – Name of embedding model used (may be None)

kjarni.IndexInfo.dimension

dimension: int

kjarni.IndexInfo.document_count

document_count: int

kjarni.IndexInfo.embedding_model

embedding_model: Optional[str]

kjarni.IndexInfo.path

path: str

kjarni.IndexInfo.segment_count

segment_count: int

kjarni.IndexInfo.size_bytes

size_bytes: int

kjarni.IndexStats

IndexStats(documents_indexed, chunks_created, dimension, size_bytes, files_processed, files_skipped, elapsed_ms)

Statistics returned after indexing operations.

Attributes:

  • documents_indexed (int) – Number of document chunks indexed (after splitting)
  • chunks_created (int) – Number of chunks created from source files
  • dimension (int) – Embedding dimension used
  • size_bytes (int) – Total index size on disk
  • files_processed (int) – Number of source files successfully processed
  • files_skipped (int) – Number of files skipped (errors, unsupported, too large)
  • elapsed_ms (int) – Total time taken in milliseconds

kjarni.IndexStats.chunks_created

chunks_created: int

kjarni.IndexStats.dimension

dimension: int

kjarni.IndexStats.documents_indexed

documents_indexed: int

kjarni.IndexStats.elapsed_ms

elapsed_ms: int

kjarni.IndexStats.files_processed

files_processed: int

kjarni.IndexStats.files_skipped

files_skipped: int

kjarni.IndexStats.size_bytes

size_bytes: int

kjarni.Indexer

Indexer(model='minilm-l6-v2', device='cpu', cache_dir=None, chunk_size=512, chunk_overlap=50, batch_size=32, extensions=None, exclude_patterns=None, recursive=True, include_hidden=False, max_file_size=10 * 1024 * 1024, quiet=False)

Document indexer for RAG applications.

The Indexer creates and manages vector indexes from text documents. Documents are split into chunks, embedded using a sentence transformer model, and stored in an efficient vector index for similarity search.

Parameters:

  • model (str) – Embedding model name (default: "minilm-l6-v2")
  • device (str) – Compute device - "cpu" or "gpu" (default: "cpu")
  • cache_dir (Optional[str]) – Directory to cache downloaded models (default: system cache)
  • chunk_size (int) – Maximum chunk size in characters (default: 512)
  • chunk_overlap (int) – Overlap between chunks in characters (default: 50)
  • batch_size (int) – Batch size for embedding operations (default: 32)
  • extensions (Optional[List[str]]) – File extensions to include (default: common text formats)
  • exclude_patterns (Optional[List[str]]) – Glob patterns for files to exclude
  • recursive (bool) – Whether to recurse into subdirectories (default: True)
  • include_hidden (bool) – Whether to include hidden files (default: False)
  • max_file_size (int) – Skip files larger than this in bytes (default: 10MB)
  • quiet (bool) – Suppress progress output to stderr (default: False)
Example

indexer = Indexer(model="minilm-l6-v2", chunk_size=256) stats = indexer.create("my_index", ["documents/"]) print(f"Created index with {stats.documents_indexed} chunks")

Functions:

  • add – Add documents to an existing index.
  • create – Create a new index from files/directories.
  • delete – Delete an index.
  • info – Get information about an existing index.

Attributes:

  • chunk_size (int) – Get the configured chunk size in characters.
  • dimension (int) – Get the embedding dimension produced by the model.
  • model_name (str) – Get the embedding model name used by this indexer.

kjarni.Indexer.add

add(index_path, inputs, on_progress=None, cancel_token=None)

Add documents to an existing index.

Processes additional files and appends them to an existing index. The index must have been created with the same embedding model.

Parameters:

  • index_path (str) – Path to existing index
  • inputs (Sequence[str]) – List of file or directory paths to add
  • on_progress (Optional[Callable[[Progress], None]]) – Optional callback for progress updates
  • cancel_token (Optional[CancelToken]) – Optional token to cancel the operation

Returns:

  • int – Number of document chunks added

Raises:

  • KjarniException – If the index doesn't exist or has incompatible settings
Example

added = indexer.add("my_index", ["new_docs/"]) print(f"Added {added} document chunks")

kjarni.Indexer.chunk_size

chunk_size: int

Get the configured chunk size in characters.

kjarni.Indexer.create

create(index_path, inputs, force=False, on_progress=None, cancel_token=None)

Create a new index from files/directories.

Scans the input paths for supported text files, splits them into chunks, generates embeddings, and stores everything in a vector index.

Parameters:

  • index_path (str) – Path where the index will be created
  • inputs (Sequence[str]) – List of file or directory paths to index
  • force (bool) – If True, overwrite existing index at index_path
  • on_progress (Optional[Callable[[Progress], None]]) – Optional callback for progress updates
  • cancel_token (Optional[CancelToken]) – Optional token to cancel the operation

Returns:

  • IndexStats – IndexStats with information about what was indexed

Raises:

  • ValueError – If inputs is empty
  • KjarniException – If indexing fails
Example

def show_progress(p): ... print(f"{p.stage}: {p.current}/{p.total}") stats = indexer.create("idx", ["docs/"], on_progress=show_progress)

kjarni.Indexer.delete

delete(index_path)

Delete an index.

Permanently removes the index directory and all its contents. This is a static method that doesn't require an Indexer instance.

Parameters:

  • index_path (str) – Path to the index to delete

Raises:

  • KjarniException – If the index doesn't exist or deletion fails
Example

Indexer.delete("my_index")

kjarni.Indexer.dimension

dimension: int

Get the embedding dimension produced by the model.

kjarni.Indexer.info

info(index_path)

Get information about an existing index.

This is a static method that doesn't require an Indexer instance.

Parameters:

  • index_path (str) – Path to the index directory

Returns:

  • IndexInfo – IndexInfo with index statistics and metadata

Raises:

  • KjarniException – If the index doesn't exist or is corrupted
Example

info = Indexer.info("my_index") print(f"Index has {info.document_count} documents") print(f"Using model: {info.embedding_model}")

kjarni.Indexer.model_name

model_name: str

Get the embedding model name used by this indexer.

kjarni.KjarniException

KjarniException(message, code)

Bases: Exception

Exception raised by Kjarni operations.

Attributes:

  • code –

kjarni.KjarniException.code

code = code

kjarni.Progress

Bases: NamedTuple

Progress update during indexing operations.

Attributes:

  • stage (str) – Current operation stage (scanning, loading, embedding, etc.)
  • current (int) – Current item number being processed
  • total (int) – Total items to process (may be 0 if unknown)
  • message (Optional[str]) – Optional status message

kjarni.Progress.current

current: int

kjarni.Progress.message

message: Optional[str]

kjarni.Progress.stage

stage: str

kjarni.Progress.total

total: int

kjarni.RerankResult

Bases: NamedTuple

Single rerank result.

Attributes:

  • document (str) –
  • index (int) –
  • score (float) –

kjarni.RerankResult.document

document: str

kjarni.RerankResult.index

index: int

kjarni.RerankResult.score

score: float

kjarni.Reranker

Reranker(model=None, device='cpu', cache_dir=None, quiet=False)

Text reranking model using cross-encoders.

Example

reranker = Reranker() results = reranker.rerank("What is Python?", [ ... "Python is a programming language", ... "Java is also a language", ... "The weather is nice today" ... ]) for r in results: ... print(f"{r.index}: {r.score:.3f} - {r.document[:30]}...")

Functions:

  • rerank – Rerank documents by relevance to query.
  • rerank_top_k – Rerank and return top-k results.
  • score – Score a single query-document pair.

Parameters:

  • model (Optional[str]) – Model name (e.g., "cross-encoder-minilm")
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • quiet (bool) – Suppress progress output

kjarni.Reranker.rerank

rerank(query, documents)

Rerank documents by relevance to query.

Parameters:

  • query (str) – Query text
  • documents (List[str]) – List of documents to rerank

Returns:

  • List[RerankResult] – List of RerankResult sorted by score (highest first)

kjarni.Reranker.rerank_top_k

rerank_top_k(query, documents, k)

Rerank and return top-k results.

Parameters:

  • query (str) – Query text
  • documents (List[str]) – List of documents to rerank
  • k (int) – Number of top results to return

Returns:

  • List[RerankResult] – Top-k RerankResults sorted by score

kjarni.Reranker.score

score(query, document)

Score a single query-document pair.

Parameters:

  • query (str) – Query text
  • document (str) – Document text

Returns:

  • float – Relevance score (higher = more relevant)

kjarni.ScanReport

Bases: NamedTuple

What scanning a directory did.

Attributes:

  • added (int) –
  • skipped (int) –

kjarni.ScanReport.added

added: int

kjarni.ScanReport.skipped

skipped: int

kjarni.SearchMode

Bases: Enum

Search mode determining how queries are processed.

Attributes:

  • KEYWORD – BM25-based text matching only
  • SEMANTIC – Embedding-based vector similarity only
  • HYBRID – Combined keyword + semantic with reciprocal rank fusion (recommended)

kjarni.SearchMode.HYBRID

HYBRID = KjarniSearchMode.HYBRID

kjarni.SearchMode.KEYWORD

KEYWORD = KjarniSearchMode.KEYWORD

kjarni.SearchMode.SEMANTIC

SEMANTIC = KjarniSearchMode.SEMANTIC

kjarni.SearchResult

SearchResult(score, document_id, text, metadata)

A single search result.

Attributes:

  • score (float) – Relevance score (higher is better, scale varies by search mode)
  • document_id (int) – Document ID within the index
  • text (str) – The matched text chunk
  • metadata (Dict[str, Any]) – Associated metadata (source file, chunk index, custom fields)

kjarni.SearchResult.document_id

document_id: int

kjarni.SearchResult.metadata

metadata: Dict[str, Any]

kjarni.SearchResult.score

score: float

kjarni.SearchResult.text

text: str

kjarni.Searcher

Searcher(model='minilm-l6-v2', device='cpu', cache_dir=None, rerank_model=None, default_mode=SearchMode.HYBRID, default_top_k=10, quiet=False)

Document searcher for RAG applications.

The Searcher performs queries against vector indexes created by the Indexer. It supports three search modes:

  • Keyword: BM25 text matching, good for exact term matching
  • Semantic: Vector similarity, good for conceptual matching
  • Hybrid: Combined approach using reciprocal rank fusion (recommended)

Optionally, a cross-encoder reranker can be configured to improve result quality by re-scoring the top candidates.

Parameters:

  • model (str) – Embedding model name (must match the model used to create the index)
  • device (str) – Compute device - "cpu" or "gpu" (default: "cpu")
  • cache_dir (Optional[str]) – Directory to cache downloaded models (default: system cache)
  • rerank_model (Optional[str]) – Optional cross-encoder model for reranking results
  • default_mode (SearchMode) – Default search mode (default: HYBRID)
  • default_top_k (int) – Default number of results (default: 10)
  • quiet (bool) – Suppress progress output (default: False)
Example

Basic searcher

searcher = Searcher(model="minilm-l6-v2")

Searcher with reranking

searcher = Searcher( ... model="minilm-l6-v2", ... rerank_model="ms-marco-MiniLM-L-6-v2", ... )

Functions:

  • search – Search an index.
  • search_keywords – Static keyword search (BM25) - no embedding model needed.

Attributes:

  • default_mode (SearchMode) – Get the default search mode.
  • default_top_k (int) – Get the default number of results.
  • has_reranker (bool) – Check if a reranker is configured.
  • model_name (str) – Get the embedding model name used by this searcher.
  • reranker_model (Optional[str]) – Get the reranker model name, or None if no reranker is configured.

kjarni.Searcher.default_mode

default_mode: SearchMode

Get the default search mode.

kjarni.Searcher.default_top_k

default_top_k: int

Get the default number of results.

kjarni.Searcher.has_reranker

has_reranker: bool

Check if a reranker is configured.

kjarni.Searcher.model_name

model_name: str

Get the embedding model name used by this searcher.

kjarni.Searcher.reranker_model

reranker_model: Optional[str]

Get the reranker model name, or None if no reranker is configured.

search(index_path, query, mode=None, top_k=None, rerank=None, threshold=None, source_pattern=None, filter_key=None, filter_value=None)

Search an index.

Parameters:

  • index_path (str) – Path to the index directory
  • query (str) – Search query string
  • mode (Optional[SearchMode]) – Search mode (None = use default)
  • top_k (Optional[int]) – Number of results (None = use default)
  • rerank (Optional[bool]) – Use reranker (None = auto, use if configured)
  • threshold (Optional[float]) – Minimum score threshold (results below this are filtered)
  • source_pattern (Optional[str]) – Filter by source file pattern (glob syntax, e.g. "*.md")
  • filter_key (Optional[str]) – Metadata key to filter on
  • filter_value (Optional[str]) – Required value for filter_key

Returns:

  • List[SearchResult] – List of SearchResult objects, sorted by relevance (highest first)

Raises:

  • KjarniException – If the index doesn't exist or search fails
Example

Basic search

results = searcher.search("my_index", "machine learning")

Search with options

results = searcher.search( ... "my_index", ... "neural networks", ... mode=SearchMode.SEMANTIC, ... top_k=5, ... threshold=0.5, ... )

Search with filtering

results = searcher.search( ... "my_index", ... "API reference", ... source_pattern="*.md", ... )

kjarni.Searcher.search_keywords

search_keywords(index_path, query, top_k=10)

Static keyword search (BM25) - no embedding model needed.

This is a convenience method for pure keyword search that doesn't require loading an embedding model. Useful for quick text matching or when you only need BM25 results.

Parameters:

  • index_path (str) – Path to the index directory
  • query (str) – Search query string
  • top_k (int) – Maximum number of results (default: 10)

Returns:

  • List[SearchResult] – List of SearchResult objects, sorted by BM25 score

Raises:

  • KjarniException – If the index doesn't exist or search fails
Example

Quick keyword search without loading embedder

results = Searcher.search_keywords("my_index", "Python tutorial")

kjarni.Segment

Bases: NamedTuple

One timed piece of a transcript, in seconds from the start.

Attributes:

  • end (float) –
  • start (float) –
  • text (str) –

kjarni.Segment.end

end: float

kjarni.Segment.start

start: float

kjarni.Segment.text

text: str

kjarni.Summarizer

Summarizer(model=None, min_length=0, max_length=0, device='cpu', cache_dir=None, quiet=False)

Summarizes article-length text.

Example

summarizer = Summarizer() print(summarizer.summarize(article))

Functions:

  • summarize – Summarize text.

Parameters:

  • model (Optional[str]) – e.g. "distilbart-cnn" (the default) or "bart-large-cnn"
  • min_length (int) – Minimum summary length in tokens; 0 uses the model's default
  • max_length (int) – Maximum summary length in tokens; 0 uses the model's default
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • quiet (bool) – Suppress progress output

kjarni.Summarizer.summarize

summarize(text)

Summarize text.

kjarni.Transcriber

Transcriber(model=None, language=None, translate=False, device='cpu', quiet=False)

Speech to text with Whisper.

Example

transcriber = Transcriber(language="en") print(transcriber.transcribe_file("meeting.wav").text)

Functions:

  • transcribe – Transcribe mono samples in -1..1 at any sample rate.
  • transcribe_file – Transcribe a wav, mp3, flac or ogg file.

Parameters:

  • model (Optional[str]) – e.g. "whisper-small" (the default) or "whisper-large-v3"
  • language (Optional[str]) – ISO code such as "en" or "is"; None detects it from the audio
  • translate (bool) – Translate the speech into English instead of transcribing it
  • device (str) – "cpu" or "gpu"
  • quiet (bool) – Suppress progress output

kjarni.Transcriber.transcribe

transcribe(samples, sample_rate)

Transcribe mono samples in -1..1 at any sample rate.

Accepts a list or any buffer of float32, such as a NumPy array, which is passed without copying.

kjarni.Transcriber.transcribe_file

transcribe_file(path)

Transcribe a wav, mp3, flac or ogg file.

kjarni.Transcript

Bases: NamedTuple

The result of transcribing audio.

Attributes:

  • duration_secs (float) –
  • language (str) –
  • segments (List[Segment]) –
  • text (str) –

kjarni.Transcript.duration_secs

duration_secs: float

kjarni.Transcript.language

language: str

kjarni.Transcript.segments

segments: List[Segment]

kjarni.Transcript.text

text: str

kjarni.Translator

Translator(model=None, source=None, target=None, device='cpu', cache_dir=None, quiet=False)

Translates text between languages.

Example

translator = Translator(source="en", target="de") translator.translate("The house is small.") 'Das Haus ist klein.'

Functions:

  • translate – Translate text.

source and target rather than from and to, which Python reserves.

Parameters:

  • model (Optional[str]) – e.g. "flan-t5-base" (the default) or "flan-t5-large"
  • source (Optional[str]) – Default source language ("en", "english", ...)
  • target (Optional[str]) – Default target language
  • device (str) – "cpu" or "gpu"
  • cache_dir (Optional[str]) – Directory to cache models
  • quiet (bool) – Suppress progress output

kjarni.Translator.translate

translate(text, source=None, target=None)

Translate text.

Languages left as None fall back to the defaults given at construction; with neither, this raises KjarniException with code INVALID_CONFIG.

kjarni.Turn

Bases: NamedTuple

One message of a transcript: role is "system", "user" or "assistant".

Attributes:

  • content (str) –
  • role (str) –

kjarni.Turn.content

content: str

kjarni.Turn.role

role: str

kjarni.version

version()

Get Kjarni version.

Kjarni runs the same engine on every platform: