@miadi/connector 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -2
- package/dist/approve.d.ts +7 -0
- package/dist/approve.js +52 -0
- package/dist/bin.js +8 -0
- package/dist/captions.d.ts +66 -2
- package/dist/captions.js +111 -57
- package/dist/local-transcription.d.ts +21 -0
- package/dist/local-transcription.js +111 -0
- package/dist/reading/contract.d.ts +1 -1
- package/dist/reading/host-runtime.d.ts +7 -0
- package/dist/reading/host-runtime.js +61 -0
- package/dist/reading/runtime-report.d.ts +21 -0
- package/dist/reading/runtime-report.js +40 -0
- package/dist/records.d.ts +1 -1
- package/dist/records.js +2 -0
- package/dist/review-events.d.ts +9 -0
- package/dist/review-events.js +59 -0
- package/dist/server.d.ts +5 -1
- package/dist/server.js +5 -0
- package/dist/tools.js +134 -10
- package/dist/transcript-intake.d.ts +24 -0
- package/dist/transcript-intake.js +118 -0
- package/dist/transcript-job.d.ts +190 -0
- package/dist/transcript-job.js +507 -0
- package/dist/transcript-routes.d.ts +14 -0
- package/dist/transcript-routes.js +92 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -20,8 +20,8 @@ Call `get_capabilities` first. It names the signed-in person, their Miadi API ti
|
|
|
20
20
|
|
|
21
21
|
| kind | tools |
|
|
22
22
|
|---|---|
|
|
23
|
-
| reads | `get_capabilities` `get_context` `list_circles` `get_circle` `list_sessions` `search_sessions` `get_session` `get_evidence` `read_episode_file` `get_evaluations` `get_narrative_beats` `review_lookup` `review_versions` `handoff_status` `list_records` `get_run_result` `mission_status` `provider_capabilities` `mission_model_preflight` `search` `fetch` `list_research_artifacts` `read_research_artifact` |
|
|
24
|
-
| contributions | `append_observation` `open_inquiry` `link_records` `propose_narrative_beat` `record_evaluation` `register_source_intent` `record_handoff` `update_handoff` `prepare_calendar_event` `save_research` |
|
|
23
|
+
| reads | `get_capabilities` `get_context` `list_circles` `get_circle` `list_sessions` `search_sessions` `get_session` `get_evidence` `read_episode_file` `get_evaluations` `get_narrative_beats` `review_lookup` `review_versions` `review_transcript_status` `handoff_status` `list_records` `get_run_result` `mission_status` `provider_capabilities` `mission_model_preflight` `search` `fetch` `list_research_artifacts` `read_research_artifact` |
|
|
24
|
+
| contributions | `ensure_review_transcript` `append_observation` `open_inquiry` `link_records` `propose_narrative_beat` `record_evaluation` `register_source_intent` `record_handoff` `update_handoff` `prepare_calendar_event` `save_research` |
|
|
25
25
|
| requests (approved by a person) | `propose_work` `propose_session_completion` `request_authorized_run` `request_session_steer` `revoke_session_steering` `request_review_operation` `request_deep_diver` `link_review_to_episode` `request_inquiry_episode` |
|
|
26
26
|
| decisions in the conversation | `show_decisions` (cards), `decide_request` (called by the card only) |
|
|
27
27
|
|
|
@@ -42,6 +42,19 @@ The model that asked cannot approve its own request.
|
|
|
42
42
|
|
|
43
43
|
`get_run_result` returns one `projection` of the decision, dispatch/completion state, receipt link and outstanding instructions. The in-chat card, approval page and Miadi's research page use that same read model. Asking `show_decisions` for an already-decided `record_id` shows its receipt without issuing another decision token. An in-flight card can refresh status without repeating the operation. A completed basic review with unapplied approval instructions remains open as **changes outstanding**, not falsely finished.
|
|
44
44
|
|
|
45
|
+
### A review's transcript (jgwill/Miadi#995)
|
|
46
|
+
|
|
47
|
+
A review is processed from the words of its video, so the connector acquires them itself, for a review made anywhere: the review service's own page, a manual edit, another client, or this connector's `create`.
|
|
48
|
+
|
|
49
|
+
- **`ensure_review_transcript`** starts one job per review. It needs a person who may contribute and who holds Miadi's write tier or registered the video's source. It asks no transcript decision and needs no pasted text: processing a review already carries that authority. It never overwrites, never creates a version and never publishes.
|
|
50
|
+
- **Order.** 1. The transcript the review service already holds is kept, read back and its digest recorded. 2. A source registered as withheld is held: nothing is read or stored until it is released. 3. The video's captions in its **spoken language** (the video's own `language`; YouTube auto-dubs a video into many languages and lists an `-orig` track for each dub, so the first `-orig` track is not taken, and a track in the wrong script is refused). 4. A transcription made on this host (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`, off until the operator enables it, one at a time, at most `MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES` minutes), only for a source its owner released. No model service is called and nothing costs money. 5. One `POST /api/reviews/{id}/transcript` with `overwrite: false` and the words' provenance. 6. A readback of the stored text, whose sha256 must match what was sent.
|
|
51
|
+
- **Progress and failure.** The answer comes within about 20 seconds with the job's state and goes on if it needs longer. `review_transcript_status` (read-only; `verify: true` reads the transcript back now) says `unknown`, `absent`, `acquiring`, `stored`, `held` or `failed`, with the stages, the attempts, `next_attempt_at` and `give_up_at`, the digest and coverage of what is stored, and for a failure its code, the remedy and who can do it (`operator`, `source_owner`). Captions that YouTube has not made yet are tried every 15 minutes for three days. A job a restart interrupted resumes from its receipt; a held job resumes when its source is released.
|
|
52
|
+
- **Links that need no card.** Every answer carries plain links: `status` (`/transcripts/<review id>`, a page that asks for a Miadi person token, or JSON with `Authorization: Bearer` and `?format=json`), `review`, `transcript_api` (the review service, with its token) and `job` (the job's record). `decision` is `null`: no decision stands between the request and the store. `review_lookup` and `review_versions` carry the same `transcript` state, and `show_decisions` and `get_run_result` answer with a line and a link for each request, so a client that draws no card still shows where things stand.
|
|
53
|
+
- **Every review, however it was made.** The review service announces `review.created` for each review it creates (its site, its API, a Shortcut, this connector), built with `@miadi/hooks-core`'s `buildReviewCreatedEvent` and signed like its other factory webhooks. Miadi's `/api/factory/review-events` normalizes it, records it in the event ledger (`@miadi/hooks-gateway`, `MIADI_EVENTS_DIR`, default `/srv/miadi/events`) and hands it to this connector's inbox, `inbox/connector-transcripts/`. Every 15 seconds the connector takes up to three: it asks the review service for the review again, starts the review's transcript job (a review that already holds one stores nothing, a withheld source is held), records the fact as the job's authority, and moves the file to `done/` or, with the reason, to `rejected/`. A fact waits in the inbox while the connector is down or the review service cannot be asked.
|
|
54
|
+
- **Endings are facts too.** When a job reaches `stored`, `held` or `failed`, the connector records `review.transcript.stored`, `review.transcript.held` or `review.transcript.failed` in the same ledger, on the review's trace (`miadi-review:<id>`) and naming the fact that caused it. The same ending recorded twice is one fact.
|
|
55
|
+
- **A worker's door.** A factory worker's account holds no Miadi API tier, so it cannot call the tools. `node packages/connector/scripts/ensure-transcript.mjs <review id> --mission run_request:<id> [--verify]` runs the same job under an approved run or work proposal that names the review (a person with the write tier approved it, and the job records the mission and who approved it). `--status` reads the state without a mission. A second process's attempt is left alone until it has written no stage for five minutes.
|
|
56
|
+
- **The host's reading runtime.** `get_capabilities` loads the module `MIADI_READING_ADAPTER` names (`scripts/host-reading-runtime.mjs` on gaia) and reports `reading_workflow.provider_runtime` from what it finds: `verified_transcript_only` while only caption acquisition has a provider. A reading acquires its transcript with the same reader and the same language rule, keeps durable stage receipts, and stops at the generation stages with a named blocker. Acquiring a transcript does not depend on the review service's import handshake.
|
|
57
|
+
|
|
45
58
|
### Revising a mission before it is decided
|
|
46
59
|
|
|
47
60
|
A mission is revised, never re-requested (jgwill/Miadi#919). `revise_pending_request` changes an agent run or work proposal that still awaits a decision, or that its approver sent back, and gives it its next version. Pass the version you read as `expected_version` and only the fields that change. The request keeps its id, its approval page and its one card. A change of `provider` is verified on the host again. Each revision is a record in the ledger carrying the whole new content, its reason, author, changed fields and `sha256` content hash, so every earlier version stays readable verbatim with `get_request_history`. A request already approved, queued or declined is refused: a change after a decision is a new request or a steer.
|
package/dist/approve.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ import { type RuntimeDeps } from "./runtime-steer.js";
|
|
|
21
21
|
import { type TmuxLike } from "./steer.js";
|
|
22
22
|
import { type ModelRoutingDeps } from "./claude-models.js";
|
|
23
23
|
import { type FetchCaptions } from "./captions.js";
|
|
24
|
+
import { type TranscriptJobIo } from "./transcript-job.js";
|
|
24
25
|
import { type ProviderAuthorization } from "./provider-policy.js";
|
|
25
26
|
export { factoryDir, runBriefFile, readQueueState } from "./queue-state.js";
|
|
26
27
|
export interface ApprovalDeps {
|
|
@@ -52,6 +53,10 @@ export interface ApprovalDeps {
|
|
|
52
53
|
modelRouting?: ModelRoutingDeps;
|
|
53
54
|
/** Reads a video's captions for an approved create; without it a create stores no transcript (tests, other embedders). */
|
|
54
55
|
captions?: FetchCaptions;
|
|
56
|
+
/** A transcription made on this host from the video's audio, tried for a released source whose captions are missing (jgwill/Miadi#995). */
|
|
57
|
+
localTranscription?: FetchCaptions;
|
|
58
|
+
/** The event folder (`MIADI_EVENTS_DIR`, default /srv/miadi/events): the ledger of facts and this connector's inbox. Absent, no fact is taken or announced. */
|
|
59
|
+
eventsDir?: string;
|
|
55
60
|
/** The link a named person decides a consent request on; set where the decision secret is held. */
|
|
56
61
|
consentLink?: (recordId: string) => string;
|
|
57
62
|
/** Where decision events go (default: one JSON line on stdout, the service journal); tests collect them. */
|
|
@@ -91,6 +96,8 @@ export declare function runBrief(record: ConnectorRecord, approver: MiadiPerson,
|
|
|
91
96
|
export declare function episodeReferences(record: ConnectorRecord): string[];
|
|
92
97
|
/** Whether the owner of this video's source registered it as withheld. */
|
|
93
98
|
export declare function sourceWithheld(records: ConnectorRecord[], videoId: unknown): boolean;
|
|
99
|
+
/** What a transcript job needs from this connector: its ledger, the review service's transcript door and the readers. */
|
|
100
|
+
export declare function transcriptJobIo(deps: Pick<ApprovalDeps, "config" | "ledger" | "fetchImpl" | "captions" | "localTranscription" | "log" | "eventsDir">): TranscriptJobIo;
|
|
94
101
|
export declare function executeApproved(record: ConnectorRecord, approver: MiadiPerson, deps: ApprovalDeps, instructions?: string): Promise<Record<string, unknown>>;
|
|
95
102
|
export declare function page(title: string, body: string): string;
|
|
96
103
|
/**
|
package/dist/approve.js
CHANGED
|
@@ -28,6 +28,9 @@ import { steerAttempts, steerSession, tmuxAdapter } from "./steer.js";
|
|
|
28
28
|
import { contentHash, versionOf } from "./revisions.js";
|
|
29
29
|
import { modelAttributes, routeModel } from "./claude-models.js";
|
|
30
30
|
import { TRANSCRIPT_RETRY_MS, transcriptStep } from "./captions.js";
|
|
31
|
+
import { reviewTranscriptService, settleTranscriptJobs } from "./transcript-job.js";
|
|
32
|
+
import { settleTranscriptRequests } from "./transcript-intake.js";
|
|
33
|
+
import { announceTranscriptOutcome, transcriptInbox } from "./review-events.js";
|
|
31
34
|
import { ReviewClient } from "./reviews.js";
|
|
32
35
|
import { sourceWordsOf } from "./source-words.js";
|
|
33
36
|
import { canReadReading } from "./reading/privacy.js";
|
|
@@ -213,6 +216,18 @@ async function callReview(deps, method, path, payload) {
|
|
|
213
216
|
export function sourceWithheld(records, videoId) {
|
|
214
217
|
return records.some((r) => r.kind === "source_intent" && r.body.video_id === videoId && r.body.readiness === "withheld");
|
|
215
218
|
}
|
|
219
|
+
/** What a transcript job needs from this connector: its ledger, the review service's transcript door and the readers. */
|
|
220
|
+
export function transcriptJobIo(deps) {
|
|
221
|
+
return {
|
|
222
|
+
ledger: deps.ledger,
|
|
223
|
+
service: reviewTranscriptService(deps.config, deps.fetchImpl),
|
|
224
|
+
...(deps.captions ? { captions: deps.captions } : {}),
|
|
225
|
+
...(deps.localTranscription ? { local: deps.localTranscription } : {}),
|
|
226
|
+
log: (event) => logDecision(deps, event),
|
|
227
|
+
// A job's ending is a fact of its own, recorded in the event ledger on the review's trace (jgwill/Miadi#995).
|
|
228
|
+
...(deps.eventsDir ? { outcome: (job, receipt) => announceTranscriptOutcome(job, receipt, deps.eventsDir) } : {}),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
216
231
|
function transcriptIo(deps) {
|
|
217
232
|
return {
|
|
218
233
|
withheld: (video) => sourceWithheld(current(deps.ledger.all()), video),
|
|
@@ -713,10 +728,47 @@ export async function settleTranscripts(deps) {
|
|
|
713
728
|
logDecision(deps, { phase: "transcript", record: r.id, video: waiting.video_id, outcome: next.outcome });
|
|
714
729
|
out.push(r.id);
|
|
715
730
|
}
|
|
731
|
+
// The jobs ensure_review_transcript started: a retry that is due, a stop that left one half done, a source released since.
|
|
732
|
+
out.push(...(await settleTranscriptJobs(transcriptJobIo(deps))));
|
|
716
733
|
return out;
|
|
717
734
|
}
|
|
718
735
|
/** Runs settleTranscripts while the connector runs, one pass at a time. */
|
|
719
736
|
export function startTranscriptSettling(deps) {
|
|
737
|
+
if (!deps.captions && !deps.localTranscription)
|
|
738
|
+
return;
|
|
739
|
+
// A job says when it tries again, so its pass looks every minute and acts only on a job that is due.
|
|
740
|
+
let jobsBusy = false;
|
|
741
|
+
const jobPass = (resumeAll) => {
|
|
742
|
+
if (jobsBusy)
|
|
743
|
+
return;
|
|
744
|
+
jobsBusy = true;
|
|
745
|
+
settleTranscriptJobs(transcriptJobIo(deps), { resumeAll })
|
|
746
|
+
.catch((error) => logDecision(deps, { phase: "transcript", error: error instanceof Error ? error.message : String(error) }))
|
|
747
|
+
.finally(() => {
|
|
748
|
+
jobsBusy = false;
|
|
749
|
+
});
|
|
750
|
+
};
|
|
751
|
+
// The first pass after a start resumes every job the stopped process left half done; later passes leave a fresh attempt to its own process.
|
|
752
|
+
setTimeout(() => jobPass(true), 15_000).unref();
|
|
753
|
+
setInterval(() => jobPass(false), 60_000).unref();
|
|
754
|
+
// The review.created facts the ingress hands to this connector's inbox; a pass takes them every 15 seconds (jgwill/Miadi#995).
|
|
755
|
+
let intakeBusy = false;
|
|
756
|
+
const intakePass = () => {
|
|
757
|
+
if (intakeBusy)
|
|
758
|
+
return;
|
|
759
|
+
intakeBusy = true;
|
|
760
|
+
if (!deps.eventsDir) {
|
|
761
|
+
intakeBusy = false;
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
settleTranscriptRequests(transcriptJobIo(deps), { dir: transcriptInbox(deps.eventsDir), reviewUrl: deps.config.reviewUrl, ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}) })
|
|
765
|
+
.catch((error) => logDecision(deps, { phase: "transcript", intake: true, error: error instanceof Error ? error.message : String(error) }))
|
|
766
|
+
.finally(() => {
|
|
767
|
+
intakeBusy = false;
|
|
768
|
+
});
|
|
769
|
+
};
|
|
770
|
+
setTimeout(intakePass, 20_000).unref();
|
|
771
|
+
setInterval(intakePass, 15_000).unref();
|
|
720
772
|
if (!deps.captions)
|
|
721
773
|
return;
|
|
722
774
|
let busy = false;
|
package/dist/bin.js
CHANGED
|
@@ -7,11 +7,14 @@ import { steeringTransport } from "./tools.js";
|
|
|
7
7
|
import { tmuxAdapter } from "./steer.js";
|
|
8
8
|
import { defaultRuntime } from "./runtime-steer.js";
|
|
9
9
|
import { youtubeCaptions } from "./captions.js";
|
|
10
|
+
import { localTranscriptionFromEnv } from "./local-transcription.js";
|
|
11
|
+
import { eventsDir } from "./review-events.js";
|
|
10
12
|
import { VERSION } from "./version.js";
|
|
11
13
|
const config = configFromEnv();
|
|
12
14
|
// The host's steering surface (jgwill/Miadi#909): the tmux server of the user the service runs as,
|
|
13
15
|
// reached only through request_session_steer inside an approved grant, at the mission's bound pane.
|
|
14
16
|
const tmux = tmuxAdapter();
|
|
17
|
+
const localTranscription = localTranscriptionFromEnv();
|
|
15
18
|
const { app } = createConnectorApp(config, {
|
|
16
19
|
identify: identifyThroughMiadi(config.miadiUrl),
|
|
17
20
|
tmux,
|
|
@@ -24,6 +27,10 @@ const { app } = createConnectorApp(config, {
|
|
|
24
27
|
},
|
|
25
28
|
// An approved create stores the video's YouTube captions as the review's transcript, with no model call.
|
|
26
29
|
captions: youtubeCaptions,
|
|
30
|
+
// A transcription made on this host, tried after missing captions for a released source, only where the operator enabled it (jgwill/Miadi#995).
|
|
31
|
+
...(localTranscription ? { localTranscription } : {}),
|
|
32
|
+
// The facts the review service announces, taken from this connector's inbox, and the outcomes it announces (jgwill/Miadi#995).
|
|
33
|
+
eventsDir: eventsDir(),
|
|
27
34
|
});
|
|
28
35
|
app.listen(config.port, config.host, () => {
|
|
29
36
|
console.log(`@miadi/connector ${VERSION} on http://${config.host}:${config.port}`);
|
|
@@ -32,5 +39,6 @@ app.listen(config.port, config.host, () => {
|
|
|
32
39
|
console.log(` reviews: ${config.reviewUrl} (search ${config.reviewToken ? "enabled" : "disabled: no MIADI_REVIEW_TOKEN"})`);
|
|
33
40
|
console.log(` state: ${config.stateDir}`);
|
|
34
41
|
const steering = steeringTransport(tmux);
|
|
42
|
+
console.log(` transcripts: captions on, local transcription ${localTranscription ? `on (${process.env.MIADI_TRANSCRIPT_LOCAL})` : "off"}, review events from ${eventsDir()}`);
|
|
35
43
|
console.log(` steering: ${steering.transport}${steering.reason ? ` (${steering.reason})` : ""}`);
|
|
36
44
|
});
|
package/dist/captions.d.ts
CHANGED
|
@@ -10,11 +10,25 @@ export type CaptionsAnswer = {
|
|
|
10
10
|
last_ms: number;
|
|
11
11
|
duration_s?: number;
|
|
12
12
|
fetched_at: string;
|
|
13
|
-
|
|
13
|
+
kind?: CaptionKind;
|
|
14
|
+
basis?: string;
|
|
15
|
+
method?: TranscriptMethod;
|
|
16
|
+
segments?: {
|
|
17
|
+
start_ms: number;
|
|
18
|
+
end_ms: number;
|
|
19
|
+
text: string;
|
|
20
|
+
}[];
|
|
21
|
+
}
|
|
22
|
+
/** `absent`: the video has no usable caption track at all, as opposed to a track not made yet or a reader that failed. */
|
|
23
|
+
| {
|
|
14
24
|
state: "none_yet";
|
|
15
25
|
message?: string;
|
|
26
|
+
absent?: boolean;
|
|
16
27
|
};
|
|
17
28
|
export type FetchCaptions = (videoId: string) => Promise<CaptionsAnswer>;
|
|
29
|
+
export type CaptionKind = "manual" | "automatic" | "local";
|
|
30
|
+
/** How the words were obtained: the uploader's or YouTube's captions, or a transcription made on this host. */
|
|
31
|
+
export type TranscriptMethod = "youtube_captions" | "local_transcription";
|
|
18
32
|
export interface TranscriptReceipt {
|
|
19
33
|
outcome: "stored" | "already_present" | "waiting_for_captions" | "held_source_withheld" | "no_captions" | "no_review";
|
|
20
34
|
video_id: string;
|
|
@@ -28,6 +42,10 @@ export interface TranscriptReceipt {
|
|
|
28
42
|
covers?: string;
|
|
29
43
|
stored_at?: string;
|
|
30
44
|
message?: string;
|
|
45
|
+
/** The caption track or transcription the words came from, and why that one (jgwill/Miadi#995). */
|
|
46
|
+
track?: string;
|
|
47
|
+
method?: TranscriptMethod;
|
|
48
|
+
basis?: string;
|
|
31
49
|
}
|
|
32
50
|
export interface TranscriptIo {
|
|
33
51
|
withheld: (videoId: string) => boolean;
|
|
@@ -52,13 +70,55 @@ export declare function transcriptFromJson3(raw: string, o: {
|
|
|
52
70
|
language: string;
|
|
53
71
|
duration_s?: number;
|
|
54
72
|
fetched_at: string;
|
|
73
|
+
kind?: CaptionKind;
|
|
74
|
+
engine?: string;
|
|
55
75
|
}): {
|
|
56
76
|
text: string;
|
|
57
77
|
words: number;
|
|
58
78
|
first_ms: number;
|
|
59
79
|
last_ms: number;
|
|
80
|
+
/** The timecoded paragraphs, for a reader that checks claims against where they were said. */
|
|
81
|
+
segments: {
|
|
82
|
+
start_ms: number;
|
|
83
|
+
end_ms: number;
|
|
84
|
+
text: string;
|
|
85
|
+
}[];
|
|
60
86
|
} | null;
|
|
61
|
-
/**
|
|
87
|
+
/** What yt-dlp says of a video, from its info.json: the spoken language and the tracks YouTube lists. */
|
|
88
|
+
export interface CaptionInfo {
|
|
89
|
+
language?: string | null;
|
|
90
|
+
duration?: number;
|
|
91
|
+
title?: string;
|
|
92
|
+
subtitles?: Record<string, unknown>;
|
|
93
|
+
automatic_captions?: Record<string, unknown>;
|
|
94
|
+
}
|
|
95
|
+
export type CaptionChoice = {
|
|
96
|
+
track: string;
|
|
97
|
+
language: string;
|
|
98
|
+
kind: "manual" | "automatic";
|
|
99
|
+
basis: string;
|
|
100
|
+
} | {
|
|
101
|
+
none: string;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* The one caption track that holds what the video's speaker said.
|
|
105
|
+
*
|
|
106
|
+
* YouTube auto-dubs a video into many languages and lists an `-orig` captions track for each dub, so
|
|
107
|
+
* "any `-orig` track" can be a dub (jgwill/Miadi#995: the first one found for an English video was
|
|
108
|
+
* Bengali). The spoken language is the video's own `language`. A track the uploader wrote in that
|
|
109
|
+
* language comes first, then YouTube's original-language automatic track. With no stated language a
|
|
110
|
+
* single `-orig` track is the answer and several are refused, never guessed.
|
|
111
|
+
*/
|
|
112
|
+
export declare function chooseCaptionTrack(info: CaptionInfo): CaptionChoice;
|
|
113
|
+
/** True when the words are mostly not in the script their language is written in: a wrong or dubbed track, caught before it is stored. */
|
|
114
|
+
export declare function scriptMismatch(text: string, language: string): boolean;
|
|
115
|
+
/** Runs one yt-dlp command in a directory of its own; tests inject their own. */
|
|
116
|
+
export type YtDlp = (args: string[], cwd: string) => Promise<void>;
|
|
117
|
+
/**
|
|
118
|
+
* The video's captions in the language it is spoken in, through a local yt-dlp in a directory of its own.
|
|
119
|
+
* One call reads what the video lists (its spoken language and tracks), a second downloads that one track.
|
|
120
|
+
*/
|
|
121
|
+
export declare function makeYoutubeCaptions(ytdlp?: YtDlp): FetchCaptions;
|
|
62
122
|
export declare const youtubeCaptions: FetchCaptions;
|
|
63
123
|
/**
|
|
64
124
|
* One attempt at the transcript of a created review. A source its owner registered as withheld is
|
|
@@ -71,5 +131,9 @@ export declare function transcriptStep(input: {
|
|
|
71
131
|
supplied?: string;
|
|
72
132
|
source?: string;
|
|
73
133
|
}, io: TranscriptIo): Promise<TranscriptReceipt>;
|
|
134
|
+
/** Where found words came from, as a receipt says it. */
|
|
135
|
+
export declare function sourceOf(a: Extract<CaptionsAnswer, {
|
|
136
|
+
state: "found";
|
|
137
|
+
}>): string;
|
|
74
138
|
/** What a transcript receipt says on a request's card and approval page. */
|
|
75
139
|
export declare function transcriptLines(transcript: unknown): string[];
|
package/dist/captions.js
CHANGED
|
@@ -50,10 +50,11 @@ export function transcriptFromJson3(raw, o) {
|
|
|
50
50
|
const start = e.tStartMs ?? 0;
|
|
51
51
|
const open = paragraphs[paragraphs.length - 1];
|
|
52
52
|
if (!open || start - end >= PAUSE_MS || words.startsWith(">>") || open.text.length >= PARAGRAPH_CHARS)
|
|
53
|
-
paragraphs.push({ at: start, text: words });
|
|
53
|
+
paragraphs.push({ at: start, end: start + (e.dDurationMs ?? 0), text: words });
|
|
54
54
|
else
|
|
55
55
|
open.text += ` ${words}`;
|
|
56
56
|
end = Math.max(end, start + (e.dDurationMs ?? 0));
|
|
57
|
+
paragraphs[paragraphs.length - 1].end = Math.max(paragraphs[paragraphs.length - 1].end, end);
|
|
57
58
|
if (first < 0)
|
|
58
59
|
first = start;
|
|
59
60
|
last = end;
|
|
@@ -61,65 +62,112 @@ export function transcriptFromJson3(raw, o) {
|
|
|
61
62
|
if (!paragraphs.length)
|
|
62
63
|
return null;
|
|
63
64
|
const covered = { first_ms: first, last_ms: last, duration_s: o.duration_s };
|
|
64
|
-
const
|
|
65
|
+
const what = o.kind === "manual"
|
|
66
|
+
? "YouTube captions written for the video"
|
|
67
|
+
: o.kind === "local"
|
|
68
|
+
? `Transcription made on this host${o.engine ? ` by ${o.engine}` : ""} from the video's audio`
|
|
69
|
+
: "YouTube automatic captions";
|
|
70
|
+
const header = `(${what}, language ${o.language}, uncorrected, fetched ${o.fetched_at.slice(0, 10)}. They run from ${coverage(covered)}. Names may be misheard, and a voice the ${o.kind === "local" ? "transcription" : "captions"} did not catch is absent.)`;
|
|
65
71
|
const body = paragraphs.map((p) => `[${clock(p.at)}] ${p.text}`).join("\n\n");
|
|
66
|
-
return {
|
|
72
|
+
return {
|
|
73
|
+
text: `${header}\n\n${body}\n`,
|
|
74
|
+
words: paragraphs.reduce((n, p) => n + p.text.split(" ").length, 0),
|
|
75
|
+
first_ms: first,
|
|
76
|
+
last_ms: last,
|
|
77
|
+
/** The timecoded paragraphs, for a reader that checks claims against where they were said. */
|
|
78
|
+
segments: paragraphs.map((p) => ({ start_ms: p.at, end_ms: p.end, text: p.text })),
|
|
79
|
+
};
|
|
67
80
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
"
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
81
|
+
/**
|
|
82
|
+
* The one caption track that holds what the video's speaker said.
|
|
83
|
+
*
|
|
84
|
+
* YouTube auto-dubs a video into many languages and lists an `-orig` captions track for each dub, so
|
|
85
|
+
* "any `-orig` track" can be a dub (jgwill/Miadi#995: the first one found for an English video was
|
|
86
|
+
* Bengali). The spoken language is the video's own `language`. A track the uploader wrote in that
|
|
87
|
+
* language comes first, then YouTube's original-language automatic track. With no stated language a
|
|
88
|
+
* single `-orig` track is the answer and several are refused, never guessed.
|
|
89
|
+
*/
|
|
90
|
+
export function chooseCaptionTrack(info) {
|
|
91
|
+
const auto = Object.keys(info.automatic_captions ?? {});
|
|
92
|
+
const manual = Object.keys(info.subtitles ?? {}).filter((k) => k !== "live_chat");
|
|
93
|
+
const stated = typeof info.language === "string" ? info.language.split(/[-_]/)[0].toLowerCase() : "";
|
|
94
|
+
if (!stated || stated === "und") {
|
|
95
|
+
const orig = auto.filter((k) => k.endsWith("-orig"));
|
|
96
|
+
if (orig.length === 1)
|
|
97
|
+
return { track: orig[0], language: orig[0].slice(0, -"-orig".length), kind: "automatic", basis: "the video lists one original-language track and names no spoken language" };
|
|
98
|
+
return { none: orig.length ? `The video names no spoken language and lists ${orig.length} original-language caption tracks, so none is taken for what was said.` : "The video lists no captions." };
|
|
99
|
+
}
|
|
100
|
+
const own = (k) => k.split(/[-_]/)[0].toLowerCase() === stated;
|
|
101
|
+
const written = manual.find((k) => k.toLowerCase() === String(info.language).toLowerCase()) ?? manual.find(own);
|
|
102
|
+
if (written)
|
|
103
|
+
return { track: written, language: stated, kind: "manual", basis: `captions written for the video in its spoken language (${info.language})` };
|
|
104
|
+
if (auto.includes(`${stated}-orig`))
|
|
105
|
+
return { track: `${stated}-orig`, language: stated, kind: "automatic", basis: `YouTube's original-language automatic track for the spoken language (${info.language})` };
|
|
106
|
+
// An older listing names the original track without the suffix, and only when no track carries one.
|
|
107
|
+
if (!auto.some((k) => k.endsWith("-orig")) && auto.includes(stated))
|
|
108
|
+
return { track: stated, language: stated, kind: "automatic", basis: `YouTube's automatic track for the spoken language (${info.language})` };
|
|
109
|
+
return { none: `The video is spoken in ${info.language} and has no caption track in that language yet.` };
|
|
110
|
+
}
|
|
111
|
+
const LATIN_LANGUAGES = new Set(["en", "fr", "de", "es", "it", "pt", "nl", "sv", "da", "no", "fi", "pl", "cs", "ro", "id", "tr"]);
|
|
112
|
+
/** True when the words are mostly not in the script their language is written in: a wrong or dubbed track, caught before it is stored. */
|
|
113
|
+
export function scriptMismatch(text, language) {
|
|
114
|
+
if (!LATIN_LANGUAGES.has(language.split(/[-_]/)[0].toLowerCase()))
|
|
115
|
+
return false;
|
|
116
|
+
const letters = text.match(/\p{L}/gu) ?? [];
|
|
117
|
+
if (letters.length < 40)
|
|
118
|
+
return false;
|
|
119
|
+
const foreign = letters.filter((c) => !/\p{Script=Latin}/u.test(c)).length;
|
|
120
|
+
return foreign / letters.length > 0.2;
|
|
121
|
+
}
|
|
122
|
+
const execYtDlp = async (args, cwd) => {
|
|
123
|
+
await promisify(execFile)("uvx", ["--quiet", "yt-dlp@latest", "--ignore-config", "--js-runtimes", `node:${process.execPath}`, "--no-playlist", "--no-warnings", ...args], { cwd, timeout: 180_000, maxBuffer: 16 * 1024 * 1024 });
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* The video's captions in the language it is spoken in, through a local yt-dlp in a directory of its own.
|
|
127
|
+
* One call reads what the video lists (its spoken language and tracks), a second downloads that one track.
|
|
128
|
+
*/
|
|
129
|
+
export function makeYoutubeCaptions(ytdlp = execYtDlp) {
|
|
130
|
+
return async (videoId) => {
|
|
131
|
+
if (!VIDEO_ID.test(videoId))
|
|
132
|
+
return { state: "none_yet", message: "Not a YouTube video id." };
|
|
133
|
+
const dir = mkdtempSync(join(tmpdir(), "miadi-captions-"));
|
|
134
|
+
const url = `https://youtu.be/${videoId}`;
|
|
100
135
|
try {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
136
|
+
await ytdlp(["--skip-download", "--write-info-json", "--output", "video.%(ext)s", url], dir);
|
|
137
|
+
let info;
|
|
138
|
+
try {
|
|
139
|
+
info = JSON.parse(readFileSync(join(dir, "video.info.json"), "utf8"));
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return { state: "none_yet", message: "YouTube answered without the video's description of itself." };
|
|
143
|
+
}
|
|
144
|
+
const choice = chooseCaptionTrack(info);
|
|
145
|
+
if ("none" in choice)
|
|
146
|
+
return { state: "none_yet", message: choice.none, absent: true };
|
|
147
|
+
await ytdlp(["--skip-download", choice.kind === "manual" ? "--write-subs" : "--write-auto-subs", "--sub-langs", choice.track, "--sub-format", "json3", "--output", "video.%(ext)s", url], dir);
|
|
148
|
+
const file = readdirSync(dir).find((f) => f === `video.${choice.track}.json3`);
|
|
149
|
+
if (!file)
|
|
150
|
+
return { state: "none_yet", message: `YouTube lists the ${choice.track} track but has not produced it yet.` };
|
|
151
|
+
const duration_s = typeof info.duration === "number" && info.duration > 0 ? info.duration : undefined;
|
|
152
|
+
const fetched_at = new Date().toISOString();
|
|
153
|
+
const rendered = transcriptFromJson3(readFileSync(join(dir, file), "utf8"), { language: choice.language, fetched_at, kind: choice.kind, ...(duration_s ? { duration_s } : {}) });
|
|
154
|
+
if (!rendered)
|
|
155
|
+
return { state: "none_yet", message: "The caption track holds no words." };
|
|
156
|
+
if (scriptMismatch(rendered.text, choice.language))
|
|
157
|
+
return { state: "none_yet", message: `The ${choice.track} track is not written in ${choice.language}, so it is not stored as what the video's speaker said.`, absent: true };
|
|
158
|
+
return { state: "found", ...rendered, language: choice.language, track: choice.track, kind: choice.kind, basis: choice.basis, method: "youtube_captions", ...(duration_s ? { duration_s } : {}), fetched_at };
|
|
104
159
|
}
|
|
105
|
-
catch {
|
|
106
|
-
|
|
160
|
+
catch (error) {
|
|
161
|
+
// A refusal or a timeout today may answer tomorrow, so it waits with the captions that are not there yet.
|
|
162
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
163
|
+
return { state: "none_yet", message: message.split("\n").filter(Boolean).pop()?.slice(0, 300) ?? "yt-dlp failed" };
|
|
107
164
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
catch (error) {
|
|
115
|
-
// A refusal or a timeout today may answer tomorrow, so it waits with the captions that are not there yet.
|
|
116
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
117
|
-
return { state: "none_yet", message: message.split("\n").filter(Boolean).pop()?.slice(0, 300) ?? "yt-dlp failed" };
|
|
118
|
-
}
|
|
119
|
-
finally {
|
|
120
|
-
rmSync(dir, { recursive: true, force: true });
|
|
121
|
-
}
|
|
122
|
-
};
|
|
165
|
+
finally {
|
|
166
|
+
rmSync(dir, { recursive: true, force: true });
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export const youtubeCaptions = makeYoutubeCaptions();
|
|
123
171
|
/**
|
|
124
172
|
* One attempt at the transcript of a created review. A source its owner registered as withheld is
|
|
125
173
|
* neither read nor stored until it is released: the transcript the service holds is public.
|
|
@@ -157,13 +205,19 @@ export async function transcriptStep(input, io) {
|
|
|
157
205
|
return {
|
|
158
206
|
...base,
|
|
159
207
|
outcome: "stored",
|
|
160
|
-
source: input.source ?? (supplied ? "supplied with the request" :
|
|
208
|
+
source: input.source ?? (supplied ? "supplied with the request" : sourceOf(answer)),
|
|
161
209
|
chars: text.length,
|
|
162
210
|
sha256: createHash("sha256").update(text).digest("hex"),
|
|
163
211
|
stored_at: new Date(now).toISOString(),
|
|
164
|
-
...(answer?.state === "found"
|
|
212
|
+
...(answer?.state === "found"
|
|
213
|
+
? { language: answer.language, words: answer.words, covers: coverage(answer), track: answer.track, method: answer.method ?? "youtube_captions", ...(answer.basis ? { basis: answer.basis } : {}) }
|
|
214
|
+
: {}),
|
|
165
215
|
};
|
|
166
216
|
}
|
|
217
|
+
/** Where found words came from, as a receipt says it. */
|
|
218
|
+
export function sourceOf(a) {
|
|
219
|
+
return a.method === "local_transcription" ? `local transcription (${a.track})` : `YouTube captions (${a.track})`;
|
|
220
|
+
}
|
|
167
221
|
/** What a transcript receipt says on a request's card and approval page. */
|
|
168
222
|
export function transcriptLines(transcript) {
|
|
169
223
|
const t = transcript;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type FetchCaptions, type YtDlp } from "./captions.js";
|
|
2
|
+
export interface WhisperOutput {
|
|
3
|
+
language: string;
|
|
4
|
+
duration?: number;
|
|
5
|
+
segments: {
|
|
6
|
+
start: number;
|
|
7
|
+
end: number;
|
|
8
|
+
text: string;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
/** Runs the engine on one audio file. Tests inject their own; production runs faster-whisper through uv. */
|
|
12
|
+
export type Whisper = (audioPath: string, model: string, language: string | null) => Promise<WhisperOutput>;
|
|
13
|
+
export interface LocalOptions {
|
|
14
|
+
model?: string;
|
|
15
|
+
maxMinutes?: number;
|
|
16
|
+
ytdlp?: YtDlp;
|
|
17
|
+
whisper?: Whisper;
|
|
18
|
+
}
|
|
19
|
+
export declare function makeLocalTranscription(o?: LocalOptions): FetchCaptions;
|
|
20
|
+
/** The host's choice: set only when its operator enabled it. */
|
|
21
|
+
export declare function localTranscriptionFromEnv(env?: NodeJS.ProcessEnv, o?: Pick<LocalOptions, "ytdlp" | "whisper">): FetchCaptions | undefined;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A transcription made on this host, for a video whose captions are missing (jgwill/Miadi#995).
|
|
3
|
+
*
|
|
4
|
+
* It is the second reader a transcript job tries, after YouTube's captions, and only where the host's
|
|
5
|
+
* operator enabled it (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`) and the source is released: it downloads the
|
|
6
|
+
* video's audio, which a withheld or unregistered source does not allow. It calls no model service and costs
|
|
7
|
+
* no money. The resources are bounded: one transcription at a time, a longest video
|
|
8
|
+
* (`MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES`, default 90) and a time limit.
|
|
9
|
+
*/
|
|
10
|
+
import { execFile } from "node:child_process";
|
|
11
|
+
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { promisify } from "node:util";
|
|
15
|
+
import { transcriptFromJson3 } from "./captions.js";
|
|
16
|
+
const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
|
|
17
|
+
// The audio is decoded by ffmpeg, not by faster-whisper's own decoder, whose `av` dependency has resolved to a
|
|
18
|
+
// version without the keyword it passes (open() got an unexpected keyword argument 'metadata_errors').
|
|
19
|
+
const SCRIPT = `
|
|
20
|
+
import sys, json, subprocess
|
|
21
|
+
import numpy as np
|
|
22
|
+
from faster_whisper import WhisperModel
|
|
23
|
+
audio_path, model, lang = sys.argv[1], sys.argv[2], (sys.argv[3] if len(sys.argv) > 3 else "") or None
|
|
24
|
+
pcm = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", audio_path, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"], check=True, capture_output=True).stdout
|
|
25
|
+
audio = np.frombuffer(pcm, dtype=np.float32)
|
|
26
|
+
m = WhisperModel(model, device="cpu", compute_type="int8")
|
|
27
|
+
segments, info = m.transcribe(audio, language=lang, vad_filter=True)
|
|
28
|
+
out = [{"start": s.start, "end": s.end, "text": s.text} for s in segments]
|
|
29
|
+
print(json.dumps({"language": info.language, "duration": info.duration, "segments": out}))
|
|
30
|
+
`;
|
|
31
|
+
const execWhisper = async (audioPath, model, language) => {
|
|
32
|
+
const { stdout } = await promisify(execFile)("uv", ["run", "--no-project", "--quiet", "--with", "faster-whisper", "python", "-c", SCRIPT, audioPath, model, language ?? ""], {
|
|
33
|
+
timeout: 60 * 60_000,
|
|
34
|
+
maxBuffer: 128 * 1024 * 1024,
|
|
35
|
+
});
|
|
36
|
+
return JSON.parse(stdout.trim().split("\n").pop() ?? "{}");
|
|
37
|
+
};
|
|
38
|
+
const execYtDlp = async (args, cwd) => {
|
|
39
|
+
await promisify(execFile)("uvx", ["--quiet", "yt-dlp@latest", "--ignore-config", "--js-runtimes", `node:${process.execPath}`, "--no-playlist", "--no-warnings", ...args], { cwd, timeout: 600_000, maxBuffer: 16 * 1024 * 1024 });
|
|
40
|
+
};
|
|
41
|
+
/** Only one transcription runs at a time on this host. */
|
|
42
|
+
let busy = Promise.resolve();
|
|
43
|
+
export function makeLocalTranscription(o = {}) {
|
|
44
|
+
const model = o.model ?? "base";
|
|
45
|
+
const maxMinutes = o.maxMinutes ?? 90;
|
|
46
|
+
const ytdlp = o.ytdlp ?? execYtDlp;
|
|
47
|
+
const whisper = o.whisper ?? execWhisper;
|
|
48
|
+
return (videoId) => {
|
|
49
|
+
const turn = busy.then(() => transcribe(videoId));
|
|
50
|
+
busy = turn.catch(() => undefined);
|
|
51
|
+
return turn;
|
|
52
|
+
};
|
|
53
|
+
async function transcribe(videoId) {
|
|
54
|
+
if (!VIDEO_ID.test(videoId))
|
|
55
|
+
return { state: "none_yet", message: "Not a YouTube video id." };
|
|
56
|
+
const dir = mkdtempSync(join(tmpdir(), "miadi-local-transcription-"));
|
|
57
|
+
const url = `https://youtu.be/${videoId}`;
|
|
58
|
+
try {
|
|
59
|
+
await ytdlp(["--skip-download", "--write-info-json", "--output", "video.%(ext)s", url], dir);
|
|
60
|
+
let info = {};
|
|
61
|
+
try {
|
|
62
|
+
info = JSON.parse(readFileSync(join(dir, "video.info.json"), "utf8"));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return { state: "none_yet", message: "YouTube answered without the video's description of itself, so its length is unknown." };
|
|
66
|
+
}
|
|
67
|
+
const minutes = typeof info.duration === "number" ? info.duration / 60 : Infinity;
|
|
68
|
+
if (minutes > maxMinutes)
|
|
69
|
+
return { state: "none_yet", message: `The video runs ${Number.isFinite(minutes) ? Math.round(minutes) : "an unknown number of"} minutes, past this host's local transcription limit of ${maxMinutes}.` };
|
|
70
|
+
await ytdlp(["-f", "bestaudio[ext=m4a]/bestaudio", "--output", "audio.%(ext)s", url], dir);
|
|
71
|
+
const audio = readdirSync(dir).find((f) => f.startsWith("audio."));
|
|
72
|
+
if (!audio)
|
|
73
|
+
return { state: "none_yet", message: "The video's audio could not be downloaded." };
|
|
74
|
+
const hint = typeof info.language === "string" ? info.language.split(/[-_]/)[0].toLowerCase() : null;
|
|
75
|
+
const out = await whisper(join(dir, audio), model, hint);
|
|
76
|
+
const events = out.segments
|
|
77
|
+
.filter((s) => s.text.trim())
|
|
78
|
+
.map((s) => ({ tStartMs: Math.round(s.start * 1000), dDurationMs: Math.max(0, Math.round((s.end - s.start) * 1000)), segs: [{ utf8: s.text }] }));
|
|
79
|
+
const fetched_at = new Date().toISOString();
|
|
80
|
+
const duration_s = out.duration ?? (typeof info.duration === "number" ? info.duration : undefined);
|
|
81
|
+
const rendered = transcriptFromJson3(JSON.stringify({ events }), { language: out.language, fetched_at, kind: "local", engine: `faster-whisper ${model}`, ...(duration_s ? { duration_s } : {}) });
|
|
82
|
+
if (!rendered)
|
|
83
|
+
return { state: "none_yet", message: "The local transcription produced no words." };
|
|
84
|
+
return {
|
|
85
|
+
state: "found",
|
|
86
|
+
...rendered,
|
|
87
|
+
language: out.language,
|
|
88
|
+
track: `faster-whisper-${model}`,
|
|
89
|
+
kind: "local",
|
|
90
|
+
basis: `transcribed on this host from the video's audio, because YouTube had no usable captions (spoken language ${info.language ?? "not stated"})`,
|
|
91
|
+
method: "local_transcription",
|
|
92
|
+
...(duration_s ? { duration_s } : {}),
|
|
93
|
+
fetched_at,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
98
|
+
return { state: "none_yet", message: `Local transcription failed: ${message.split("\n").filter(Boolean).pop()?.slice(0, 300) ?? "unknown error"}` };
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
rmSync(dir, { recursive: true, force: true });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** The host's choice: set only when its operator enabled it. */
|
|
106
|
+
export function localTranscriptionFromEnv(env = process.env, o = {}) {
|
|
107
|
+
if (env.MIADI_TRANSCRIPT_LOCAL !== "faster-whisper")
|
|
108
|
+
return undefined;
|
|
109
|
+
const max = Number(env.MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES);
|
|
110
|
+
return makeLocalTranscription({ model: env.MIADI_TRANSCRIPT_LOCAL_MODEL || "base", ...(Number.isFinite(max) && max > 0 ? { maxMinutes: max } : {}), ...o });
|
|
111
|
+
}
|
|
@@ -35,9 +35,9 @@ export declare const sourcePart: z.ZodObject<{
|
|
|
35
35
|
locator: z.ZodString;
|
|
36
36
|
provider: z.ZodString;
|
|
37
37
|
caption_kind: z.ZodEnum<{
|
|
38
|
-
supplied: "supplied";
|
|
39
38
|
manual: "manual";
|
|
40
39
|
automatic: "automatic";
|
|
40
|
+
supplied: "supplied";
|
|
41
41
|
local_stt: "local_stt";
|
|
42
42
|
}>;
|
|
43
43
|
fetched_at: z.ZodString;
|