Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 159 additions & 11 deletions crates/openplotva-app/src/dialog_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use openplotva_media::video::VideoOrientation;
use openplotva_taskman::{
ADMIN_COMMAND_PRIORITY, DEFAULT_PRIORITY, HIGHEST_PRIORITY, IMAGE_REGULAR_QUEUE_NAME,
IMAGE_VIP_PRIORITY, IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageGenJobParams,
InMemoryTaskQueue, MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, VideoGenJobParams,
InMemoryTaskQueue, MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, VideoFrameRef, VideoGenJobParams,
fallback_queue_time_estimate, format_duration_ru, format_go_duration, new_image_edit_job_at,
new_image_gen_job_at, new_music_gen_job_at, new_video_gen_job_at,
};
Expand Down Expand Up @@ -939,6 +939,8 @@ pub struct VideoScheduleRequest {
pub orientation: String,
/// Asked with an admin shortcut: the job jumps every queue.
pub admin_command: bool,
/// Pictures a video with sound starts from and, with two, ends on.
pub frames: Vec<VideoFrameRef>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
Expand Down Expand Up @@ -1732,6 +1734,7 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
} else {
String::new()
},
frames: if sound { request.frames } else { Vec::new() },
},
OffsetDateTime::now_utc(),
)
Expand Down Expand Up @@ -2636,6 +2639,10 @@ impl<RatesFetcherT, RatesDispatcherT, TranslatorT>
"video service unavailable",
));
};
let frames = match video_frame_attachments(&req) {
Ok(frames) => frames,
Err(reason) => return Ok(ToolResult::failed(format!("{tool}_frames_invalid"), reason)),
};
let request = VideoScheduleRequest {
chat_id: req.context.chat_id,
thread_id: req.context.thread_id,
Expand All @@ -2652,6 +2659,13 @@ impl<RatesFetcherT, RatesDispatcherT, TranslatorT>
.unwrap_or_default()
.to_owned(),
admin_command: req.context.message_meta.admin_command,
frames: frames
.into_iter()
.map(|frame| VideoFrameRef {
file_id: frame.file_id,
file_unique_id: frame.file_unique_id,
})
.collect(),
};
match scheduler.schedule_video(request).await {
Ok(result) => Ok(dialog_make_video_tool_result(&result, tool)),
Expand Down Expand Up @@ -3124,18 +3138,44 @@ where
}

fn draw_image_attachments(req: &DrawRequest) -> Result<Vec<ChatAttachment>, String> {
let available = &req.context.image_attachments;
if !req.file_ids.is_empty() {
validate_image_edit_sources(selected_image_attachments(&req.context, &req.file_ids)?)
}

/// Pictures a video starts from and ends on: at most two, from `file_ids` or else the first two
/// of the current message and its quote.
fn video_frame_attachments(req: &VideoRequest) -> Result<Vec<ChatAttachment>, String> {
let mut frames: Vec<ChatAttachment> = selected_image_attachments(&req.context, &req.file_ids)?
.into_iter()
.filter(|image| image.kind.trim() == "image")
.collect();
if frames.len() > MAX_VIDEO_FRAMES && !req.file_ids.is_empty() {
return Err(format!(
"a video starts from one picture or runs from a first to a last picture; {} were given",
frames.len()
));
}
frames.truncate(MAX_VIDEO_FRAMES);
Ok(frames)
}

/// The first and the last frame of a video.
const MAX_VIDEO_FRAMES: usize = 2;

/// Pictures named by `file_ids`, or else the current message's pictures with their media group.
fn selected_image_attachments(
context: &openplotva_dialog::ToolContext,
file_ids: &[String],
) -> Result<Vec<ChatAttachment>, String> {
let available = &context.image_attachments;
if !file_ids.is_empty() {
let mut selected = Vec::<ChatAttachment>::new();
for id in &req.file_ids {
for id in file_ids {
let id = id.trim();
let id = req
.context
let id = context
.image_reference_ids
.get(id)
.map_or(id, |value| value.trim());
let Some(image) = req
.context
let Some(image) = context
.message_meta
.attachments
.iter()
Expand All @@ -3155,10 +3195,10 @@ fn draw_image_attachments(req: &DrawRequest) -> Result<Vec<ChatAttachment>, Stri
selected.push(image.clone());
}
}
return validate_image_edit_sources(selected);
return Ok(selected);
}

let current = &req.context.message_meta.attachments;
let current = &context.message_meta.attachments;
let mut selected = Vec::<ChatAttachment>::new();
for image in current {
if image.kind.trim() == "image" && !image.media_group_id.trim().is_empty() {
Expand All @@ -3180,7 +3220,7 @@ fn draw_image_attachments(req: &DrawRequest) -> Result<Vec<ChatAttachment>, Stri
selected.push(image.clone());
}
}
validate_image_edit_sources(selected)
Ok(selected)
}

fn validate_image_edit_sources(images: Vec<ChatAttachment>) -> Result<Vec<ChatAttachment>, String> {
Expand Down Expand Up @@ -5474,6 +5514,7 @@ mod tests {
steps: 0,
orientation: String::new(),
admin_command: false,
frames: Vec::new(),
}
}

Expand Down Expand Up @@ -5533,6 +5574,7 @@ mod tests {
sound: false,
steps: 0,
orientation: String::new(),
frames: Vec::new(),
})
);
assert_eq!(
Expand Down Expand Up @@ -5809,6 +5851,7 @@ mod tests {
caption: "Кот танцует".to_owned(),
quality: quality.to_owned(),
orientation: orientation.to_owned(),
file_ids: Vec::new(),
};
toolbox.make_video(request("high", "portrait")).await?;
toolbox.make_movie(request("", "square")).await?;
Expand All @@ -5827,6 +5870,111 @@ mod tests {
Ok(())
}

fn picture(id: &str, source: &str) -> ChatAttachment {
ChatAttachment {
kind: "image".to_owned(),
source: source.to_owned(),
file_id: format!("{id}-file"),
file_unique_id: id.to_owned(),
..ChatAttachment::default()
}
}

#[tokio::test]
async fn video_tools_take_up_to_two_pictures_as_first_and_last_frame()
-> Result<(), ToolboxError> {
let scheduler = Arc::new(VideoSchedulerRecorder::default());
let toolbox = toolbox(None).with_video_scheduler(scheduler.clone());
let request = |attached: Vec<ChatAttachment>, file_ids: &[&str]| VideoRequest {
context: ToolContext {
message_meta: ChatMessageMeta {
attachments: attached,
..ChatMessageMeta::default()
},
image_attachments: vec![picture("old-a", "history"), picture("old-b", "history")],
..context()
},
prompt: "The cat jumps".to_owned(),
caption: "Кот прыгает".to_owned(),
file_ids: file_ids.iter().map(|id| (*id).to_owned()).collect(),
..VideoRequest::default()
};

toolbox
.make_movie(request(vec![picture("attached", "message")], &[]))
.await?;
toolbox
.make_movie(request(Vec::new(), &["old-b", "old-a"]))
.await?;
toolbox
.make_movie(request(
vec![
picture("a", "message"),
picture("b", "message"),
picture("c", "quoted"),
],
&[],
))
.await?;
let refused = toolbox
.make_movie(request(Vec::new(), &["old-a", "old-b", "attached"]))
.await;

let recorded = scheduler.0.lock().expect("videos");
let ids = |index: usize| {
recorded[index]
.frames
.iter()
.map(|frame| (frame.file_unique_id.as_str(), frame.file_id.as_str()))
.collect::<Vec<_>>()
};
assert_eq!(ids(0), [("attached", "attached-file")]);
assert_eq!(
ids(1),
[("old-b", "old-b-file"), ("old-a", "old-a-file")],
"file_ids keep their order: first frame, then last"
);
assert_eq!(
ids(2),
[("a", "a-file"), ("b", "b-file")],
"the first two attached pictures"
);
assert_eq!(recorded.len(), 3, "three named pictures are not scheduled");
drop(recorded);
let refused = refused?;
assert_eq!(
refused.error.as_ref().map(|error| error.code.as_str()),
Some("make_movie_frames_invalid")
);
Ok(())
}

#[tokio::test]
async fn only_a_video_with_sound_keeps_its_pictures() -> Result<(), ToolboxError> {
let frames = vec![VideoFrameRef {
file_id: "first-file".to_owned(),
file_unique_id: "first".to_owned(),
}];
for (vip, text, kept) in [
(true, "оживи картинку", true),
(true, "сделай гифку из картинки", false),
(false, "оживи картинку", false),
] {
let (queue, _) = schedule_video_as(
vip,
VideoScheduleRequest {
message_text: text.to_owned(),
frames: frames.clone(),
..video_request(11)
},
)
.await?;
let params = scheduled_video_params(&queue);
assert_eq!(params.frames.is_empty(), !kept, "{text}, vip {vip}");
}
Ok(())
}

#[test]
fn silent_clip_wording_is_recognized_in_any_case_and_language() {
for text in [
Expand Down
2 changes: 2 additions & 0 deletions crates/openplotva-app/src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"<h3>Привет! Я {{.BotName}}</h3

<p><b>Видео:</b> <code>/video бабушка достаёт пирожки из печки</code> или «{{.BotName}}, сгенерируй видео…». С VIP видео идёт со звуком: речь, шумы и музыка, а реплики в кавычках звучат дословно. Можно попросить вертикальное видео (для сторис, Reels, TikTok) и высокое качество — это дольше. Без VIP вместо видео будет гифка.</p>

<p><b>Оживить картинку (VIP):</b> пришли картинку с подписью <code>/video что должно произойти</code> или ответь этой командой на картинку. Две картинки станут первым и последним кадром.</p>

<h3>Полезности</h3>

<p>Ищу в интернете, читаю ссылки, кратко пересказываю YouTube, перевожу тексты и показываю курсы валют.</p>
Expand Down
39 changes: 27 additions & 12 deletions crates/openplotva-app/src/image_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -778,23 +778,30 @@ pub struct DrawApiVideo {
pub fps: i64,
}

/// Options of a MiniMax-H3 render; `None` keeps the farm's default (2 steps, 480p landscape).
/// Options of a MiniMax-H3 render; `None` keeps the farm's default (2 steps, 480p landscape,
/// text only).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
pub struct DrawApiVideoOptions {
pub struct DrawApiVideoOptions<'a> {
/// Sampling steps: 2 or 4.
#[serde(skip_serializing_if = "Option::is_none")]
pub steps: Option<u8>,
/// "landscape" or "portrait".
/// "landscape" or "portrait"; without it a first picture sets the frame.
#[serde(skip_serializing_if = "Option::is_none")]
pub orientation: Option<&'static str>,
/// Data URL of the picture the video starts from.
#[serde(skip_serializing_if = "Option::is_none")]
pub image_b64: Option<&'a str>,
/// Data URL of the picture the video ends on.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_image_b64: Option<&'a str>,
}

#[derive(Serialize)]
struct DrawApiVideoRequest<'a> {
prompt: &'a str,
format: &'a str,
#[serde(flatten)]
options: DrawApiVideoOptions,
options: DrawApiVideoOptions<'a>,
}

/// AIFarm draw-api image generator.
Expand Down Expand Up @@ -956,7 +963,7 @@ where
&self,
endpoint: &str,
prompt: &str,
options: DrawApiVideoOptions,
options: DrawApiVideoOptions<'_>,
job_id: &str,
) -> Result<DrawApiVideo, ImageGenerationError> {
let prompt = prompt.trim();
Expand Down Expand Up @@ -8916,7 +8923,7 @@ mod tests {
"rain",
DrawApiVideoOptions {
steps: Some(4),
orientation: None,
..DrawApiVideoOptions::default()
},
"video-78"
)
Expand Down Expand Up @@ -9004,7 +9011,7 @@ mod tests {
&generator,
"rain",
77,
crate::video_jobs::VideoRender::default(),
&crate::video_jobs::VideoRender::default(),
)
.await
.expect("the second submission renders the clip");
Expand Down Expand Up @@ -9035,10 +9042,12 @@ mod tests {
&generator,
"rain",
78,
crate::video_jobs::VideoRender {
&crate::video_jobs::VideoRender {
sound: true,
steps: 4,
orientation: openplotva_media::video::VideoOrientation::Portrait,
orientation: Some(openplotva_media::video::VideoOrientation::Portrait),
first_frame: Some("data:image/jpeg;base64,Zmlyc3Q=".to_owned()),
last_frame: None,
},
)
.await
Expand All @@ -9055,7 +9064,13 @@ mod tests {
let body = decode_discovery_body(&job.invocation.body).expect("video body");
assert_eq!(
serde_json::from_slice::<Value>(&body).expect("video request"),
json!({"prompt": "rain", "format": "mp4", "steps": 4, "orientation": "portrait"})
json!({
"prompt": "rain",
"format": "mp4",
"steps": 4,
"orientation": "portrait",
"image_b64": "data:image/jpeg;base64,Zmlyc3Q="
})
);
}

Expand Down Expand Up @@ -9094,7 +9109,7 @@ mod tests {
&generator,
"rain",
79,
crate::video_jobs::VideoRender {
&crate::video_jobs::VideoRender {
sound: true,
..crate::video_jobs::VideoRender::default()
},
Expand Down Expand Up @@ -9128,7 +9143,7 @@ mod tests {
&generator,
"rain",
80,
crate::video_jobs::VideoRender::default(),
&crate::video_jobs::VideoRender::default(),
)
.await
.expect_err("an unknown job fails the clip");
Expand Down
Loading
Loading