PEP-108: voice and text stories from the user's own bot, transcribe timeout, «в проекте X»

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 15:18:33 +05:00
parent e1abca0be9
commit 2d4e8e6119
12 changed files with 182 additions and 17 deletions

View File

@ -32,3 +32,11 @@ GITEA_OAUTH_CLIENT_SECRET=
# Вход через Google (PEP-90): OAuth-клиент из Google Cloud, redirect URI <PEPPA_WEB_URL>/auth/google/callback
# GOOGLE_CLIENT_ID=
# GOOGLE_CLIENT_SECRET=
# Стори голосом в Telegram (PEP-45/108): OpenAI-совместимый /audio/transcriptions.
# Свой сервис Пеппы — scripts/transcribe-up.sh (docker, 127.0.0.1:3185, без ключа); облако — OpenAI/Groq с ключом.
# PEPPA_TRANSCRIBE_URL=http://127.0.0.1:3185/v1
# PEPPA_TRANSCRIBE_MODEL=deepdml/faster-whisper-large-v3-turbo-ct2
# PEPPA_TRANSCRIBE_LANG=ru
# PEPPA_TRANSCRIBE_KEY=
# PEPPA_TRANSCRIBE_TIMEOUT_SEC=300

View File

@ -68,7 +68,7 @@ import {
type ChatMessage,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
import { acceptTask, answerAndDeliver, decideIncident, moveTask, postToChat, resumeSession, stopSession } from "@peppa/runner";
import { AsyncLocalStorage } from "node:async_hooks";
import { eq, sql } from "drizzle-orm";
@ -100,11 +100,11 @@ export interface BotOptions {
log?: (msg: string) => void;
}
const HELP = `Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас.
const helpText = (voice: boolean) => `Я бот Peppa FACTORY. Присылаю вопросы от агентов и сообщения о том, что задача готова или агент ждёт вас.
• Кнопки под сообщением — быстрый ответ.
• Ответ <b>реплаем</b> на сообщение — свой текст, он уйдёт агенту.
• Просто напишите (или наговорите голосом) задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
• Просто напишите${voice ? " (или наговорите голосом)" : ""} задачу — я её заведу: «в PAY: экспорт в CSV». Проект и эпик уточню кнопками, потом предложу сразу взять в работу.
• /status — кто из агентов работает и какие вопросы открыты.
• /digest — сводка за сутки по вашим проектам (каждый день приходит сама; время и что присылать — в Настройках → Уведомления).`;
@ -609,7 +609,7 @@ export function createBot(o: BotOptions) {
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username, botUserId: via.getStore()?.userId });
if (b) {
await syncOwnBots().catch(() => {}); // the chat now belongs to this bot
await reply(m.chat.id, `Привязано ✅\n\n${HELP}`);
await reply(m.chat.id, `Привязано ✅\n\n${helpText(voiceStoriesEnabled())}`);
scheduleReconcile();
return "done";
}
@ -624,7 +624,7 @@ export function createBot(o: BotOptions) {
// PEP-48: what follows is done by this user through Telegram.
enterActor({ kind: "user", userId: user.id, channel: "telegram" });
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, helpText(voiceStoriesEnabled())).then(() => "done");
if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
if (/^\/digest\b/.test(text)) {
const d = await buildDigest(db, user);

View File

@ -46,15 +46,16 @@ export async function dropDraft(db: Db, id: number): Promise<void> {
}
/**
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…".
* "в PAY: экспорт в CSV", "PAY: …", "PAY — …", or (voice, no punctuation) "в PAY экспорт…" and
* "в проекте Pay экспорт…" (how whisper writes it down, PEP-108).
* The key counts only if it is one of the user's projects; otherwise the whole text is the story.
*/
export function parseStoryText(text: string, projects: Project[]): { project: Project | null; body: string } {
const t = text.trim();
const byKey = (k: string) => projects.find((p) => p.key.toLowerCase() === k.toLowerCase()) ?? null;
const withSep = /^(?:(?:в|во|для|in|to)\s+)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
const withSep = /^(?:(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?)?([A-Za-z][A-Za-z0-9]{1,9})\s*[::—–-]\s*([\s\S]+)$/i.exec(t);
if (withSep && byKey(withSep[1]!)) return { project: byKey(withSep[1]!), body: withSep[2]!.trim() };
const spoken = /^(?:в|во|для|in|to)\s+([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
const spoken = /^(?:в|во|для|in|to)\s+(?:проекте?\s+|project\s+)?([A-Za-z][A-Za-z0-9]{1,9})[,.]?\s+([\s\S]+)$/i.exec(t);
if (spoken && byKey(spoken[1]!)) return { project: byKey(spoken[1]!), body: spoken[2]!.trim() };
return { project: null, body: t };
}

View File

@ -2,7 +2,8 @@
// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language,
// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}.
// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Peppa's own is
// the `transcribe` service of infra/docker-compose.yml (scripts/transcribe-up.sh). Tests use
// mock-transcribe (packages/testkit).
export interface TranscribeConfig {
@ -10,6 +11,8 @@ export interface TranscribeConfig {
key: string | null;
model: string;
language: string | null;
/** How long to wait for the text: a local model on CPU (PEP-108) is slower than a cloud API. */
timeoutMs: number;
}
/** From env; null when voice is not set up (the bot asks for text then). */
@ -21,6 +24,7 @@ export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): Transcri
key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null,
model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1",
language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"),
timeoutMs: (Number(env.PEPPA_TRANSCRIBE_TIMEOUT_SEC) > 0 ? Number(env.PEPPA_TRANSCRIBE_TIMEOUT_SEC) : 300) * 1000,
};
}
@ -38,7 +42,7 @@ export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename
method: "POST",
headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {},
body: form,
signal: AbortSignal.timeout(120_000),
signal: AbortSignal.timeout(cfg.timeoutMs),
});
} catch (e) {
throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);

View File

@ -2,6 +2,7 @@ import Link from "next/link";
import { PRODUCT_HELP } from "@peppa/core";
import { publicOrigin, uiMode } from "@/lib/auth";
import { Workspace } from "@/components/Workspace";
import { voiceStoriesEnabled } from "@peppa/shared";
import { PageHeader, Section } from "@/components/common";
const TOOLS: Array<[string, string]> = [
@ -272,7 +273,10 @@ export default async function Help() {
</p>
<p className="m-0 text-muted-foreground">
Новую стори можно просто написать или наговорить боту: «в PAY: экспорт в CSV». Бот уточнит проект (если не указан) и
эпик кнопками, создаст стори и предложит «Взять в работу». Голосовые работают, если на сервере настроена расшифровка.
эпик кнопками, создаст стори и предложит «Взять в работу».{" "}
{voiceStoriesEnabled()
? "Голосовое бот сначала расшифрует и покажет текст («Расслышал: …»); проект можно назвать голосом: «в проекте Pay …»."
: "Голосовые пока не настроены на сервере — пишите текстом."}
</p>
</Section>

View File

@ -7,6 +7,7 @@ import { Input, Label } from "@/components/ui/input";
import { GoogleSignIn } from "@/components/GoogleSignIn";
import { EgovSign } from "@/components/EgovSign";
import { OwnBotSteps } from "@/components/OwnBotSteps";
import { voiceStoriesEnabled } from "@peppa/shared";
import { Workspace } from "@/components/Workspace";
import { publicOrigin, requireUser, uiMode, words } from "@/lib/auth";
import { db } from "@/lib/db";
@ -176,7 +177,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise
</form>
}
>
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Peppa FACTORY"}. Новую задачу можно просто написать боту.
Вопросы агентов и «готово к ревью» приходят вам {user.telegramBotUsername ? <>от вашего бота <span className="font-mono">@{user.telegramBotUsername}</span></> : "от общего бота Peppa FACTORY"}. Новую задачу можно просто {voiceStoriesEnabled() ? "написать или наговорить голосом" : "написать"} боту.
</Row>
) : (
ownBotSteps

View File

@ -4,6 +4,7 @@ import { Hidden } from "@/components/cards";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { voiceStoriesEnabled } from "@peppa/shared";
function StepNum({ n, done }: { n: number; done: boolean }) {
return (
@ -15,11 +16,13 @@ function StepNum({ n, done }: { n: number; done: boolean }) {
/**
* PEP-85: connecting the user's own Telegram bot in three plain steps (BotFather → token →
* Start). Shown on the Home page as the first thing a new user does, and in Settings.
* Start), then what it is for (PEP-108: write or dictate a story). Shown on the Home page as
* the first thing a new user does, and in Settings.
*/
export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername: string | null; back: string; bare?: boolean }) {
const hasBot = !!botUsername;
const fields = { back };
const voice = voiceStoriesEnabled();
return (
<div className={cn("flex flex-col gap-4", !bare && "rounded-lg border bg-card p-4")}>
{!bare && (
@ -98,6 +101,18 @@ export function OwnBotSteps({ botUsername, back, bare = false }: { botUsername:
)}
</div>
</li>
{/* PEP-108: what the bot is for besides questions — a story by text or by voice. */}
<li className="flex gap-2.5">
<StepNum n={4} done={false} />
<div className="flex min-w-0 flex-col items-start gap-1.5">
<span className="font-medium">Напишите боту задачу</span>
<span className="text-muted-foreground">
Просто напишите{voice ? <> или <b>наговорите голосовое</b></> : null}, что нужно сделать, например{" "}
<span className="font-mono text-foreground">в PAY: экспорт платежей в CSV</span> (PAY — ключ проекта). Бот переспросит проект и эпик
кнопками, заведёт стори и предложит сразу взять её в работу.
</span>
</div>
</li>
</ol>
{/* PEP-100: every user has their own bot — no shared-bot shortcut. */}
{hasBot && (

80
infra/whisper/server.py Normal file
View File

@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Local speech-to-text for Peppa (PEP-108): faster-whisper behind the OpenAI-compatible
endpoint Peppa already speaks — POST /v1/audio/transcriptions (multipart: file, model,
language, response_format=json) -> {"text": "..."}. Listens on 127.0.0.1 only; audio never
leaves this machine. Any format PyAV reads works, Telegram's OGG/Opus voice notes included.
"""
import io
import json
import os
import sys
import threading
import time
from email.parser import BytesParser
from email.policy import HTTP
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from faster_whisper import WhisperModel
HOST = os.environ.get("WHISPER_HOST", "127.0.0.1")
PORT = int(os.environ.get("WHISPER_PORT", "8178"))
MODEL = os.environ.get("WHISPER_MODEL", "large-v3-turbo")
MAX_BYTES = int(os.environ.get("WHISPER_MAX_BYTES", str(25 * 1024 * 1024)))
print(f"loading model {MODEL}…", flush=True)
model = WhisperModel(MODEL, device="cpu", compute_type="int8", cpu_threads=int(os.environ.get("WHISPER_THREADS", "8")))
lock = threading.Lock() # one transcription at a time: the model is not re-entrant
print(f"ready on http://{HOST}:{PORT}", flush=True)
def parse_multipart(content_type: str, body: bytes) -> dict:
msg = BytesParser(policy=HTTP).parsebytes(b"Content-Type: " + content_type.encode() + b"\r\n\r\n" + body)
out = {}
for part in msg.iter_parts():
name = part.get_param("name", header="content-disposition")
if name:
out[name] = part.get_payload(decode=True)
return out
class Handler(BaseHTTPRequestHandler):
def _send(self, status: int, body: dict):
data = json.dumps(body, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path in ("/health", "/v1/health"):
return self._send(200, {"ok": True, "model": MODEL})
self._send(404, {"error": {"message": "not found"}})
def do_POST(self):
if self.path.rstrip("/") not in ("/v1/audio/transcriptions", "/audio/transcriptions"):
return self._send(404, {"error": {"message": "not found"}})
length = int(self.headers.get("Content-Length") or 0)
if length <= 0 or length > MAX_BYTES:
return self._send(413, {"error": {"message": f"audio must be 1..{MAX_BYTES} bytes"}})
try:
fields = parse_multipart(self.headers.get("Content-Type", ""), self.rfile.read(length))
audio = fields.get("file")
if not audio:
return self._send(400, {"error": {"message": "no file"}})
language = (fields.get("language") or b"").decode().strip() or None
started = time.time()
with lock:
segments, info = model.transcribe(io.BytesIO(audio), language=language, vad_filter=True, beam_size=5)
text = " ".join(s.text.strip() for s in segments).strip()
print(f"{time.strftime('%F %T')} {len(audio)} bytes, {info.duration:.1f}s audio, lang={info.language}, {time.time() - started:.1f}s", flush=True)
self._send(200, {"text": text})
except Exception as e: # a broken file must not take the service down
print(f"error: {e}", file=sys.stderr, flush=True)
self._send(400, {"error": {"message": f"could not transcribe: {e}"}})
def log_message(self, *_):
pass
ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()

View File

@ -54,3 +54,11 @@ export function peppaRoot(fallback?: string): string {
export function peppaHome(): string {
return process.env.PEPPA_HOME ?? `${homedir()}/.peppa`;
}
/**
* PEP-108: voice stories in Telegram work — speech to text is set up (PEPPA_TRANSCRIBE_URL, the
* bot's apps/bot/src/transcribe.ts). The web and the bot's /help mention voice only then.
*/
export function voiceStoriesEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
return !!env.PEPPA_TRANSCRIBE_URL?.trim();
}

View File

@ -22,9 +22,11 @@ export interface MockTgUser {
const chatType = (chatId: number) => (chatId < 0 ? "group" : "private");
export class MockTelegram {
readonly token = "mock-123:TOKEN";
/** PEP-85: a second instance stands in for a user's own bot — give it its own identity. */
constructor(bot: { id?: number; username?: string } = {}) {
/** Bot token: methods accept any, files (/file/bot<token>/…) only this one — like Telegram. */
readonly token: string;
/** PEP-85: a second instance stands in for a user's own bot — give it its own identity (and token, PEP-108). */
constructor(bot: { id?: number; username?: string; token?: string } = {}) {
this.token = bot.token ?? "mock-123:TOKEN";
this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" };
}
readonly bot: { id: number; username: string; is_bot: boolean; first_name: string };

View File

@ -336,6 +336,9 @@ describe("Стори из сообщения боту", () => {
const p = await project({ turns: [] });
tg.userSendsVoice(PM, MockTranscribe.speech(`в ${p.key} добавить экспорт`));
await botMsg(/Голосовые сообщения пока не работают/);
// PEP-108: without speech to text /help does not promise voice notes.
tg.userSends(PM, "/help");
assert.doesNotMatch((await botMsg(/Я бот Peppa FACTORY/)).text, /голосом/);
const stt = await new MockTranscribe().start();
Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key });

View File

@ -5,6 +5,7 @@ import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { core, db, teardown, waitFor } from "./helpers.ts";
import { MockTelegram } from "../src/mock-telegram.ts";
import { MockTranscribe } from "../src/mock-transcribe.ts";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
@ -12,8 +13,8 @@ const { TelegramApi } = await import("@peppa/bot/telegram");
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const shared = await new MockTelegram().start();
const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot" }).start();
const OWN_TOKEN = "1234567890:" + "A".repeat(35);
const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot", token: OWN_TOKEN }).start();
const ALICE = { id: 601, chatId: 601, username: "alice" };
const BOB = { id: 602, chatId: 602, username: "bob" };
const EVE = { id: 666, chatId: 666, username: "eve" };
@ -108,6 +109,44 @@ describe("свой Telegram-бот", () => {
assert.equal(own.botMessages(BOB.chatId).length, n);
});
// PEP-108, spec telegram-notifications: «Стори из своего бота текстом и голосом». The voice file
// exists only in her bot's mock (its own token) — getFile/downloadFile must go through the bot
// the update came from; every reply comes from her bot, the shared one stays silent.
test("Scenario: Стори из своего бота текстом и голосом", async () => {
const p = await core.getProject(db, "MOWNA");
const sharedBefore = shared.botMessages(ALICE.chatId).length;
const storyNamed = (title: string) => waitFor(`story «${title}»`, async () => (await core.listTasks(db, { projectId: p.id })).find((t) => t.title === title));
const createFrom = async (re: RegExp) => {
const ask = await waitFor(`draft ${re}`, async () => own.botMessages(ALICE.chatId).find((m) => re.test(m.text)));
const create = ask.reply_markup!.inline_keyboard.flat().find((b) => /Создать/.test(b.text))!;
own.userClicks(ALICE, ask.message_id, create.callback_data!);
await waitFor("created in her bot", async () => /Создал/.test(ask.text));
};
// Text.
own.userSends(ALICE, "в MOWNA: каталог товаров");
await createFrom(/Новая стори в <b>MOWNA<\/b>: «каталог товаров»/);
assert.ok(await storyNamed("каталог товаров"));
// Voice.
const stt = await new MockTranscribe().start();
Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key });
try {
own.userSends(ALICE, "/help");
await waitFor("help mentions voice", async () => own.botMessages(ALICE.chatId).some((m) => /наговори голосом/.test(m.text)));
own.userSendsVoice(ALICE, MockTranscribe.speech("В проекте Mowna починить вход"));
await waitFor("heard", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Расслышал: «В проекте Mowna починить вход»")));
await createFrom(/Новая стори в <b>MOWNA<\/b>: «починить вход»/);
assert.match((await storyNamed("починить вход")).description!, /расшифровка голосового/);
assert.equal(stt.requests.length, 1);
} finally {
delete process.env.PEPPA_TRANSCRIBE_URL;
delete process.env.PEPPA_TRANSCRIBE_KEY;
await stt.stop();
}
assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot");
});
test("отключение своего бота: опрос останавливается, привязка сбрасывается", async () => {
await core.clearUserBot(db, alice.id);
await bot.syncOwnBots();