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
232 changes: 198 additions & 34 deletions crates/openplotva-app/src/dialog_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<VideoFrameRef>,
/// Pictures for a video with sound, at most three, in order.
pub pictures: Vec<VideoFrameRef>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
Expand Down Expand Up @@ -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<VideoFrameRef>,
message_text: &str,
) -> (Vec<VideoFrameRef>, Vec<VideoFrameRef>) {
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| {
Expand Down Expand Up @@ -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,
Expand All @@ -1734,7 +1805,8 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
} else {
String::new()
},
frames: if sound { request.frames } else { Vec::new() },
frames,
references,
},
OffsetDateTime::now_utc(),
)
Expand Down Expand Up @@ -2639,8 +2711,8 @@ impl<RatesFetcherT, RatesDispatcherT, TranslatorT>
"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 {
Expand All @@ -2659,11 +2731,11 @@ impl<RatesFetcherT, RatesDispatcherT, TranslatorT>
.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(),
};
Expand Down Expand Up @@ -3141,25 +3213,26 @@ fn draw_image_attachments(req: &DrawRequest) -> Result<Vec<ChatAttachment>, 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<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() {
/// 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<Vec<ChatAttachment>, String> {
let mut pictures: Vec<ChatAttachment> =
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(
Expand Down Expand Up @@ -5514,7 +5587,7 @@ mod tests {
steps: 0,
orientation: String::new(),
admin_command: false,
frames: Vec::new(),
pictures: Vec::new(),
}
}

Expand Down Expand Up @@ -5575,6 +5648,7 @@ mod tests {
steps: 0,
orientation: String::new(),
frames: Vec::new(),
references: Vec::new(),
})
);
assert_eq!(
Expand Down Expand Up @@ -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::<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"
"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!(
Expand All @@ -5951,30 +6041,104 @@ 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),
] {
let (queue, _) = schedule_video_as(
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<VideoFrameRef> = ["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::<Vec<_>>()
};

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 [
Expand Down
2 changes: 1 addition & 1 deletion crates/openplotva-app/src/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ 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>
<p><b>Видео по картинкам (VIP):</b> пришли до трёх картинок с подписью <code>/video что должно произойти</code> или ответь этой командой на картинку. Люди, животные, предметы и места с картинок появятся в новой сцене целиком, без обрезки и полей. Чтобы видео началось с самой картинки, напиши «оживи»: тогда вторая картинка станет последним кадром.</p>

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

Expand Down
5 changes: 5 additions & 0 deletions crates/openplotva-app/src/image_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading