Here's a context-aware subtitle conversion program that uses llama.cpp to perform natural case conversion (natcase) on .srt subtitle files. The approach focuses on efficiency for slower machines while maintaining context awareness.
Option 1: Bash Script (simpler, less control)
#!/bin/bash
# NatCase SRT Converter using llama.cpp
# Usage: ./natcase_srt.sh input.srt [output.srt] [model_path]
INPUT="$1"
OUTPUT="${2:-${INPUT%.*}_natcase.${INPUT##*.}}"
MODEL="${3:-./models/gemma-3-1b.gguf}"
# Check if llama.cpp is available
if ! command -v ./main &> /dev/null; then
echo "Error: llama.cpp 'main' executable not found in current directory"
exit 1
fi
# Process each subtitle text block
process_subtitle() {
local text="$1"
local context="$2"
# Prepare prompt with context
prompt="Convert this subtitle text to natural case (proper nouns capitalized, rest lowercase), keeping the meaning exactly the same. Only output the converted text.\n\nContext: ${context}\nText: ${text}\nConverted:"
# Call llama.cpp with conservative settings for slow machines
echo -e "$prompt" | ./main \
-m "$MODEL" \
--temp 0.2 \
--top-k 40 \
--top-p 0.9 \
--repeat-penalty 1.1 \
-n 256 \
-c 512 \
-p - 2>/dev/null | \
grep -v "^>" | \
sed '/^$/d' | \
head -n 1
}
# Main processing loop
current_context=""
while IFS= read -r line; do
if [[ "$line" =~ ^[0-9]+$ ]]; then
# Subtitle number - pass through
echo "$line"
elif [[ "$line" =~ ^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} ]]; then
# Timestamp - pass through
echo "$line"
elif [[ -z "$line" ]]; then
# Empty line between subtitles
echo
current_context=""
else
# Subtitle text - process
processed=$(process_subtitle "$line" "$current_context")
echo "$processed"
current_context+=" $processed"
# Keep context manageable for memory
current_context=$(echo "$current_context" | awk '{print substr($0,length-200)}')
fi
done < "$INPUT" > "$OUTPUT"
echo "Conversion complete. Output saved to $OUTPUT"
Option 2: C99 Program (more efficient)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_LINE 2048
#define CONTEXT_SIZE 512
void process_with_llama(const char *text, const char *context, char *output, const char *model_path) {
int pipefd[2];
pid_t pid;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process
close(pipefd[0]); // Close unused read end
// Redirect stdout to pipe
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
// Prepare prompt
char prompt[MAX_LINE * 2];
snprintf(prompt, sizeof(prompt),
"Convert this subtitle text to natural case (proper nouns capitalized, rest lowercase), "
"keeping the meaning exactly the same. Only output the converted text.\n\n"
"Context: %s\nText: %s\nConverted:",
context, text);
// Execute llama.cpp with conservative settings
execl("./main", "./main",
"-m", model_path,
"--temp", "0.2",
"--top-k", "40",
"--top-p", "0.9",
"--repeat-penalty", "1.1",
"-n", "256",
"-c", "512",
"-p", "-",
NULL);
perror("execl");
exit(EXIT_FAILURE);
} else { // Parent process
close(pipefd[1]); // Close unused write end
// Read output from llama.cpp
char buffer[MAX_LINE];
ssize_t count = read(pipefd[0], buffer, sizeof(buffer) - 1);
if (count == -1) {
perror("read");
exit(EXIT_FAILURE);
}
buffer[count] = '\0';
// Wait for child to finish
int status;
waitpid(pid, &status, 0);
// Extract just the converted text (first line after prompt)
char *converted = strstr(buffer, "Converted:");
if (converted) {
converted += strlen("Converted:");
char *end = strchr(converted, '\n');
if (end) *end = '\0';
// Trim whitespace
while (isspace(*converted)) converted++;
char *p = converted + strlen(converted) - 1;
while (p > converted && isspace(*p)) p--;
*(p + 1) = '\0';
strncpy(output, converted, MAX_LINE - 1);
} else {
strncpy(output, text, MAX_LINE - 1); // Fallback to original
}
close(pipefd[0]);
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s input.srt [output.srt] [model_path]\n", argv[0]);
return EXIT_FAILURE;
}
const char *input_path = argv[1];
const char *output_path = (argc > 2) ? argv[2] : "output.srt";
const char *model_path = (argc > 3) ? argv[3] : "models/gemma-3-1b.gguf";
FILE *input = fopen(input_path, "r");
if (!input) {
perror("fopen input");
return EXIT_FAILURE;
}
FILE *output = fopen(output_path, "w");
if (!output) {
perror("fopen output");
fclose(input);
return EXIT_FAILURE;
}
char line[MAX_LINE];
char context[CONTEXT_SIZE] = {0};
bool in_subtitle = false;
while (fgets(line, sizeof(line), input)) {
// Remove trailing newline
line[strcspn(line, "\n")] = '\0';
// Check for subtitle number or timestamp
if (strlen(line) == 0) {
// Empty line between subtitles
fputc('\n', output);
in_subtitle = false;
context[0] = '\0'; // Reset context
} else if (isdigit(line[0]) && strspn(line, "0123456789") == strlen(line)) {
// Subtitle number
fprintf(output, "%s\n", line);
in_subtitle = true;
} else if (strstr(line, "-->")) {
// Timestamp line
fprintf(output, "%s\n", line);
in_subtitle = true;
} else if (in_subtitle) {
// Subtitle text - process with context
char processed[MAX_LINE];
process_with_llama(line, context, processed, model_path);
fprintf(output, "%s\n", processed);
// Update context (rolling window)
strncat(context, " ", CONTEXT_SIZE - strlen(context) - 1);
strncat(context, processed, CONTEXT_SIZE - strlen(context) - 1);
// Keep context size manageable
if (strlen(context) > CONTEXT_SIZE - 50) {
memmove(context, context + strlen(context) - (CONTEXT_SIZE / 2), CONTEXT_SIZE / 2);
context[CONTEXT_SIZE / 2] = '\0';
}
} else {
// Unknown line - pass through
fprintf(output, "%s\n", line);
}
}
fclose(input);
fclose(output);
printf("Conversion complete. Output saved to %s\n", output_path);
return EXIT_SUCCESS;
}
Key Features:
- Context Awareness: Maintains a rolling context window to help with proper noun capitalization
- Efficiency: Uses conservative settings suitable for slow machines
- SRT Format Preservation: Keeps all timing and numbering intact
- Fallback: If processing fails, original text is preserved
- Memory Management: Limits context size to