use base64::{engine::general_purpose::STANDARD, Engine};
use super::types::{DocumentSource, ImageSource};
pub fn encode_image_base64(bytes: &[u8]) -> String {
STANDARD.encode(bytes)
}
pub fn image_source_base64(media_type: impl Into<String>, data: impl Into<String>) -> ImageSource {
ImageSource::Base64 {
media_type: media_type.into(),
data: data.into(),
}
}
pub fn image_source_url(url: impl Into<String>) -> ImageSource {
ImageSource::Url { url: url.into() }
}
pub fn document_source_pdf_base64(data: impl Into<String>) -> DocumentSource {
DocumentSource::Base64 {
media_type: "application/pdf".to_string(),
data: data.into(),
}
}
pub fn document_source_pdf_url(url: impl Into<String>) -> DocumentSource {
DocumentSource::Url { url: url.into() }
}
pub fn document_source_text(data: impl Into<String>) -> DocumentSource {
DocumentSource::Text {
media_type: "text/plain".to_string(),
data: data.into(),
}
}
pub fn estimate_image_tokens(width: u32, height: u32) -> u32 {
(width * height) / 750
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_source_creation() {
let base64_src = image_source_base64("image/jpeg", "base64data");
match base64_src {
ImageSource::Base64 { media_type, data } => {
assert_eq!(media_type, "image/jpeg");
assert_eq!(data, "base64data");
}
_ => panic!("Expected base64 source"),
}
let url_src = image_source_url("https://example.com/image.jpg");
match url_src {
ImageSource::Url { url } => {
assert_eq!(url, "https://example.com/image.jpg");
}
_ => panic!("Expected URL source"),
}
}
#[test]
fn test_estimate_image_tokens() {
let tokens = estimate_image_tokens(1092, 1092);
assert_eq!(tokens, 1589);
let tokens = estimate_image_tokens(200, 200);
assert_eq!(tokens, 53); }
}