135 lines
5.1 KiB
Python
135 lines
5.1 KiB
Python
#!/usr/bin/env python3
|
||
"""Транскрипция встречи: faster-whisper → заметка в buryan-work.
|
||
|
||
Использование:
|
||
transcribe.py <аудио|видео> [--client Имя] [--model tiny|base|small] [--push]
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from datetime import datetime
|
||
|
||
WORK = "/opt/buryan-work"
|
||
MODEL = os.environ.get("WHISPER_MODEL", "base")
|
||
|
||
|
||
def sh(cmd, timeout=600):
|
||
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
|
||
return r.returncode, (r.stdout or ""), (r.stderr or "")
|
||
|
||
|
||
|
||
def decode_np(path):
|
||
"""Декодирует через ffmpeg в float32 — обходит несовместимость av."""
|
||
import numpy as np
|
||
r = subprocess.run(
|
||
["ffmpeg", "-v", "quiet", "-i", path, "-f", "s16le", "-acodec", "pcm_s16le",
|
||
"-ar", "16000", "-ac", "1", "-"],
|
||
capture_output=True, timeout=600)
|
||
if r.returncode != 0:
|
||
raise RuntimeError("ffmpeg decode failed")
|
||
audio = np.frombuffer(r.stdout, np.int16).astype(np.float32) / 32768.0
|
||
return audio
|
||
|
||
def to_wav(src):
|
||
dst = "/tmp/meeting-" + str(int(time.time())) + ".wav"
|
||
rc, _, err = sh(f"ffmpeg -y -i '{src}' -ar 16000 -ac 1 -c:a pcm_s16le '{dst}'")
|
||
if rc != 0:
|
||
raise RuntimeError(f"ffmpeg: {err[:200]}")
|
||
return dst
|
||
|
||
|
||
def transcribe(path, model_size=MODEL):
|
||
from faster_whisper import WhisperModel
|
||
model = WhisperModel(model_size, device="cpu", compute_type="int8")
|
||
audio = decode_np(path)
|
||
segments, info = model.transcribe(audio, language="ru", vad_filter=True,
|
||
beam_size=1)
|
||
rows = []
|
||
for seg in segments:
|
||
rows.append({"start": round(seg.start, 1), "end": round(seg.end, 1),
|
||
"text": seg.text.strip()})
|
||
return rows, getattr(info, "duration", None)
|
||
|
||
|
||
def summarize(rows):
|
||
"""Простая выжимка без LLM: решения, вопросы, следующие шаги."""
|
||
text = " ".join(r["text"] for r in rows)
|
||
sentences = re.split(r"(?<=[.!?])\s+", text)
|
||
decisions = [s for s in sentences if re.search(
|
||
r"\b(решили|договорились|утвердили|согласовали|выбрали)\b", s, re.I)]
|
||
questions = [s for s in sentences if s.strip().endswith("?")]
|
||
actions = [s for s in sentences if re.search(
|
||
r"\b(нужно|надо|сделаем|подготов|отправ|провер|созвон|доработа)\w*", s, re.I)]
|
||
return {
|
||
"decisions": decisions[:8],
|
||
"questions": questions[:8],
|
||
"actions": actions[:10],
|
||
"key": sentences[:5],
|
||
}
|
||
|
||
|
||
def make_note(rows, summary, client, source, duration):
|
||
date = datetime.now().strftime("%Y-%m-%d")
|
||
name = f"{date}-{(client or 'встреча').replace(' ', '-')}.md"
|
||
path = os.path.join(WORK, "meetings", name)
|
||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||
lines = [f"# Встреча: {client or 'без названия'}", "",
|
||
f"**Дата:** {date} ", f"**Источник:** `{os.path.basename(source)}` ",
|
||
f"**Длительность:** {round(duration or 0)} с", "", "## Решения", ""]
|
||
lines += [f"- {s}" for s in summary["decisions"]] or ["- (не найдено)"]
|
||
lines += ["", "## Вопросы", ""]
|
||
lines += [f"- {s}" for s in summary["questions"]] or ["- (не найдено)"]
|
||
lines += ["", "## Следующие шаги", ""]
|
||
lines += [f"- [ ] {s}" for s in summary["actions"]] or ["- [ ] (не найдено)"]
|
||
lines += ["", "## Транскрипт", "", "```"]
|
||
for r in rows:
|
||
lines.append(f"[{r['start']:>7.1f}] {r['text']}")
|
||
lines += ["```", ""]
|
||
open(path, "w", encoding="utf-8").write("\n".join(lines))
|
||
return path
|
||
|
||
|
||
def push(note, client):
|
||
if not os.path.isdir(WORK + "/.git"):
|
||
return "нет локальной копии"
|
||
rel = os.path.relpath(note, WORK)
|
||
sh(f"cd {WORK} && git add -A && "
|
||
f"git -c user.name=buryan-agent -c user.email=agent@buryans.ru "
|
||
f"commit -q -m 'Встреча: {client or 'без названия'}' && git push -q")
|
||
return f"закоммичено: {rel}"
|
||
|
||
|
||
def main():
|
||
if len(sys.argv) < 2:
|
||
print(__doc__)
|
||
return
|
||
src = sys.argv[1]
|
||
client = None
|
||
do_push = "--push" in sys.argv
|
||
if "--client" in sys.argv:
|
||
client = sys.argv[sys.argv.index("--client") + 1]
|
||
model = MODEL
|
||
if "--model" in sys.argv:
|
||
model = sys.argv[sys.argv.index("--model") + 1]
|
||
if not os.path.exists(src):
|
||
print("файл не найден:", src)
|
||
return
|
||
wav = to_wav(src)
|
||
print("распознаю...")
|
||
rows, duration = transcribe(wav, model)
|
||
print(f"сегментов: {len(rows)}, длительность: {round(duration or 0)} с")
|
||
summary = summarize(rows)
|
||
note = make_note(rows, summary, client, src, duration)
|
||
print("заметка:", note)
|
||
if do_push:
|
||
print(push(note, client))
|
||
print(json.dumps({k: len(v) for k, v in summary.items()}, ensure_ascii=False))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|