From 6aa5e3ae58f467d16286cde63992d2d7ec0f5d8a Mon Sep 17 00:00:00 2001
From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com>
Date: Thu, 3 Dec 2026 17:54:48 +0100
Subject: [PATCH 1/2] Videos with sound start from a picture and can end on a
second one
draw-api h3video_generate takes image_b64 and last_image_b64 (aifarm-draw #53). Both video tools take
file_ids; without them the pictures of the current message and its quote are used. One picture is the
first frame, two are the first and the last. Only a video with sound keeps them: FastFrames renders
from text alone.
The video worker downloads each picture at up to 1280 px and describes it with the vision model. The
MiniMax-H3 optimizer gets the descriptions as "Picture 1, the first frame: ..." lines and writes the
I2VA or FL2VA body that starts from (draw-api adds the alignment line). A picture sets the
frame unless the user asked for one. A picture that cannot be loaded or described leaves a video from
text instead of a failure.
---
crates/openplotva-app/src/dialog_tools.rs | 159 +++++++++-
crates/openplotva-app/src/help.rs | 2 +
crates/openplotva-app/src/image_jobs.rs | 39 ++-
crates/openplotva-app/src/lib.rs | 8 +-
crates/openplotva-app/src/media.rs | 1 +
crates/openplotva-app/src/video_jobs.rs | 348 ++++++++++++++++++++--
crates/openplotva-dialog/src/dispatch.rs | 1 +
crates/openplotva-dialog/src/lib.rs | 21 +-
crates/openplotva-llm/src/aifarm.rs | 4 +-
crates/openplotva-media/src/video.rs | 87 +++++-
crates/openplotva-taskman/src/lib.rs | 37 ++-
prompts/aifarm/system.prompt | 2 +-
prompts/video/movie_optimizer.prompt | 17 ++
13 files changed, 649 insertions(+), 77 deletions(-)
diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs
index df0bde7..7f3ad6e 100644
--- a/crates/openplotva-app/src/dialog_tools.rs
+++ b/crates/openplotva-app/src/dialog_tools.rs
@@ -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,
};
@@ -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,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
@@ -1732,6 +1734,7 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
} else {
String::new()
},
+ frames: if sound { request.frames } else { Vec::new() },
},
OffsetDateTime::now_utc(),
)
@@ -2636,6 +2639,10 @@ impl
"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,
@@ -2652,6 +2659,13 @@ impl
.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)),
@@ -3124,18 +3138,43 @@ where
}
fn draw_image_attachments(req: &DrawRequest) -> Result, 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 from the
+/// current message and its quote.
+fn video_frame_attachments(req: &VideoRequest) -> Result, String> {
+ let frames: Vec = selected_image_attachments(&req.context, &req.file_ids)?
+ .into_iter()
+ .filter(|image| image.kind.trim() == "image")
+ .collect();
+ if frames.len() > MAX_VIDEO_FRAMES {
+ return Err(format!(
+ "a video starts from one picture or runs from a first to a last picture; {} were given",
+ frames.len()
+ ));
+ }
+ 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, String> {
+ let available = &context.image_attachments;
+ if !file_ids.is_empty() {
let mut selected = Vec::::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()
@@ -3155,10 +3194,10 @@ fn draw_image_attachments(req: &DrawRequest) -> Result, 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::::new();
for image in current {
if image.kind.trim() == "image" && !image.media_group_id.trim().is_empty() {
@@ -3180,7 +3219,7 @@ fn draw_image_attachments(req: &DrawRequest) -> Result, Stri
selected.push(image.clone());
}
}
- validate_image_edit_sources(selected)
+ Ok(selected)
}
fn validate_image_edit_sources(images: Vec) -> Result, String> {
@@ -5474,6 +5513,7 @@ mod tests {
steps: 0,
orientation: String::new(),
admin_command: false,
+ frames: Vec::new(),
}
}
@@ -5533,6 +5573,7 @@ mod tests {
sound: false,
steps: 0,
orientation: String::new(),
+ frames: Vec::new(),
})
);
assert_eq!(
@@ -5809,6 +5850,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?;
@@ -5827,6 +5869,101 @@ 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, 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?;
+ let refused = toolbox
+ .make_movie(request(
+ vec![
+ picture("a", "message"),
+ picture("b", "message"),
+ picture("c", "quoted"),
+ ],
+ &[],
+ ))
+ .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::>()
+ };
+ 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!(recorded.len(), 2, "three pictures are not scheduled");
+ 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 [
diff --git a/crates/openplotva-app/src/help.rs b/crates/openplotva-app/src/help.rs
index 2a4a847..5b6d891 100644
--- a/crates/openplotva-app/src/help.rs
+++ b/crates/openplotva-app/src/help.rs
@@ -65,6 +65,8 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"
Привет! Я {{.BotName}}
Видео:/video бабушка достаёт пирожки из печки или «{{.BotName}}, сгенерируй видео…». С VIP видео идёт со звуком: речь, шумы и музыка, а реплики в кавычках звучат дословно. Можно попросить вертикальное видео (для сторис, Reels, TikTok) и высокое качество — это дольше. Без VIP вместо видео будет гифка.
+
Оживить картинку (VIP): пришли картинку с подписью /video что должно произойти или ответь этой командой на картинку. Две картинки станут первым и последним кадром.
+
Полезности
Ищу в интернете, читаю ссылки, кратко пересказываю YouTube, перевожу тексты и показываю курсы валют.
diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs
index 60cdb33..0cc4885 100644
--- a/crates/openplotva-app/src/image_jobs.rs
+++ b/crates/openplotva-app/src/image_jobs.rs
@@ -778,15 +778,22 @@ 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,
- /// "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)]
@@ -794,7 +801,7 @@ struct DrawApiVideoRequest<'a> {
prompt: &'a str,
format: &'a str,
#[serde(flatten)]
- options: DrawApiVideoOptions,
+ options: DrawApiVideoOptions<'a>,
}
/// AIFarm draw-api image generator.
@@ -956,7 +963,7 @@ where
&self,
endpoint: &str,
prompt: &str,
- options: DrawApiVideoOptions,
+ options: DrawApiVideoOptions<'_>,
job_id: &str,
) -> Result {
let prompt = prompt.trim();
@@ -8916,7 +8923,7 @@ mod tests {
"rain",
DrawApiVideoOptions {
steps: Some(4),
- orientation: None,
+ ..DrawApiVideoOptions::default()
},
"video-78"
)
@@ -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");
@@ -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
@@ -9055,7 +9064,13 @@ mod tests {
let body = decode_discovery_body(&job.invocation.body).expect("video body");
assert_eq!(
serde_json::from_slice::(&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="
+ })
);
}
@@ -9094,7 +9109,7 @@ mod tests {
&generator,
"rain",
79,
- crate::video_jobs::VideoRender {
+ &crate::video_jobs::VideoRender {
sound: true,
..crate::video_jobs::VideoRender::default()
},
@@ -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");
diff --git a/crates/openplotva-app/src/lib.rs b/crates/openplotva-app/src/lib.rs
index f0e8405..9221f92 100644
--- a/crates/openplotva-app/src/lib.rs
+++ b/crates/openplotva-app/src/lib.rs
@@ -3903,7 +3903,7 @@ async fn start_runtime_workers(
.with_image_fallback_notice_sender(Arc::new(
dialog_messages::DrawQueueNoticeDispatcherSender::new(Arc::clone(&dispatcher_queue)),
))
- .with_vision_describer(dialog_tool_media);
+ .with_vision_describer(Arc::clone(&dialog_tool_media));
if config.video.enabled {
app_dialog_toolbox = app_dialog_toolbox.with_video_scheduler(dialog_tool_adapter.clone());
}
@@ -4445,7 +4445,11 @@ async fn start_runtime_workers(
Arc::clone(&permission_policy),
telegram.clone(),
)
- .with_reaction_ux(Arc::clone(&generation_reactions)),
+ .with_reaction_ux(Arc::clone(&generation_reactions))
+ .with_frames(video_jobs::TelegramVideoFrames::new(
+ telegram.clone(),
+ Arc::clone(&dialog_tool_media),
+ )),
}) as Arc
});
let vip_image_queue = Arc::clone(&task_queue_for_updates);
diff --git a/crates/openplotva-app/src/media.rs b/crates/openplotva-app/src/media.rs
index d88a035..62d0c0f 100644
--- a/crates/openplotva-app/src/media.rs
+++ b/crates/openplotva-app/src/media.rs
@@ -202,6 +202,7 @@ impl RoutedMediaPromptOptimizer {
let prompt_store = Arc::clone(&self.prompt_store);
let request = request.clone();
let brief = brief.clone();
+ let target = target.clone();
async move {
if attempt.protocol
== Some(openplotva_llm::provider_schema::Protocol::Genkit)
diff --git a/crates/openplotva-app/src/video_jobs.rs b/crates/openplotva-app/src/video_jobs.rs
index 9a708da..9cf0bd8 100644
--- a/crates/openplotva-app/src/video_jobs.rs
+++ b/crates/openplotva-app/src/video_jobs.rs
@@ -15,7 +15,8 @@ use openplotva_media::{
};
use openplotva_server::ACTION_SEND_VIDEO;
use openplotva_taskman::{
- InMemoryTaskQueue, TaskQueueWorkItem, VideoGenJobParams, video_gen_job_params_from_payload,
+ InMemoryTaskQueue, TaskQueueWorkItem, VideoFrameRef, VideoGenJobParams,
+ video_gen_job_params_from_payload,
};
use openplotva_telegram::{
ChatRef, ReplyParametersPlan, TELEGRAM_PARSE_MODE_HTML, TelegramClient, TelegramOutboundMethod,
@@ -64,12 +65,17 @@ impl VideoPromptOptimizer for crate::media::RoutedMediaPromptOptimizer {
}
/// What the farm renders: a silent FastFrames clip, or a MiniMax-H3 video with sound and its
-/// options, where zero steps and landscape keep the farm's defaults.
-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+/// options, where zero steps and no frame keep the farm's defaults.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct VideoRender {
pub sound: bool,
pub steps: u8,
- pub orientation: VideoOrientation,
+ /// `None` leaves the frame to the farm: landscape, or the first picture's shape.
+ pub orientation: Option,
+ /// Data URL of the picture the video starts from.
+ pub first_frame: Option,
+ /// Data URL of the picture the video ends on.
+ pub last_frame: Option,
}
impl VideoRender {
@@ -81,14 +87,15 @@ impl VideoRender {
}
}
- fn options(&self) -> DrawApiVideoOptions {
+ fn options(&self) -> DrawApiVideoOptions<'_> {
if !self.sound {
return DrawApiVideoOptions::default();
}
DrawApiVideoOptions {
steps: (self.steps > 0).then_some(self.steps),
- orientation: (self.orientation == VideoOrientation::Portrait)
- .then_some(VideoOrientation::Portrait.as_str()),
+ orientation: self.orientation.map(VideoOrientation::as_str),
+ image_b64: self.first_frame.as_deref(),
+ last_image_b64: self.last_frame.as_deref(),
}
}
}
@@ -99,7 +106,7 @@ pub trait VideoGenerator: Send + Sync {
&'a self,
prompt: &'a str,
job_id: i64,
- render: VideoRender,
+ render: &'a VideoRender,
) -> VideoJobFuture<'a, Result>;
}
@@ -111,7 +118,7 @@ where
&'a self,
prompt: &'a str,
job_id: i64,
- render: VideoRender,
+ render: &'a VideoRender,
) -> VideoJobFuture<'a, Result> {
Box::pin(async move {
let (endpoint, options) = (render.endpoint(), render.options());
@@ -170,7 +177,25 @@ pub struct VideoDelivery {
pub sound: bool,
}
+/// A picture a video starts from or ends on, ready for draw-api and the prompt writer.
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct LoadedVideoFrame {
+ /// `data:image/...;base64,...`.
+ pub data_url: String,
+ /// What the picture shows.
+ pub description: String,
+}
+
pub trait VideoJobEffects: Send + Sync {
+ /// Download and describe one picture of a video with sound.
+ fn load_frame<'a>(
+ &'a self,
+ _params: &'a VideoGenJobParams,
+ _frame: &'a VideoFrameRef,
+ ) -> VideoJobFuture<'a, Result> {
+ Box::pin(async { Err("video frames are not supported here".to_owned()) })
+ }
+
fn can_send_video<'a>(&'a self, chat_id: i64) -> VideoJobFuture<'a, bool>;
/// Best-effort: mark the trigger message with the "generating" reaction.
@@ -195,11 +220,83 @@ pub trait VideoJobEffects: Send + Sync {
) -> VideoJobFuture<'a, Result