🇬🇧 English...
Narrative Analyzer is not just a script, but a comprehensive methodology for extracting meaning from sequential textual data. Here are the key principles:
The system operates on the principle of an information pyramid:
- Raw data
- → Deep analysis
- → Contextual compression
- → Season summary
This enables the analysis of endless volumes of content while preserving relevant context.
Each stage of analysis fuels the next:
- Analysis of episode N relies on the findings from episodes 1...(N-1)
- The more data analyzed — the higher the quality of the analysis becomes
- The system "learns" to understand the universe as it processes new data
The tool works with any sequential textual data:
- TV series/anime/movie subtitles
- Podcast and lecture transcripts
- Book chapters and literary works
- Let's plays and gaming streams
- Article series or blog posts
- Historical chronicles and documents
Unlike simple summarization, the system identifies:
- Plot arcs and narrative structures
- Character and relationship evolution
- Emotional patterns and tone
- Unresolved mysteries and foreshadowing
- Connections between disparate events
The project solves the fundamental problem of limited LLM context through:
- Dynamic history compression (working with the model's memory)
- Semantic ranking (determining what is truly important to keep)
- Insight reuse (analysis produces analysis for analysis)
# Cloning the repository
git clone https://github.com/limloop/narrative-analyzer.git
cd narrative-analyzer
# Installing dependencies
pip install -r requirements.txtCreate a .env file in the root directory:
# Required variables
OPENROUTER_API_KEY=your_openrouter_api_key_hereHow to get an API key:
- Register on OpenRouter
- Go to API settings
- Create a new key
- Copy it into the
.envfile
Generate a base config and customize it for your project:
# Generating a configuration template
python analyzer.py --generate-config
# Editing the config for your project
nano config.json # or use any editor{
"content_series_name": "Your Project Name",
"input_dir": "clean",
"output_dir": "data",
"model_settings": {
"name": "z-ai/glm-4.5-air:free",
"temperature": 0.5,
"max_tokens": 4096
},
"api_settings": {
"base_url": "https://openrouter.ai/api/v1",
"max_retries": 5
},
"content_settings": {
"content_type": "TV series",
"content_unit": "episode",
"main_character": "protagonist"
}
}Place VTT subtitle files in the root directory and run the conversion:
# Converting VTT -> clean text
python converter.py
# Files will be saved to the clean/ folderYou can also place raw txt files directly into the clean folder.
Without a configuration file, the system will run on a standard template, which is useless for real work.
# Running analysis on all files
python analyzer.py --config config.jsonAfter analysis, you can create general season summaries:
python compact.pyThis script also transforms the data into a human-readable format.
In config.json, you can specify any model from the OpenRouter catalog or any other API compatible with the openai library:
{
"model_settings": {
"name": "google/gemini-pro-1.5",
"temperature": 0.7
}
}For fine-tuning the analysis, modify the prompt templates in config.json:
{
"analysis_prompt": {
"system_message": "Your custom system prompt...",
"user_prompt_template": "Your custom user prompt with {variables}..."
}
}For long series, configure the context parameters:
{
"context_settings": {
"full_context_episodes": 5,
"max_context_length": 40000,
"enable_context_summary": true
}
}The examples/ folder contains a complete working example of real data processing:
examples/
├── *.vtt # Raw VTT subtitles from YouTube
├── clean/ # Cleaned text files
│ └── *.txt # Text after converter processing
├── data/ # Analysis results
│ └── *.json # Structured analysis in JSON
└── combined_results/ # Final summaries
├── all_episodes.jsonl # All episodes in single file
├── season_summary.json # Season summary report
├── full_prompt.txt # Full analysis prompt
└── compact_season_prompt.txt # Compact season prompt
- Source data: VTT subtitles of "Game of God" series
- Conversion:
python src/converter.py→ clean/*.txt - Analysis:
python src/analyzer.py→ data/*.json - Summarization:
python src/compact.py→ combined_results/
- Raw data - original VTT files with timestamps
- Cleaned texts - converter output results
- Deep analysis - AI-structured insights per episode
- Season summaries - unified narrative overview
# Copy config from example
cp examples/config.json config.json
# Run full pipeline
python src/converter.py
python src/analyzer.py
python src/compact.py- Check the correctness of
OPENROUTER_API_KEYin.env - Ensure you have available requests on your account
- If encoding errors occur, try converting files to UTF-8
- For very long episodes, increasing
max_context_lengthmay be required
🇷🇺 Русский...
Narrative Analyzer — это не просто скрипт, а целая методология извлечения смысла из последовательных текстовых данных. Вот ключевые принципы:
Система работает по принципу информационной пирамиды:
- Сырые данные
- → Глубокий анализ
- → Контекстное сжатие
- → Сезонная сводка
Это позволяет анализировать бесконечные объемы контента, сохраняя релевантный контекст.
Каждый этап анализа становится топливом для следующего:
- Анализ эпизода N опирается на выводы эпизодов 1...(N-1)
- Чем больше данных проанализировано — тем качественнее становится анализ
- Система "учится" понимать вселенную по мере обработки новых данных
Инструмент работает с любыми последовательными текстовыми данными:
- Субтитры сериалов/аниме/фильмов
- Транскрипты подкастов и лекций
- Главы книг и литературные произведения
- Летсплеи и игровые стримы
- Циклы статей или блог-постов
- Исторические хроники и документы
В отличие от простой суммаризации, система выявляет:
- Сюжетные арки и нарративные структуры
- Эволюцию персонажей и отношений
- Эмоциональные паттерны и тональность
- Неразрешенные загадки и форшедоуинг
- Связи между разрозненными событиями
Проект решает фундаментальную проблему ограниченного контекста LLM через:
- Динамическое сжатие истории (работа с памятью модели)
- Семантическое ранжирование (что действительно важно сохранить)
- Переиспользование insights (анализ производит анализ для анализа)
# Клонирование репозитория
git clone https://github.com/limloop/narrative-analyzer.git
cd narrative-analyzer
# Установка зависимостей
pip install -r requirements.txtСоздайте файл .env в корневой директории:
# Обязательные переменные
OPENROUTER_API_KEY=your_openrouter_api_key_hereКак получить API ключ:
- Зарегистрируйтесь на OpenRouter
- Перейдите в настройки API
- Создайте новый ключ
- Скопируйте его в файл
.env
Сгенерируйте базовый конфиг и настройте под ваш проект:
# Генерация шаблона конфигурации
python analyzer.py --generate-config
# Редактирование конфига под ваш проект
nano config.json # или используйте любой редактор{
"content_series_name": "Название вашего проекта",
"input_dir": "clean",
"output_dir": "data",
"model_settings": {
"name": "z-ai/glm-4.5-air:free",
"temperature": 0.5,
"max_tokens": 4096
},
"api_settings": {
"base_url": "https://openrouter.ai/api/v1",
"max_retries": 5
},
"content_settings": {
"content_type": "сериале",
"content_unit": "эпизод",
"main_character": "герой"
}
}Поместите VTT файлы субтитров в корневую директорию и запустите конвертацию:
# Конвертация VTT -> чистый текст
python converter.py
# Файлы будут сохранены в папку clean/Вы так же можете поместить сырые txt файлы сразу в папку clean.
Без конфигурационного файла система будет работать на стандартном шаблоне, который в реальной работе бесполезен.
# Запуск анализа всех файлов
python analyzer.py --config config.jsonПосле анализа можно создать общие сводки по сезону:
python compact.pyТак же этот скрипт преобразовывает данные в читаемый для человека вид.
В config.json можно указать любую модель из каталога OpenRouter или любого другого совместимого с библиотекой openai api:
{
"model_settings": {
"name": "google/gemini-pro-1.5",
"temperature": 0.7
}
}Для тонкой настройки анализа измените шаблоны промптов в config.json:
{
"analysis_prompt": {
"system_message": "Твой кастомный system prompt...",
"user_prompt_template": "Твой кастомный user prompt с {переменными}..."
}
}Для длинных сериалов настройте параметры контекста:
{
"context_settings": {
"full_context_episodes": 5,
"max_context_length": 40000,
"enable_context_summary": true
}
}В папке examples/ вы найдете полный рабочий пример обработки реальных данных:
examples/
├── *.vtt # Сырые VTT-субтитры из YouTube
├── clean/ # Очищенные текстовые файлы
│ └── *.txt # Текст после обработки конвертером
├── data/ # Результаты анализа
│ └── *.json # Структурированный анализ в JSON
└── combined_results/ # Финальные сводки
├── all_episodes.jsonl # Все эпизоды в одном файле
├── season_summary.json # Итоговая сводка сезона
├── full_prompt.txt # Полный промпт для анализа
└── compact_season_prompt.txt # Сжатый промпт сезона
- Исходные данные: VTT-субтитры серий "Игра Бога"
- Конвертация:
python src/converter.py→ clean/*.txt - Анализ:
python src/analyzer.py→ data/*.json - Сводка:
python src/compact.py→ combined_results/
- Сырые данные - оригинальные VTT файлы с временными метками
- Очищенные тексты - результат работы конвертера
- Глубокий анализ - структурированные выводы ИИ по каждой серии
- Сезонные сводки - объединенная картина всего narrative
# Копируем конфиг из примера
cp examples/config.json config.json
# Запускаем полный пайплайн
python src/converter.py
python src/analyzer.py
python src/compact.py- Проверьте правильность
OPENROUTER_API_KEYв.env - Убедитесь, что на счету есть доступные запросы
- Если возникают ошибки кодировки, попробуйте конвертировать файлы в UTF-8
- Для очень длинных эпизодов может потребоваться увеличение
max_context_length