new structure for transcription engine
- found problems with mps - integrated jinja2 templates for rendering (.tex?) - raw ui & bad structure
This commit is contained in:
@@ -1,84 +0,0 @@
|
||||
Используй **исключительно текст из транскрибации** как первоисточник.
|
||||
Разрешается расширять тему и объяснять глубже, но **дополнительная информация должна быть строго отделена и явно помечена**.
|
||||
|
||||
### Цель
|
||||
|
||||
Создать структурированную, полный образовательный конспект лекции **формата Obsidian Markdown**, который:
|
||||
|
||||
* воспроизводит информацию из транскрибата максимально точно
|
||||
* дополняет и разъясняет сложные моменты
|
||||
* превращает речь в ясный учебный материал
|
||||
* сохраняет смысл, порядок, и логическую структуру лектора
|
||||
* улучшает академичность и связность
|
||||
|
||||
### Правила работы с транскриптом
|
||||
|
||||
* Используй только факты из транскрибации как основу.
|
||||
* **Не выдумывай факты**, которых не было.
|
||||
* **Дополнительные пояснения допустимы**, но строго в спец-блоках (см. ниже).
|
||||
* Цитаты из оригинального текста — **дослівно**, максимум **25 слов подряд**.
|
||||
* Нельзя писать «лектор сказал», «в тексте было» — пишем как учебный материал.
|
||||
|
||||
### Блоки для расширений
|
||||
|
||||
Если нужно объяснить термин, дополнить концепцию, исправить недосказанность — используй:
|
||||
|
||||
```
|
||||
> AI clarification:
|
||||
> Ваше дополнение, объяснение, аналогия или расширение темы.
|
||||
```
|
||||
|
||||
Для коротких определений:
|
||||
|
||||
```
|
||||
**AI note:** краткое пояснение
|
||||
```
|
||||
|
||||
### Обязательная структура результата
|
||||
|
||||
```
|
||||
# Название темы
|
||||
|
||||
## Ключевые идеи
|
||||
- маркеры
|
||||
- …
|
||||
|
||||
## Основные понятия и определения
|
||||
- **Термин** — определение
|
||||
- …
|
||||
|
||||
## Подробный конспект
|
||||
(структура, логика, абзацы, тезисы)
|
||||
|
||||
> Цитаты (≤25 слов)
|
||||
|
||||
## Примеры и объяснения
|
||||
- собственные пересказанные примеры из транскрибации
|
||||
- при необходимости:
|
||||
> AI clarification
|
||||
|
||||
## Выводы и ключевые инсайты
|
||||
- …
|
||||
|
||||
## Вопросы для самопроверки
|
||||
- …
|
||||
```
|
||||
|
||||
### Обязательный формат Obsidian Markdown
|
||||
|
||||
Используй следующие возможности Obsidian:
|
||||
|
||||
| Элемент | Формат |
|
||||
| ----------------- | ----------------------------------------- |
|
||||
| Заголовки | `#`, `##`, `###` |
|
||||
| Цитаты | `>` |
|
||||
| Списки | `-` и `1.` |
|
||||
| Врезка/внимание | `> [!note]` `> [!tip]` |
|
||||
| Код/формулы | `\`…`` и блоки ``` |
|
||||
| Выделение | `**жирный**`, `_курсив_`, `==выделение==` |
|
||||
| Внутренние ссылки | `[[Термин]]` если термин важный |
|
||||
| Таблицы | стандартные markdown таблицы |
|
||||
| Чек-лист | `- [ ]` |
|
||||
| Формулы | Для однострочных формул используй $ formula $. Для мультистрочных формул используй $$ formula $$ |
|
||||
|
||||
**Не добавляй** приветствий, заключений, обращений, пояснений формата. Только готовый md-текст.
|
||||
@@ -0,0 +1,13 @@
|
||||
# not sure, but why not?
|
||||
|
||||
class AudioPreparationError(Exception):
|
||||
"""Base exception for audio preparation"""
|
||||
pass
|
||||
|
||||
class ResamplingError(AudioPreparationError):
|
||||
"""Raises when resampling fails"""
|
||||
pass
|
||||
|
||||
class DownmixingError(AudioPreparationError):
|
||||
"""Raises when downmixing to mono fails"""
|
||||
pass
|
||||
@@ -0,0 +1,58 @@
|
||||
Create a complete, structured **Obsidian Markdown** educational summary based on the transcript.
|
||||
|
||||
The final document must be written in **{{ language }}**.
|
||||
|
||||
Use the transcript strictly as the factual basis:
|
||||
- Do NOT invent facts.
|
||||
- You may add clarifications and explanations, but they MUST be placed in special blocks.
|
||||
- Preserve the logical order and meaning of the original speaker.
|
||||
- Transform speech into clear academic exposition.
|
||||
- Quotes must be accurate and **<= 25 words**.
|
||||
- Do not reference the transcript or the speaker. Write as a stand-alone educational text.
|
||||
|
||||
You must follow the template below exactly.
|
||||
|
||||
---
|
||||
|
||||
# {{ title }}
|
||||
|
||||
## Key Ideas
|
||||
- bullet points summarizing the main concepts
|
||||
|
||||
## Core Concepts and Definitions
|
||||
- **Term** — definition
|
||||
- **Another Term** — definition
|
||||
|
||||
## Detailed Summary
|
||||
Write a logically structured, academically clear exposition.
|
||||
Break it into paragraphs, subsections, lists, and quotes.
|
||||
|
||||
To include quotes from the transcript, use:
|
||||
|
||||
> "{{ quote }}"
|
||||
(Ensure that every quote is ≤ 25 words.)
|
||||
|
||||
## Examples and Explanations
|
||||
Use examples that appear in the transcript.
|
||||
Additional clarifications must use the following block:
|
||||
|
||||
> AI clarification:
|
||||
> Your extended explanation, analogy, or contextual detail.
|
||||
|
||||
Short notes should use:
|
||||
|
||||
**AI note:** short clarification
|
||||
|
||||
## Conclusions and Key Insights
|
||||
- summary points
|
||||
- what the reader should remember
|
||||
|
||||
## Self-Assessment Questions
|
||||
- question 1
|
||||
- question 2
|
||||
- question 3
|
||||
|
||||
---
|
||||
|
||||
### Transcript (for your reference only):
|
||||
{{ transcription }}
|
||||
@@ -0,0 +1,75 @@
|
||||
Create a clean, structured **LaTeX educational summary** based strictly on the transcript.
|
||||
|
||||
The final document must be written in **{{ language }}**.
|
||||
|
||||
Guidelines:
|
||||
- Use ONLY facts from the transcript as the base.
|
||||
- You MAY add explanations, but they MUST appear in designated blocks.
|
||||
- Do NOT reference the transcript or the speaker.
|
||||
- Maintain the speaker`s logical order.
|
||||
- Produce academically clear, structured LaTeX text.
|
||||
- Quotes must be accurate and <= 25 words.
|
||||
|
||||
Use the structure below.
|
||||
Assume that stylistic environments are already defined in the `.sty` file.
|
||||
|
||||
---
|
||||
|
||||
\section*{ {{ title }} }
|
||||
|
||||
\subsection*{Key Ideas}
|
||||
\begin{itemize}
|
||||
\item main idea
|
||||
\item …
|
||||
\end{itemize}
|
||||
|
||||
\subsection*{Core Concepts and Definitions}
|
||||
\begin{description}
|
||||
\item[\textbf{Term}] definition
|
||||
\item[\textbf{Another Term}] definition
|
||||
\end{description}
|
||||
|
||||
\subsection*{Detailed Summary}
|
||||
Write a clear, logically structured academic explanation.
|
||||
Break content into paragraphs, subsections, lists.
|
||||
|
||||
Quotes from the transcript must be included as:
|
||||
|
||||
\begin{quote}
|
||||
"{{ quote }}"
|
||||
\end{quote}
|
||||
|
||||
(Ensure each quote is ≤ 25 words.)
|
||||
|
||||
\subsection*{Examples and Explanations}
|
||||
|
||||
Examples based on the transcript.
|
||||
|
||||
Additional clarifications must use the following custom environment (assumed to exist in the .sty):
|
||||
|
||||
\begin{aiclarification}
|
||||
Your additional explanation, analogy, or contextual expansion.
|
||||
\end{aiclarification}
|
||||
|
||||
Short notes should use:
|
||||
|
||||
\ainote{short clarification}
|
||||
|
||||
\subsection*{Conclusions and Key Insights}
|
||||
\begin{itemize}
|
||||
\item conclusion
|
||||
\item conclusion
|
||||
\end{itemize}
|
||||
|
||||
\subsection*{Self-Assessment Questions}
|
||||
\begin{enumerate}
|
||||
\item question
|
||||
\item question
|
||||
\item question
|
||||
\end{enumerate}
|
||||
|
||||
---
|
||||
|
||||
% Transcript included only for reference (model must not copy or analyze or mention this directly)
|
||||
% ======================================================
|
||||
% {{ transcription | replace("%", "\\%") }}
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
||||
|
||||
|
||||
class PromptManager:
|
||||
"""
|
||||
Self-written class for Jinja2 templates especially for summarization.
|
||||
|
||||
Supports:
|
||||
- md
|
||||
- latex
|
||||
|
||||
Usage examples:
|
||||
```
|
||||
from prompts.prompt_manager import PromptManager
|
||||
|
||||
pm = PromptManager("notecast/prompts")
|
||||
|
||||
markdown_text = pm.render(
|
||||
"markdown_default_prompt.md.j2",
|
||||
language="Russian",
|
||||
title="Calculus - Lecture 1",
|
||||
transcription=raw_transcription_text
|
||||
)
|
||||
|
||||
latex_text = pm.render(
|
||||
"latex_default_prompt.j2",
|
||||
language="Russian",
|
||||
title="Calculus - Lecture 1",
|
||||
transcription=raw_transcription_text
|
||||
)
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(self, templates_dir: str) -> None:
|
||||
if not os.path.isdir(templates_dir):
|
||||
raise NotADirectoryError(f"Templates directory not found: {templates_dir}")
|
||||
|
||||
self.templates_dir = templates_dir
|
||||
|
||||
self.env = Environment(
|
||||
loader=FileSystemLoader(self.templates_dir),
|
||||
autoescape=False,
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
undefined=StrictUndefined
|
||||
)
|
||||
|
||||
def list_templates(self) -> list[str]:
|
||||
templates = []
|
||||
for file in os.listdir(self.templates_dir):
|
||||
if file.endswith(".j2"):
|
||||
templates.append(file)
|
||||
return templates
|
||||
|
||||
def load(self, template_name: str):
|
||||
try:
|
||||
return self.env.get_template(template_name)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to load template '{template_name}': {e}")
|
||||
|
||||
def render(
|
||||
self,
|
||||
template_name: str,
|
||||
*,
|
||||
language: str,
|
||||
title: str,
|
||||
transcription: str
|
||||
) -> str:
|
||||
template = self.load(template_name)
|
||||
|
||||
return template.render(
|
||||
language=language,
|
||||
title=title,
|
||||
transcription=transcription
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
import openai
|
||||
|
||||
|
||||
# maybe make it asynchronous?
|
||||
class LLMrequest:
|
||||
def __init__(self, api_key: str, model_name: str, base_url: str = None):
|
||||
if base_url:
|
||||
|
||||
Reference in New Issue
Block a user