use std::io::{self, Write};
use serde::Serialize;
use serde_json::Value;
use crate::error::Error;
use crate::surface::Surface;
pub const SCHEMA_VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, Serialize)]
pub struct TranscriptionResult {
pub schema_version: &'static str,
pub correlation_id: String,
pub target_resolved: String,
pub target_source: String,
pub file: String,
pub language: String,
pub language_source: String,
pub model: String,
pub device: u32,
pub duration_seconds: f64,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub segments: Option<Vec<Segment>>,
pub vad_chunks: usize,
pub hallucinations_removed: usize,
pub processing_time_ms: u128,
pub cold_load: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct Segment {
pub start: f64,
pub end: f64,
pub text: String,
}
pub fn write_value(value: &Value, surface: &Surface) -> Result<(), Error> {
let shaped = surface.apply(value.clone())?;
let mut stdout = io::stdout().lock();
if let Err(e) = serde_json::to_writer(&mut stdout, &shaped) {
return map_write(e);
}
if let Err(e) = stdout.write_all(b"\n") {
return map_io(e);
}
if let Err(e) = stdout.flush() {
return map_io(e);
}
Ok(())
}
pub fn write_json<T: Serialize>(value: &T, surface: &Surface) -> Result<(), Error> {
let raw = serde_json::to_value(value).map_err(|e| Error::Config(e.to_string()))?;
write_value(&raw, surface)
}
pub fn write_error(
err: &Error,
correlation_id: &str,
surface: &Surface,
target: Option<crate::error::TargetRef<'_>>,
) -> Result<(), Error> {
write_value(&err.to_json(correlation_id, target), surface)
}
fn map_write(err: serde_json::Error) -> Result<(), Error> {
if let Some(kind) = err.io_error_kind() {
return map_io(io::Error::new(kind, err));
}
Err(Error::Config(err.to_string()))
}
fn map_io(err: io::Error) -> Result<(), Error> {
if err.kind() == io::ErrorKind::BrokenPipe {
Err(Error::BrokenPipe)
} else {
Err(Error::Io(err))
}
}