Skip to main content

fauna_api/marmot/
media.rs

1use std::collections::HashMap;
2use std::sync::{Mutex, PoisonError};
3
4use base64::Engine;
5use base64::engine::general_purpose::STANDARD;
6use chrono::{DateTime, SecondsFormat, Utc};
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9
10use crate::authentification::CredentialsOrApiKey;
11use crate::billing::Rate;
12use crate::drive::{FileDates, Progress, from_bytes, parse_stream};
13use crate::error::{Error, Result};
14use crate::http::{client, encode, ok, progress_body};
15use crate::parrot::generative::{File, Part, TextPart};
16
17pub const ATTACHMENT_TYPES: [(&str, &str); 15] = [
18    ("image/jpeg", "image"),
19    ("image/png", "image"),
20    ("image/webp", "image"),
21    ("image/heic", "image"),
22    ("image/heif", "image"),
23    ("audio/mpeg", "audio_file"),
24    ("audio/wav", "audio_file"),
25    ("video/mp4", "movie"),
26    ("video/webm", "movie"),
27    ("video/quicktime", "movie"),
28    ("application/pdf", "picture_as_pdf"),
29    ("text/plain", "description"),
30    ("text/markdown", "description"),
31    ("text/csv", "table_chart"),
32    ("text/html", "language"),
33];
34
35/// Resolve a usable MIME when a file's type is unknown (common for HEIC).
36pub fn mime_from_file_name(name: &str) -> Option<&'static str> {
37    let extension = if name.contains('.') {
38        name.rsplit('.').next().unwrap_or_default().to_lowercase()
39    } else {
40        String::new()
41    };
42    match extension.as_str() {
43        "jpg" | "jpeg" => Some("image/jpeg"),
44        "png" => Some("image/png"),
45        "webp" => Some("image/webp"),
46        "heic" => Some("image/heic"),
47        "heif" => Some("image/heif"),
48        "mp3" => Some("audio/mpeg"),
49        "wav" => Some("audio/wav"),
50        "mp4" => Some("video/mp4"),
51        "webm" => Some("video/webm"),
52        "mov" | "qt" => Some("video/quicktime"),
53        "pdf" => Some("application/pdf"),
54        "txt" => Some("text/plain"),
55        "md" | "markdown" => Some("text/markdown"),
56        "csv" => Some("text/csv"),
57        "html" | "htm" => Some("text/html"),
58        "json" => Some("application/json"),
59        "xml" => Some("application/xml"),
60        _ => None,
61    }
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct Website {
67    pub url: String,
68    pub content_type: String,
69    pub title: String,
70    pub description: String,
71}
72
73/// How content is pulled from URLs: `datacenter` fetches directly from Cloud Run
74/// egress, `residential` routes through residential proxies for sites that block
75/// datacenter IPs.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "lowercase")]
78pub enum ProxyMode {
79    Residential,
80    Datacenter,
81}
82
83/// How a document source is pulled: `extraction` parses HTML/PDF text directly,
84/// `render` reads the page as a browser on the workspace's computer renders it,
85/// `virtualized` has the machine agent work the page there toward a goal. Both
86/// need the workspace's computer; without one, research extracts. A dataset
87/// enables one or more; with several, the research agent picks per source.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum DocumentMode {
91    Extraction,
92    Render,
93    Virtualized,
94}
95
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase")]
98pub struct ContentTypeInfo {
99    pub content_type: String,
100    pub name: String,
101    pub extensions: Vec<String>,
102}
103
104static TYPES_CACHE: Mutex<Option<HashMap<String, Vec<ContentTypeInfo>>>> = Mutex::new(None);
105
106pub async fn get_types() -> Result<HashMap<String, Vec<ContentTypeInfo>>> {
107    if let Some(types) = TYPES_CACHE
108        .lock()
109        .unwrap_or_else(PoisonError::into_inner)
110        .clone()
111    {
112        return Ok(types);
113    }
114
115    let response = client()
116        .get(format!("{}/media/types", super::get_url()))
117        .send()
118        .await?;
119    let types: HashMap<String, Vec<ContentTypeInfo>> = ok(response).await?.json().await?;
120
121    *TYPES_CACHE.lock().unwrap_or_else(PoisonError::into_inner) = Some(types.clone());
122    Ok(types)
123}
124
125/// `Uint8Array | Uint8Array[]` in the TypeScript SDK: one body, or one per segment.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum BytesOrBytesList {
128    Bytes(Vec<u8>),
129    BytesList(Vec<Vec<u8>>),
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct PullResponse {
134    pub data: BytesOrBytesList,
135    pub content_type: String,
136}
137
138/// The `options` argument of `query`.
139#[derive(Debug, Clone, Default)]
140pub struct QueryOptions {
141    pub cursor: u32,
142    pub max: u32,
143    pub start: Option<DateTime<Utc>>,
144    pub end: Option<DateTime<Utc>>,
145}
146
147pub async fn query(
148    authorization: &CredentialsOrApiKey,
149    query: &str,
150    options: QueryOptions,
151) -> Result<Vec<Website>> {
152    let mut body = Map::new();
153    body.insert("query".to_string(), Value::from(query));
154    body.insert("cursor".to_string(), Value::from(options.cursor));
155    body.insert("max".to_string(), Value::from(options.max));
156    if let Some(start) = options.start {
157        body.insert(
158            "start".to_string(),
159            Value::from(start.to_rfc3339_opts(SecondsFormat::Millis, true)),
160        );
161    }
162    if let Some(end) = options.end {
163        body.insert(
164            "end".to_string(),
165            Value::from(end.to_rfc3339_opts(SecondsFormat::Millis, true)),
166        );
167    }
168    let response = client()
169        .post(format!("{}/media/query", super::get_url()))
170        .header(
171            "Authorization",
172            match authorization {
173                CredentialsOrApiKey::Credentials(credentials) => {
174                    format!("Token {}", credentials.token)
175                }
176                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
177            },
178        )
179        .json(&body)
180        .send()
181        .await?;
182    Ok(response.json().await?)
183}
184
185/// The `options` argument of `pull`.
186#[derive(Debug, Clone, Default, Serialize)]
187pub struct PullOptions {
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub modals: Option<Vec<String>>,
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub segment: Option<[f64; 2]>,
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub split: Option<f64>,
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub proxy: Option<ProxyMode>,
196}
197
198/// Fetches `url` through Marmot. `request` is the fetch options (method, headers,
199/// body) as JSON.
200pub async fn pull(
201    authorization: &CredentialsOrApiKey,
202    url: &str,
203    request: Option<&Value>,
204    options: PullOptions,
205) -> Result<Option<PullResponse>> {
206    let effective_options = PullOptions {
207        proxy: Some(options.proxy.unwrap_or(ProxyMode::Datacenter)),
208        ..options
209    };
210    let mut builder = client()
211        .post(format!("{}/media/pull", super::get_url()))
212        .header("Content-Type", "application/json")
213        .header(
214            "Authorization",
215            match authorization {
216                CredentialsOrApiKey::Credentials(credentials) => {
217                    format!("Token {}", credentials.token)
218                }
219                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
220            },
221        )
222        .header("Url", url);
223    if let Some(request) = request {
224        builder = builder.header("Request", request.to_string());
225    }
226    let response = builder
227        .header("Options", serde_json::to_string(&effective_options)?)
228        .send()
229        .await?;
230
231    if !response.status().is_success() {
232        return Err(Error::Message(format!("Failed to fetch website at {url}.")));
233    }
234
235    let content_type = response
236        .headers()
237        .get("Content-Type")
238        .and_then(|value| value.to_str().ok())
239        .filter(|value| !value.is_empty())
240        .unwrap_or("application/octet-stream")
241        .to_string();
242
243    let buffer = parse_stream(response, None::<fn(u64)>).await?;
244
245    Ok(Some(PullResponse {
246        content_type,
247        data: BytesOrBytesList::Bytes(buffer.into_iter().next().unwrap_or_default()),
248    }))
249}
250
251/// A kind of file a text model reads itself.
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
253#[serde(rename_all = "lowercase")]
254pub enum Input {
255    Image,
256    Video,
257    Audio,
258}
259
260impl Input {
261    fn as_str(self) -> &'static str {
262        match self {
263            Input::Image => "image",
264            Input::Video => "video",
265            Input::Audio => "audio",
266        }
267    }
268}
269
270fn chat_parts(authorization: &CredentialsOrApiKey, raw: &[Value]) -> Vec<Part> {
271    raw.iter()
272        .map(|part| {
273            if part["type"] == "FILE" {
274                let text = |key: &str, fallback: &str| match &part[key] {
275                    Value::Null => fallback.to_string(),
276                    Value::String(value) => value.clone(),
277                    value => value.to_string(),
278                };
279                Part::File(File {
280                    file: from_bytes(
281                        authorization.clone(),
282                        &text("name", "file"),
283                        &text("contentType", "application/octet-stream"),
284                        STANDARD
285                            .decode(part["data"].as_str().unwrap_or_default())
286                            .unwrap_or_default(),
287                        FileDates::default(),
288                    ),
289                })
290            } else {
291                Part::Text(TextPart {
292                    text: match &part["text"] {
293                        Value::Null => String::new(),
294                        Value::String(text) => text.clone(),
295                        text => text.to_string(),
296                    },
297                })
298            }
299        })
300        .collect()
301}
302
303/// `Part[] | Part[][]` in the TypeScript SDK: one list, or one per segment.
304#[derive(Debug, Clone)]
305pub enum PartsOrPartsList {
306    Parts(Vec<Part>),
307    PartsList(Vec<Vec<Part>>),
308}
309
310/// The `options` argument of `chat`.
311#[derive(Debug, Clone, Default)]
312pub struct ChatOptions {
313    pub name: Option<String>,
314    pub takes: Option<Vec<Input>>,
315    pub segment: Option<[f64; 2]>,
316    pub split: Option<f64>,
317}
318
319/// A media file as message parts for a model that takes `takes` natively (images only
320/// by default). What it takes passes through; the rest becomes what it can take: a
321/// video becomes a line, its frames and its sound (audio, or a description of it),
322/// audio becomes a description, and documents become their text. With `split`, one
323/// list of parts per segment of that many milliseconds. None when it can't be read.
324pub async fn chat(
325    authorization: &CredentialsOrApiKey,
326    content_type: &str,
327    data: &[u8],
328    options: ChatOptions,
329) -> Result<Option<PartsOrPartsList>> {
330    let takes = options
331        .takes
332        .unwrap_or_else(|| vec![Input::Image])
333        .iter()
334        .map(|input| input.as_str())
335        .collect::<Vec<_>>()
336        .join(",");
337    let mut request = client()
338        .post(format!("{}/media/chat", super::get_url()))
339        .header("Content-Type", content_type)
340        .header(
341            "Authorization",
342            match authorization {
343                CredentialsOrApiKey::Credentials(credentials) => {
344                    format!("Token {}", credentials.token)
345                }
346                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
347            },
348        )
349        .header("Takes", takes);
350    if let Some(name) = options.name.as_deref().filter(|name| !name.is_empty()) {
351        request = request.header("Name", encode(name));
352    }
353    if let Some([start, end]) = options.segment {
354        request = request.header("Segment", format!("{start},{end}"));
355    }
356    if let Some(split) = options.split.filter(|split| *split != 0.0) {
357        request = request.header("Split", split.to_string());
358    }
359    let response = request.body(data.to_vec()).send().await?;
360
361    if !response.status().is_success() {
362        return Ok(None);
363    }
364
365    let json: Value = response.json().await?;
366    let Some(rows) = json.as_array() else {
367        return Ok(None);
368    };
369    if options.split.is_some_and(|split| split != 0.0) {
370        return Ok(Some(PartsOrPartsList::PartsList(
371            rows.iter()
372                .map(|segment| {
373                    chat_parts(authorization, segment.as_array().map_or(&[], Vec::as_slice))
374                })
375                .collect(),
376        )));
377    }
378    Ok(Some(PartsOrPartsList::Parts(chat_parts(
379        authorization,
380        rows,
381    ))))
382}
383
384pub async fn parse(
385    authorization: &CredentialsOrApiKey,
386    content_type: &str,
387    data: &[u8],
388    on_progress: Option<Progress>,
389) -> Result<String> {
390    let response = client()
391        .post(format!("{}/media/parse", super::get_url()))
392        .header(
393            "Authorization",
394            match authorization {
395                CredentialsOrApiKey::Credentials(credentials) => {
396                    format!("Token {}", credentials.token)
397                }
398                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
399            },
400        )
401        .header(
402            "Content-Type",
403            if content_type.is_empty() {
404                "application/octet-stream"
405            } else {
406                content_type
407            },
408        )
409        .header("Content-Length", data.len())
410        .body(progress_body(data.to_vec(), on_progress))
411        .send()
412        .await
413        .map_err(|_| Error::Message("Failed to parse media.".to_string()))?;
414    if !response.status().is_success() {
415        return Err(Error::Message(format!(
416            "Failed to parse media: {}",
417            response.status().as_u16()
418        )));
419    }
420    Ok(response.text().await?)
421}
422
423/// The `options` argument of `slice`.
424#[derive(Debug, Clone, Default)]
425pub struct SliceOptions {
426    pub segment: Option<[f64; 2]>,
427    pub split: Option<f64>,
428}
429
430pub async fn slice(
431    authorization: &CredentialsOrApiKey,
432    content_type: &str,
433    data: &[u8],
434    options: SliceOptions,
435) -> Result<Option<BytesOrBytesList>> {
436    let mut request = client()
437        .post(format!("{}/media/slice", super::get_url()))
438        .header(
439            "Content-Type",
440            if content_type.is_empty() {
441                "application/octet-stream"
442            } else {
443                content_type
444            },
445        )
446        .header(
447            "Authorization",
448            match authorization {
449                CredentialsOrApiKey::Credentials(credentials) => {
450                    format!("Token {}", credentials.token)
451                }
452                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
453            },
454        );
455    if let Some([start, end]) = options.segment {
456        request = request.header("Segment", format!("{start},{end}"));
457    }
458    if let Some(split) = options.split.filter(|split| *split != 0.0) {
459        request = request.header("Split", split.to_string());
460    }
461    let response = request.body(data.to_vec()).send().await?;
462
463    if !response.status().is_success() {
464        return Ok(None);
465    }
466
467    let multipart = response
468        .headers()
469        .get("Encoding-Size")
470        .and_then(|value| value.to_str().ok())
471        .and_then(|value| value.trim().parse::<i64>().ok())
472        .is_some_and(|size| size > 1);
473    let mut parts = parse_stream(response, None::<fn(u64)>).await?;
474    Ok(Some(if multipart {
475        BytesOrBytesList::BytesList(parts)
476    } else {
477        BytesOrBytesList::Bytes(parts.pop().unwrap_or_default())
478    }))
479}
480
481pub async fn duration(
482    authorization: &CredentialsOrApiKey,
483    content_type: &str,
484    data: &[u8],
485    on_progress: Option<Progress>,
486) -> Result<f64> {
487    let response = client()
488        .post(format!("{}/media/duration", super::get_url()))
489        .header(
490            "Authorization",
491            match authorization {
492                CredentialsOrApiKey::Credentials(credentials) => {
493                    format!("Token {}", credentials.token)
494                }
495                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
496            },
497        )
498        .header(
499            "Content-Type",
500            if content_type.is_empty() {
501                "application/octet-stream"
502            } else {
503                content_type
504            },
505        )
506        .header("Content-Length", data.len())
507        .body(progress_body(data.to_vec(), on_progress))
508        .send()
509        .await
510        .map_err(|_| Error::Message("Failed to duration media.".to_string()))?;
511    if !response.status().is_success() {
512        return Err(Error::Message(format!(
513            "Failed to duration media: {}",
514            response.status().as_u16()
515        )));
516    }
517    let text = response.text().await?;
518    Ok(text.trim().parse::<f64>().unwrap_or(f64::NAN))
519}
520
521/// Marmot's prices as callers are charged: `search` (web searches), `tweet` and `user` (official
522/// X reads), and `datacenter` and `residential` (pages pulled through each proxy).
523#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
524pub struct Pricing {
525    pub rates: Vec<Rate>,
526}
527
528/// Marmot's current prices. Anyone can read them, signed in or not.
529pub async fn pricing() -> Result<Pricing> {
530    let response = client()
531        .get(format!("{}/marmot/pricing", super::get_url()))
532        .send()
533        .await?;
534    Ok(ok(response).await?.json().await?)
535}