diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs
index 92ddc65..9d6035b 100644
--- a/crates/openplotva-app/src/dialog_tools.rs
+++ b/crates/openplotva-app/src/dialog_tools.rs
@@ -939,8 +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,
+ /// Pictures for a video with sound, at most three, in order.
+ pub pictures: Vec,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
@@ -1001,6 +1001,72 @@ fn video_with_sound(has_vip: bool, message_text: &str) -> bool {
has_vip && !asks_for_silent_clip(message_text)
}
+/// The pictures of a video with sound as its first and last frame when the user asks to animate
+/// or continue a picture, else as references: the subjects they show appear in a new scene.
+fn video_picture_roles(
+ mut pictures: Vec,
+ message_text: &str,
+) -> (Vec, Vec) {
+ if asks_to_animate_picture(message_text) {
+ pictures.truncate(2);
+ (pictures, Vec::new())
+ } else {
+ pictures.truncate(MAX_VIDEO_PICTURES);
+ (Vec::new(), pictures)
+ }
+}
+
+fn asks_to_animate_picture(message_text: &str) -> bool {
+ let text = message_text.to_lowercase();
+ let animate_word = text.split(|c: char| !c.is_alphanumeric()).any(|word| {
+ word.starts_with("оживи")
+ || word.starts_with("оживля")
+ || word.starts_with("превра")
+ || word.starts_with("аніму")
+ || word.starts_with("продовжи")
+ || word.starts_with("продовжен")
+ || matches!(
+ word,
+ "анимируй"
+ | "анимируйте"
+ | "анимировать"
+ | "заанимируй"
+ | "продолжи"
+ | "продолжите"
+ | "продолжить"
+ | "продолжение"
+ | "animate"
+ | "continue"
+ | "morph"
+ )
+ });
+ animate_word
+ || [
+ "первый кадр",
+ "первым кадром",
+ "последний кадр",
+ "последним кадром",
+ "стартовый кадр",
+ "начальный кадр",
+ "конечный кадр",
+ "этот кадр",
+ "этого кадра",
+ "перший кадр",
+ "останній кадр",
+ "first frame",
+ "last frame",
+ "start frame",
+ "starting frame",
+ "end frame",
+ "final frame",
+ "this frame",
+ "to life",
+ "turns into",
+ ]
+ .iter()
+ .any(|phrase| text.contains(phrase))
+}
+
fn asks_for_silent_clip(message_text: &str) -> bool {
let text = message_text.to_lowercase();
let gif_word = text.split(|c: char| !c.is_alphanumeric()).any(|word| {
@@ -1717,6 +1783,11 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
{
return Ok(not_scheduled_video(VideoScheduleRejection::RateLimited));
}
+ let (frames, references) = if sound {
+ video_picture_roles(request.pictures, &request.message_text)
+ } else {
+ (Vec::new(), Vec::new())
+ };
let job = new_video_gen_job_at(
VideoGenJobParams {
chat_id,
@@ -1734,7 +1805,8 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
} else {
String::new()
},
- frames: if sound { request.frames } else { Vec::new() },
+ frames,
+ references,
},
OffsetDateTime::now_utc(),
)
@@ -2639,8 +2711,8 @@ impl
"video service unavailable",
));
};
- let frames = match video_frame_attachments(&req) {
- Ok(frames) => frames,
+ let pictures = match video_picture_attachments(&req) {
+ Ok(pictures) => pictures,
Err(reason) => return Ok(ToolResult::failed(format!("{tool}_frames_invalid"), reason)),
};
let request = VideoScheduleRequest {
@@ -2659,11 +2731,11 @@ impl
.unwrap_or_default()
.to_owned(),
admin_command: req.context.message_meta.admin_command,
- frames: frames
+ pictures: pictures
.into_iter()
- .map(|frame| VideoFrameRef {
- file_id: frame.file_id,
- file_unique_id: frame.file_unique_id,
+ .map(|picture| VideoFrameRef {
+ file_id: picture.file_id,
+ file_unique_id: picture.file_unique_id,
})
.collect(),
};
@@ -3141,25 +3213,26 @@ fn draw_image_attachments(req: &DrawRequest) -> Result, Stri
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, String> {
- let mut 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 && !req.file_ids.is_empty() {
+/// Pictures for a video: at most three, from `file_ids` or else the first three of the current
+/// message and its quote.
+fn video_picture_attachments(req: &VideoRequest) -> Result, String> {
+ let mut pictures: Vec =
+ selected_image_attachments(&req.context, &req.file_ids)?
+ .into_iter()
+ .filter(|image| image.kind.trim() == "image")
+ .collect();
+ if pictures.len() > MAX_VIDEO_PICTURES && !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()
+ "a video uses at most {MAX_VIDEO_PICTURES} pictures; {} were given",
+ pictures.len()
));
}
- frames.truncate(MAX_VIDEO_FRAMES);
- Ok(frames)
+ pictures.truncate(MAX_VIDEO_PICTURES);
+ Ok(pictures)
}
-/// The first and the last frame of a video.
-const MAX_VIDEO_FRAMES: usize = 2;
+/// draw-api takes up to three references, or a first and a last frame.
+const MAX_VIDEO_PICTURES: usize = 3;
/// Pictures named by `file_ids`, or else the current message's pictures with their media group.
fn selected_image_attachments(
@@ -5514,7 +5587,7 @@ mod tests {
steps: 0,
orientation: String::new(),
admin_command: false,
- frames: Vec::new(),
+ pictures: Vec::new(),
}
}
@@ -5575,6 +5648,7 @@ mod tests {
steps: 0,
orientation: String::new(),
frames: Vec::new(),
+ references: Vec::new(),
})
);
assert_eq!(
@@ -5916,30 +5990,46 @@ mod tests {
&[],
))
.await?;
+ toolbox
+ .make_movie(request(
+ vec![
+ picture("a", "message"),
+ picture("b", "message"),
+ picture("c", "quoted"),
+ picture("d", "quoted"),
+ ],
+ &[],
+ ))
+ .await?;
let refused = toolbox
- .make_movie(request(Vec::new(), &["old-a", "old-b", "attached"]))
+ .make_movie(request(Vec::new(), &["old-a", "old-b", "attached", "a"]))
.await;
let recorded = scheduler.0.lock().expect("videos");
let ids = |index: usize| {
recorded[index]
- .frames
+ .pictures
.iter()
- .map(|frame| (frame.file_unique_id.as_str(), frame.file_id.as_str()))
+ .map(|picture| (picture.file_unique_id.as_str(), picture.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"
+ "file_ids keep their order"
);
assert_eq!(
ids(2),
- [("a", "a-file"), ("b", "b-file")],
- "the first two attached pictures"
+ [("a", "a-file"), ("b", "b-file"), ("c", "c-file")],
+ "three attached pictures"
+ );
+ assert_eq!(
+ ids(3),
+ [("a", "a-file"), ("b", "b-file"), ("c", "c-file")],
+ "the first three attached pictures"
);
- assert_eq!(recorded.len(), 3, "three named pictures are not scheduled");
+ assert_eq!(recorded.len(), 4, "four named pictures are not scheduled");
drop(recorded);
let refused = refused?;
assert_eq!(
@@ -5951,12 +6041,13 @@ mod tests {
#[tokio::test]
async fn only_a_video_with_sound_keeps_its_pictures() -> Result<(), ToolboxError> {
- let frames = vec![VideoFrameRef {
+ let pictures = vec![VideoFrameRef {
file_id: "first-file".to_owned(),
file_unique_id: "first".to_owned(),
}];
for (vip, text, kept) in [
(true, "оживи картинку", true),
+ (true, "этот кот летит в космосе", true),
(true, "сделай гифку из картинки", false),
(false, "оживи картинку", false),
] {
@@ -5964,17 +6055,90 @@ mod tests {
vip,
VideoScheduleRequest {
message_text: text.to_owned(),
- frames: frames.clone(),
+ pictures: pictures.clone(),
..video_request(11)
},
)
.await?;
let params = scheduled_video_params(&queue);
- assert_eq!(params.frames.is_empty(), !kept, "{text}, vip {vip}");
+ let scheduled = params.frames.len() + params.references.len();
+ assert_eq!(scheduled, usize::from(kept), "{text}, vip {vip}");
}
Ok(())
}
+ #[tokio::test]
+ async fn pictures_are_references_unless_the_user_asks_to_animate_them()
+ -> Result<(), ToolboxError> {
+ let pictures: Vec = ["a", "b", "c"]
+ .into_iter()
+ .map(|id| VideoFrameRef {
+ file_id: format!("{id}-file"),
+ file_unique_id: id.to_owned(),
+ })
+ .collect();
+ let schedule = |text: &str| {
+ let request = VideoScheduleRequest {
+ message_text: text.to_owned(),
+ pictures: pictures.clone(),
+ ..video_request(11)
+ };
+ async move {
+ let (queue, _) = schedule_video_as(true, request).await?;
+ Ok::<_, ToolboxError>(scheduled_video_params(&queue))
+ }
+ };
+ let unique_ids = |pictures: &[VideoFrameRef]| {
+ pictures
+ .iter()
+ .map(|picture| picture.file_unique_id.clone())
+ .collect::>()
+ };
+
+ let scene = schedule("/video эта бабушка кормит этого кота на кухне").await?;
+ assert!(scene.frames.is_empty());
+ assert_eq!(unique_ids(&scene.references), ["a", "b", "c"]);
+
+ let animated = schedule("оживи фото: кот потягивается").await?;
+ assert!(animated.references.is_empty());
+ assert_eq!(
+ unique_ids(&animated.frames),
+ ["a", "b"],
+ "a first and a last frame at most"
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn animating_a_picture_is_recognized_in_any_case_and_language() {
+ for text in [
+ "Оживи картинку",
+ "оживить фото",
+ "анимируй этого кота",
+ "пусть первый кадр будет как на фото",
+ "продолжи эту сцену",
+ "кот превращается в тигра",
+ "оживи світлину",
+ "анімуй фото",
+ "animate this photo",
+ "bring this picture to life",
+ "use it as the first frame",
+ ] {
+ assert!(asks_to_animate_picture(text), "{text}");
+ }
+ for text in [
+ "этот кот летит в космосе",
+ "анимированное видео с этой собакой",
+ "сделай мультяшную анимацию с ним",
+ "видео продолжительностью 10 секунд",
+ "кот гуляет по оживлённой улице",
+ "an animated clip of this dog",
+ "этот персонаж танцует гопак",
+ ] {
+ assert!(!asks_to_animate_picture(text), "{text}");
+ }
+ }
+
#[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 5b6d891..3dd92e7 100644
--- a/crates/openplotva-app/src/help.rs
+++ b/crates/openplotva-app/src/help.rs
@@ -65,7 +65,7 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"
Привет! Я {{.BotName}}
Видео:/video бабушка достаёт пирожки из печки или «{{.BotName}}, сгенерируй видео…». С VIP видео идёт со звуком: речь, шумы и музыка, а реплики в кавычках звучат дословно. Можно попросить вертикальное видео (для сторис, Reels, TikTok) и высокое качество — это дольше. Без VIP вместо видео будет гифка.
-
Оживить картинку (VIP): пришли картинку с подписью /video что должно произойти или ответь этой командой на картинку. Две картинки станут первым и последним кадром.
+
Видео по картинкам (VIP): пришли до трёх картинок с подписью /video что должно произойти или ответь этой командой на картинку. Люди, животные, предметы и места с картинок появятся в новой сцене целиком, без обрезки и полей. Чтобы видео началось с самой картинки, напиши «оживи»: тогда вторая картинка станет последним кадром.
Полезности
diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs
index 9df05fe..bee0049 100644
--- a/crates/openplotva-app/src/image_jobs.rs
+++ b/crates/openplotva-app/src/image_jobs.rs
@@ -803,6 +803,10 @@ pub struct DrawApiVideoOptions<'a> {
/// Data URL of the picture the video ends on.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_image_b64: Option<&'a str>,
+ /// Data URLs of the people, animals, objects or places the video shows in a new scene;
+ /// never together with the frames.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reference_b64: Option<&'a [String]>,
}
#[derive(Serialize)]
@@ -9057,6 +9061,7 @@ mod tests {
orientation: Some(openplotva_media::video::VideoOrientation::Portrait),
first_frame: Some("data:image/jpeg;base64,Zmlyc3Q=".to_owned()),
last_frame: None,
+ references: Vec::new(),
},
)
.await
diff --git a/crates/openplotva-app/src/video_jobs.rs b/crates/openplotva-app/src/video_jobs.rs
index 3aa1e6b..01278f1 100644
--- a/crates/openplotva-app/src/video_jobs.rs
+++ b/crates/openplotva-app/src/video_jobs.rs
@@ -11,7 +11,7 @@ use openplotva_llm::aifarm::AifarmHttpTransport;
use openplotva_llm::retry::{FailureReason, retryable_reason_from_message};
use openplotva_media::{
NsfwResult,
- video::{VideoOptimize, VideoOrientation, VideoPromptTarget},
+ video::{VideoOptimize, VideoOrientation, VideoPictureRole, VideoPromptTarget},
};
use openplotva_server::ACTION_SEND_VIDEO;
use openplotva_taskman::{
@@ -81,6 +81,8 @@ pub struct VideoRender {
pub first_frame: Option,
/// Data URL of the picture the video ends on.
pub last_frame: Option,
+ /// Data URLs of the pictures whose subjects the video shows in a new scene.
+ pub references: Vec,
}
impl VideoRender {
@@ -103,6 +105,7 @@ impl VideoRender {
orientation: self.orientation.map(VideoOrientation::as_str),
image_b64: self.first_frame.as_deref(),
last_image_b64: self.last_frame.as_deref(),
+ reference_b64: (!self.references.is_empty()).then_some(self.references.as_slice()),
}
}
}
@@ -184,7 +187,7 @@ pub struct VideoDelivery {
pub sound: bool,
}
-/// A picture a video starts from or ends on, ready for draw-api and the prompt writer.
+/// A picture of a video with sound, ready for draw-api and the prompt writer.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct LoadedVideoFrame {
/// `data:image/...;base64,...`.
@@ -227,8 +230,8 @@ pub trait VideoJobEffects: Send + Sync {
) -> VideoJobFuture<'a, Result