diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs index df0bde7..92ddc65 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,44 @@ 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 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() { + 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, 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 +3195,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 +3220,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 +5514,7 @@ mod tests { steps: 0, orientation: String::new(), admin_command: false, + frames: Vec::new(), } } @@ -5533,6 +5574,7 @@ mod tests { sound: false, steps: 0, orientation: String::new(), + frames: Vec::new(), }) ); assert_eq!( @@ -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?; @@ -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, 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::>() + }; + 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 [ 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, String>>; } +/// Longest side of a picture sent to draw-api: it cover-crops to at most 1024×576, and the +/// farm link is slow. +const VIDEO_FRAME_MAX_SIDE: u32 = 1280; + +/// Downloads the pictures of a video with sound and describes them for the prompt writer. +#[derive(Clone)] +pub struct TelegramVideoFrames { + data_urls: crate::vision::TelegramClientVisionDataUrlProvider, + describer: Arc, +} + +impl TelegramVideoFrames { + #[must_use] + pub fn new( + telegram: TelegramClient, + describer: Arc, + ) -> Self { + Self { + data_urls: crate::vision::TelegramClientVisionDataUrlProvider::new(telegram) + .with_max_side(VIDEO_FRAME_MAX_SIDE), + describer, + } + } + + async fn load( + &self, + params: &VideoGenJobParams, + frame: &VideoFrameRef, + ) -> Result { + use crate::vision::TelegramVisionDataUrlProvider as _; + + let data_url = self + .data_urls + .telegram_file_data_url(&frame.file_id, "photo", None) + .await + .map_err(|error| format!("download the picture: {error}"))?; + let picture = openplotva_core::ChatAttachment { + kind: "image".to_owned(), + source: "message".to_owned(), + file_id: frame.file_id.clone(), + file_unique_id: frame.file_unique_id.clone(), + ..openplotva_core::ChatAttachment::default() + }; + let described = self + .describer + .describe_image(crate::dialog_tools::VisionDescribeRequest { + file_id: frame.file_unique_id.clone(), + chat_id: params.chat_id, + message_id: params.message_id, + thread_id: params.thread_id, + message_meta: openplotva_core::ChatMessageMeta { + attachments: vec![picture], + ..openplotva_core::ChatMessageMeta::default() + }, + }) + .await + .map_err(|error| format!("describe the picture: {error}"))?; + let description = described.caption.trim(); + if description.is_empty() + || description == crate::vision::VISION_UNAVAILABLE_CAPTION + || !described.visual_error.trim().is_empty() + { + return Err("the picture has no description".to_owned()); + } + Ok(LoadedVideoFrame { + data_url, + description: description.to_owned(), + }) + } +} + /// Telegram effects: permission policy, reaction lifecycle, `sendAnimation` and `sendVideo`. pub struct TelegramVideoJobEffects { permissions: Arc>, telegram: TelegramClient, reactions: Option, + frames: Option, } impl TelegramVideoJobEffects { @@ -209,6 +306,7 @@ impl TelegramVideoJobEffects { permissions, telegram, reactions: None, + frames: None, } } @@ -218,6 +316,13 @@ impl TelegramVideoJobEffects { self } + /// Let videos with sound start from (and end on) chat pictures. + #[must_use] + pub fn with_frames(mut self, frames: TelegramVideoFrames) -> Self { + self.frames = Some(frames); + self + } + async fn react(&self, chat_id: i64, message_id: i32, progress: bool) { let Some(reactions) = self.reactions.as_deref() else { return; @@ -238,6 +343,19 @@ impl VideoJobEffects for TelegramVideoJobEffects where Store: ChatPermissionStore + Send + Sync, { + fn load_frame<'a>( + &'a self, + params: &'a VideoGenJobParams, + frame: &'a VideoFrameRef, + ) -> VideoJobFuture<'a, Result> { + Box::pin(async move { + match &self.frames { + Some(frames) => frames.load(params, frame).await, + None => Err("video frames are not configured".to_owned()), + } + }) + } + fn can_send_video<'a>(&'a self, chat_id: i64) -> VideoJobFuture<'a, bool> { Box::pin(async move { self.permissions @@ -428,6 +546,7 @@ where .signal_progress(params.chat_id, params.message_id) .await; let requested_orientation = VideoOrientation::parse(¶ms.orientation); + let frames = load_video_frames(effects, params).await; let optimized = optimizer .optimize_video_prompt( ¶ms.request_text, @@ -435,6 +554,10 @@ where VideoPromptTarget { sound: params.sound, orientation: requested_orientation, + pictures: frames + .iter() + .map(|frame| frame.description.clone()) + .collect(), }, ) .await?; @@ -447,15 +570,25 @@ where .await; return Ok(VideoJobOutcome::Blocked { message_id }); } + // A picture sets the frame unless the user asked for one; without pictures the optimizer + // infers it, and only portrait differs from the farm's default. + let orientation = if frames.is_empty() { + requested_orientation + .or(optimized.orientation) + .filter(|orientation| *orientation == VideoOrientation::Portrait) + } else { + requested_orientation + }; + let mut frames = frames.into_iter().map(|frame| frame.data_url); let render = VideoRender { sound: params.sound, steps: params.steps, - orientation: requested_orientation - .or(optimized.orientation) - .unwrap_or_default(), + orientation, + first_frame: frames.next(), + last_frame: frames.next(), }; let video = generator - .generate_video(&optimized.prompt, job_id, render) + .generate_video(&optimized.prompt, job_id, &render) .await?; let adult = optimized.nsfw_result == NsfwResult::Adult; let message_id = effects @@ -480,6 +613,37 @@ where Ok(VideoJobOutcome::Delivered { message_id }) } +/// The pictures of a video with sound. A picture that cannot be loaded drops them all: the +/// video is then made from the text alone instead of failing. +async fn load_video_frames( + effects: &Effects, + params: &VideoGenJobParams, +) -> Vec +where + Effects: VideoJobEffects + ?Sized, +{ + if !params.sound { + return Vec::new(); + } + let mut frames = Vec::new(); + for frame in params.frames.iter().take(2) { + match effects.load_frame(params, frame).await { + Ok(loaded) => frames.push(loaded), + Err(error) => { + tracing::warn!( + chat_id = params.chat_id, + message_id = params.message_id, + file_unique_id = %frame.file_unique_id, + %error, + "video frame unavailable; making the video from text" + ); + return Vec::new(); + } + } + } + frames +} + /// The clip title shown like a drawing's: the dialog caption, else the brief. fn video_caption_text(params: &VideoGenJobParams) -> &str { [¶ms.caption, ¶ms.brief, ¶ms.request_text] @@ -656,13 +820,13 @@ mod tests { &'a self, prompt: &'a str, job_id: i64, - render: VideoRender, + render: &'a VideoRender, ) -> VideoJobFuture<'a, Result> { self.prompts .lock() .expect("prompts") .push((prompt.to_owned(), job_id)); - self.renders.lock().expect("renders").push(render); + self.renders.lock().expect("renders").push(render.clone()); let fail = self.fail; Box::pin(async move { if fail { @@ -687,8 +851,10 @@ mod tests { #[derive(Default)] struct RecordingEffects { denied: bool, + missing_frames: bool, events: Mutex>, sent: Mutex>, + loaded_frames: Mutex>, } impl RecordingEffects { @@ -698,6 +864,28 @@ mod tests { } impl VideoJobEffects for RecordingEffects { + fn load_frame<'a>( + &'a self, + _params: &'a VideoGenJobParams, + frame: &'a VideoFrameRef, + ) -> VideoJobFuture<'a, Result> { + self.loaded_frames + .lock() + .expect("frames") + .push(frame.file_unique_id.clone()); + let id = frame.file_unique_id.clone(); + let missing = self.missing_frames && id == "last"; + Box::pin(async move { + if missing { + return Err("file is gone".to_owned()); + } + Ok(LoadedVideoFrame { + data_url: format!("data:image/jpeg;base64,{id}"), + description: format!("What {id} shows"), + }) + }) + } + fn can_send_video<'a>(&'a self, _chat_id: i64) -> VideoJobFuture<'a, bool> { let allowed = !self.denied; Box::pin(async move { allowed }) @@ -767,6 +955,7 @@ mod tests { sound: false, steps: 0, orientation: String::new(), + frames: Vec::new(), } } @@ -1070,6 +1259,21 @@ mod tests { requested: &str, inferred: Option, sound: bool, + ) -> (VideoPromptTarget, VideoRender) { + rendered_with( + &RecordingEffects::default(), + requested, + inferred, + VideoGenJobParams { sound, ..params() }, + ) + .await + } + + async fn rendered_with( + effects: &RecordingEffects, + requested: &str, + inferred: Option, + params: VideoGenJobParams, ) -> (VideoPromptTarget, VideoRender) { let optimizer = FixedOptimizer::new(Ok(VideoOptimize { prompt: "A fox runs through snow.".to_owned(), @@ -1080,20 +1284,19 @@ mod tests { execute_video_gen_job( &optimizer, &generator, - &RecordingEffects::default(), + effects, &VideoGenJobParams { - sound, steps: 4, orientation: requested.to_owned(), - ..params() + ..params }, 9, true, ) .await .expect("delivered"); - let target = optimizer.targets.lock().expect("targets")[0]; - let render = generator.renders.lock().expect("renders")[0]; + let target = optimizer.targets.lock().expect("targets")[0].clone(); + let render = generator.renders.lock().expect("renders")[0].clone(); (target, render) } @@ -1107,19 +1310,19 @@ mod tests { Some(Portrait), "the optimizer composes for it" ); - assert_eq!(render.orientation, Portrait); + assert_eq!(render.orientation, Some(Portrait)); let (target, render) = rendered_orientation("", Some(Portrait), true).await; assert_eq!(target.orientation, None, "the optimizer infers the frame"); - assert_eq!(render.orientation, Portrait); + assert_eq!(render.orientation, Some(Portrait)); let (_, render) = rendered_orientation("", None, true).await; - assert_eq!(render.orientation, Landscape, "landscape by default"); + assert_eq!(render.orientation, None, "the farm's landscape default"); assert_eq!( render.options(), DrawApiVideoOptions { steps: Some(4), - orientation: None, + ..DrawApiVideoOptions::default() } ); } @@ -1136,18 +1339,109 @@ mod tests { ); let portrait_movie = VideoRender { sound: true, - steps: 0, - orientation: VideoOrientation::Portrait, + orientation: Some(VideoOrientation::Portrait), + ..VideoRender::default() }; assert_eq!( portrait_movie.options(), DrawApiVideoOptions { - steps: None, orientation: Some("portrait"), + ..DrawApiVideoOptions::default() } ); } + fn frame(id: &str) -> VideoFrameRef { + VideoFrameRef { + file_id: format!("{id}-file"), + file_unique_id: id.to_owned(), + } + } + + #[tokio::test] + async fn pictures_become_the_first_and_last_frame_and_the_optimizer_sees_them() { + let effects = RecordingEffects::default(); + let (target, render) = rendered_with( + &effects, + "", + Some(VideoOrientation::Portrait), + VideoGenJobParams { + sound: true, + frames: vec![frame("first"), frame("last")], + ..params() + }, + ) + .await; + assert_eq!(target.pictures, ["What first shows", "What last shows"]); + assert_eq!( + render.options(), + DrawApiVideoOptions { + steps: Some(4), + orientation: None, + image_b64: Some("data:image/jpeg;base64,first"), + last_image_b64: Some("data:image/jpeg;base64,last"), + }, + "a picture sets the frame; the optimizer's guess is not sent" + ); + + let (_, render) = rendered_with( + &effects, + "landscape", + None, + VideoGenJobParams { + sound: true, + frames: vec![frame("first")], + ..params() + }, + ) + .await; + assert_eq!(render.orientation, Some(VideoOrientation::Landscape)); + assert_eq!( + render.first_frame.as_deref(), + Some("data:image/jpeg;base64,first") + ); + assert_eq!(render.last_frame, None); + } + + #[tokio::test] + async fn a_picture_that_cannot_be_loaded_leaves_a_video_from_text() { + let effects = RecordingEffects { + missing_frames: true, + ..RecordingEffects::default() + }; + let (target, render) = rendered_with( + &effects, + "", + None, + VideoGenJobParams { + sound: true, + frames: vec![frame("first"), frame("last")], + ..params() + }, + ) + .await; + assert!(target.pictures.is_empty()); + assert_eq!((render.first_frame, render.last_frame), (None, None)); + } + + #[tokio::test] + async fn a_silent_clip_ignores_pictures() { + let effects = RecordingEffects::default(); + let (target, render) = rendered_with( + &effects, + "", + None, + VideoGenJobParams { + frames: vec![frame("first")], + ..params() + }, + ) + .await; + assert!(target.pictures.is_empty()); + assert_eq!(render.options(), DrawApiVideoOptions::default()); + assert!(effects.loaded_frames.lock().expect("frames").is_empty()); + } + #[test] fn only_farm_side_render_failures_get_a_second_submission() { use crate::image_jobs::ImageGenerationError::{Forbidden, Provider}; diff --git a/crates/openplotva-dialog/src/dispatch.rs b/crates/openplotva-dialog/src/dispatch.rs index 603a03f..eea9fbf 100644 --- a/crates/openplotva-dialog/src/dispatch.rs +++ b/crates/openplotva-dialog/src/dispatch.rs @@ -122,6 +122,7 @@ pub async fn dispatch_dialog_tool( caption: step.caption.clone(), quality: step.quality.trim().to_lowercase(), orientation: step.orientation.trim().to_lowercase(), + file_ids: step.file_ids.clone(), }; if movie { toolbox.make_movie(request).await diff --git a/crates/openplotva-dialog/src/lib.rs b/crates/openplotva-dialog/src/lib.rs index 914262a..da1478a 100644 --- a/crates/openplotva-dialog/src/lib.rs +++ b/crates/openplotva-dialog/src/lib.rs @@ -306,6 +306,9 @@ pub struct VideoRequest { /// Frame of a video with sound: "portrait" (vertical) or empty for landscape. #[serde(default, skip_serializing_if = "String::is_empty")] pub orientation: String, + /// Pictures a video with sound starts from (and ends on, with two). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub file_ids: Vec, } #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] @@ -723,6 +726,15 @@ const MAKE_VIDEO_ARGS: &[ToolArgSpec] = &[ description: "\"high\" only when the user explicitly asks for a more detailed, sharper or \ higher-quality video with sound; it takes about twice as long. Omit it otherwise.", }, + ToolArgSpec { + name: "file_ids", + required: false, + description: "Pictures to animate, for a video with sound: one picture is the first frame, \ + two are the first and the last frame, in that order. Copy their file_id handle \ + or file_unique_id from the dialog attachments. Omit for a video from text, or \ + when the pictures are attached to or quoted by the current message: they are \ + used automatically.", + }, ]; const VISION_IMAGE_ARGS: &[ToolArgSpec] = &[ToolArgSpec { @@ -962,8 +974,8 @@ const ALTERNATIVE_DIALOG_TOOL_CATALOG: &[ToolSpec] = &[ summary: "Generate a GIF: a short silent video clip from a text description.", when_to_use: "Use when the latest user message asks for a GIF (гифка, gif) or explicitly \ for a clip without sound. For any other video request call make_movie. It \ - makes one continuous five-second shot from text only; it cannot animate an \ - attached picture.", + makes one continuous five-second shot from text only; it cannot animate a \ + picture.", result: "Schedules video generation and ENDS your turn; the clip arrives asynchronously. \ Call it without accompanying text or a promise to make the clip: text alongside \ a tool call is not published.", @@ -978,8 +990,9 @@ const ALTERNATIVE_DIALOG_TOOL_CATALOG: &[ToolSpec] = &[ animation or moving picture (видео, ролик, клип, фильм, анимация, \ сгенерируй видео) and does not ask for a GIF. Call it for every user: the \ bot checks VIP itself and makes a silent clip for users without VIP. Pass \ - any line the user wants spoken verbatim in prompt. It renders from text \ - only; it cannot animate an attached picture.", + any line the user wants spoken verbatim in prompt. A VIP video can start \ + from a picture (оживи картинку) and end on a second one; describe in prompt \ + what should happen to them.", result: "Schedules video generation and ENDS your turn; the video arrives asynchronously. \ Call it without accompanying text or a promise to make the video: text alongside \ a tool call is not published.", diff --git a/crates/openplotva-llm/src/aifarm.rs b/crates/openplotva-llm/src/aifarm.rs index cf6fd16..5237600 100644 --- a/crates/openplotva-llm/src/aifarm.rs +++ b/crates/openplotva-llm/src/aifarm.rs @@ -2424,10 +2424,10 @@ where } let messages = match self.client.prompt_store() { Some(prompts) => openplotva_media::video::render_video_optimizer_messages_with( - prompts, request, brief, target, + prompts, request, brief, &target, )?, None => { - openplotva_media::video::render_video_optimizer_messages(request, brief, target)? + openplotva_media::video::render_video_optimizer_messages(request, brief, &target)? } } .into_iter() diff --git a/crates/openplotva-media/src/video.rs b/crates/openplotva-media/src/video.rs index 119599e..e3b4a97 100644 --- a/crates/openplotva-media/src/video.rs +++ b/crates/openplotva-media/src/video.rs @@ -40,12 +40,14 @@ impl VideoOrientation { } /// The clip the optimizer writes a prompt for. -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct VideoPromptTarget { /// A video with sound (MiniMax-H3) instead of a silent clip (FastFrames). pub sound: bool, /// The frame the dialog asked for; `None` lets the optimizer of a video with sound infer it. pub orientation: Option, + /// What the pictures of a video with sound show: the first frame, then the last one. + pub pictures: Vec, } /// One optimized clip prompt with the safety verdict for the request. @@ -88,7 +90,7 @@ const fn optimizer_prompt_name(sound: bool) -> &'static str { pub fn render_video_optimizer_messages( request: &str, brief: &str, - target: VideoPromptTarget, + target: &VideoPromptTarget, ) -> Result, openplotva_prompts::PromptError> { openplotva_prompts::render_messages( optimizer_prompt_name(target.sound), @@ -100,7 +102,7 @@ pub fn render_video_optimizer_messages_with( prompts: &openplotva_prompts::PromptStore, request: &str, brief: &str, - target: VideoPromptTarget, + target: &VideoPromptTarget, ) -> Result, openplotva_prompts::PromptError> { prompts.render_messages( optimizer_prompt_name(target.sound), @@ -108,9 +110,9 @@ pub fn render_video_optimizer_messages_with( ) } -/// The brief is shown only when it adds something to the request. The requested frame goes -/// to the user message, so the system prompt stays the same for every request. -fn video_optimizer_template_data(request: &str, brief: &str, target: VideoPromptTarget) -> Value { +/// The brief is shown only when it adds something to the request. The requested frame and the +/// pictures go to the user message, so the system prompt stays the same for every request. +fn video_optimizer_template_data(request: &str, brief: &str, target: &VideoPromptTarget) -> Value { let request = request.trim(); let brief = brief.trim(); let (request, brief) = if request.is_empty() { @@ -124,7 +126,29 @@ fn video_optimizer_template_data(request: &str, brief: &str, target: VideoPrompt .orientation .filter(|_| target.sound) .map_or("", VideoOrientation::as_str); - json!({ "request": request, "brief": brief, "frame": frame }) + let pictures = if target.sound { + picture_lines(&target.pictures) + } else { + Vec::new() + }; + json!({ "request": request, "brief": brief, "frame": frame, "pictures": pictures }) +} + +/// "Picture 1, the first frame: …" and, with two pictures, "Picture 2, the last frame: …". +fn picture_lines(pictures: &[String]) -> Vec { + pictures + .iter() + .take(2) + .enumerate() + .map(|(index, description)| { + let role = if index == 0 { "first" } else { "last" }; + format!( + "Picture {}, the {role} frame: {}", + index + 1, + description.split_whitespace().collect::>().join(" ") + ) + }) + .collect() } /// A video with sound also returns its frame, before the prompt written for it. @@ -186,7 +210,7 @@ mod tests { let messages = render_video_optimizer_messages( "@plotva_bot сделай видео: корги на сёрфе", "A corgi surfing a wave at sunset", - VideoPromptTarget::default(), + &VideoPromptTarget::default(), ) .expect("render"); @@ -206,9 +230,9 @@ mod tests { let messages = render_video_optimizer_messages( "бабушка зовёт внука есть пирожки", "Grandma calls her grandson to eat pies", - VideoPromptTarget { + &VideoPromptTarget { sound: true, - orientation: None, + ..VideoPromptTarget::default() }, ) .expect("render"); @@ -232,16 +256,17 @@ mod tests { let target = |sound| VideoPromptTarget { sound, orientation: Some(VideoOrientation::Portrait), + ..VideoPromptTarget::default() }; - let movie = render_video_optimizer_messages("кот на крыше", "", target(true)) + let movie = render_video_optimizer_messages("кот на крыше", "", &target(true)) .expect("render a video with sound"); assert_eq!(movie[1].content, "Request: кот на крыше\nFrame: portrait"); let inferred = render_video_optimizer_messages( "кот на крыше", "", - VideoPromptTarget { + &VideoPromptTarget { sound: true, - orientation: None, + ..VideoPromptTarget::default() }, ) .expect("render without a frame"); @@ -250,11 +275,43 @@ mod tests { "the system prompt does not change" ); assert_eq!(inferred[1].content, "Request: кот на крыше"); - let clip = render_video_optimizer_messages("кот на крыше", "", target(false)) + let clip = render_video_optimizer_messages("кот на крыше", "", &target(false)) .expect("render a silent clip"); assert_eq!(clip[1].content, "Request: кот на крыше"); } + #[test] + fn the_pictures_of_a_video_with_sound_follow_the_request_as_first_and_last_frame() { + let pictures = vec![ + "Рыжий кот\nсидит на подоконнике.".to_owned(), + "Кот спит на диване.".to_owned(), + ]; + let movie = render_video_optimizer_messages( + "оживи: кот перебирается на диван", + "", + &VideoPromptTarget { + sound: true, + pictures: pictures.clone(), + ..VideoPromptTarget::default() + }, + ) + .expect("render a video from pictures"); + assert_eq!( + movie[1].content, + "Request: оживи: кот перебирается на диван\nPicture 1, the first frame: Рыжий кот сидит на подоконнике.\nPicture 2, the last frame: Кот спит на диване." + ); + let clip = render_video_optimizer_messages( + "оживи: кот перебирается на диван", + "", + &VideoPromptTarget { + pictures, + ..VideoPromptTarget::default() + }, + ) + .expect("render a silent clip"); + assert_eq!(clip[1].content, "Request: оживи: кот перебирается на диван"); + } + #[test] fn only_videos_with_sound_ask_the_optimizer_for_a_frame() { assert_eq!( @@ -269,7 +326,7 @@ mod tests { for (request, brief) in [("кот и снег", "кот и снег"), ("", "кот и снег")] { let messages = - render_video_optimizer_messages(request, brief, VideoPromptTarget::default()) + render_video_optimizer_messages(request, brief, &VideoPromptTarget::default()) .expect("render"); assert_eq!(messages[1].content, "Request: кот и снег"); } diff --git a/crates/openplotva-taskman/src/lib.rs b/crates/openplotva-taskman/src/lib.rs index f51185e..7dbfc36 100644 --- a/crates/openplotva-taskman/src/lib.rs +++ b/crates/openplotva-taskman/src/lib.rs @@ -519,6 +519,15 @@ pub struct VideoGenJobParams { pub steps: u8, /// Frame of a video with sound: "portrait", or empty for the farm's landscape default. pub orientation: String, + /// Pictures a video with sound starts from and, with two, ends on. + pub frames: Vec, +} + +/// A Telegram picture a video starts from or ends on. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +pub struct VideoFrameRef { + pub file_id: String, + pub file_unique_id: String, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] @@ -2855,6 +2864,7 @@ const VIDEO_JOB_CAPTION_META_KEY: &str = "caption"; const VIDEO_JOB_SOUND_META_KEY: &str = "sound"; const VIDEO_JOB_STEPS_META_KEY: &str = "steps"; const VIDEO_JOB_ORIENTATION_META_KEY: &str = "orientation"; +const VIDEO_JOB_FRAMES_META_KEY: &str = "frames"; #[must_use] pub fn new_video_gen_job_at( @@ -2907,6 +2917,10 @@ fn video_job_meta(params: &VideoGenJobParams) -> serde_json::Value { if !params.orientation.is_empty() { meta[VIDEO_JOB_ORIENTATION_META_KEY] = serde_json::Value::from(params.orientation.as_str()); } + if !params.frames.is_empty() { + meta[VIDEO_JOB_FRAMES_META_KEY] = + serde_json::to_value(¶ms.frames).unwrap_or(serde_json::Value::Null); + } meta } @@ -2978,6 +2992,12 @@ pub fn video_gen_job_params_from_payload( .and_then(|steps| u8::try_from(steps).ok()) .unwrap_or(0), orientation: meta_text(VIDEO_JOB_ORIENTATION_META_KEY), + frames: clip + .meta + .get(VIDEO_JOB_FRAMES_META_KEY) + .cloned() + .and_then(|frames| serde_json::from_value(frames).ok()) + .unwrap_or_default(), }) } @@ -3937,9 +3957,9 @@ mod tests { STUCK_JOB_ERROR_MESSAGE, StatelessJobItem, TASK_QUEUE_SNAPSHOT_FORMAT, TEXT_QUEUE_NAME, TaskQueueError, TaskQueueJobEvent, TaskQueueJobMessageParams, TaskQueueRecord, TaskQueueSchedule, TaskQueueScheduleDisposition, TaskQueueWalRecord, TaskQueueWalSink, - VideoGenJobParams, accelerator_effective_priority, asr_job_params_from_stateless_job, - decode_task_queue_snapshot, encode_task_queue_snapshot, fallback_queue_time_estimate, - format_duration_ru, image_edit_job_params_from_stateless_job, + VideoFrameRef, VideoGenJobParams, accelerator_effective_priority, + asr_job_params_from_stateless_job, decode_task_queue_snapshot, encode_task_queue_snapshot, + fallback_queue_time_estimate, format_duration_ru, image_edit_job_params_from_stateless_job, image_gen_job_params_from_stateless_job, music_gen_job_params_from_stateless_job, new_agent_job_at, new_asr_job_at, new_control_job_at, new_dialog_job_at, new_image_edit_job_at, new_image_gen_job_at, new_memory_consolidation_job_at, @@ -5123,6 +5143,16 @@ mod tests { sound: true, steps: 4, orientation: "portrait".to_owned(), + frames: vec![ + VideoFrameRef { + file_id: "first-file".to_owned(), + file_unique_id: "first".to_owned(), + }, + VideoFrameRef { + file_id: "last-file".to_owned(), + file_unique_id: "last".to_owned(), + }, + ], ..VideoGenJobParams::default() }; let movie = new_video_gen_job_at(params.clone(), now); @@ -5136,6 +5166,7 @@ mod tests { sound: false, steps: 0, orientation: String::new(), + frames: Vec::new(), ..params }, now, diff --git a/prompts/aifarm/system.prompt b/prompts/aifarm/system.prompt index 584f45c..4edeb86 100644 --- a/prompts/aifarm/system.prompt +++ b/prompts/aifarm/system.prompt @@ -10,7 +10,7 @@ Команды и разговорные шорткаты задают намерение пользователя: выполни соответствующее действие через инструмент. Прямая просьба нарисовать, сгенерировать, переделать или отредактировать изображение требует вызова draw_image (draw_api для %). Не заменяй действие рассуждением, описанием, обещанием или вопросом «начать?». По известному запросу сразу вызови инструмент; уточняй только недостающую деталь, без которой результат нельзя получить. Обычное рисование не требует предварительного get_user_status: исполнитель сам проверит доступ и лимиты. Действующие ограничения контента и результат инструмента сохраняют силу. Графики, диаграммы, схемы и планы по данным или размерам, таблицы, конвертацию файлов, обработку аудио и видео и точные расчёты делай через run_python: draw_image рисует иллюстрации, а не данные. Заголовки, подписи и текст на графиках пиши на языке собеседника. Чтобы поправить прежний результат run_python, возьми его код из истории и измени только то, о чём просят. - Для draw_image, draw_api, make_video и make_movie всегда передавай caption: короткое название запрошенного изображения или ролика на языке пользователя. Убери обращение к боту, просьбу рисовать или сделать видео и слова вежливости. Сохрани смысл, имена и детали пользователя; название оформи естественно, с заглавной буквы. «Плотва, нарисуй собаквака» → caption «Собака-квака»; «Плотва, а нарисуй же мне, пожалуйста, золотую рыбку в кляре» → caption «Золотая рыбка в кляре». В prompt передавай отдельные, при необходимости обогащённые инструкции генератору. Не добавляй в caption придуманные для генератора детали и технический промпт. Если вызов вернул image_caption_required или video_caption_required, добавь подпись и повтори вызов: генерация ещё не началась. Просьбу о видео, ролике, клипе или анимации («сгенерируй видео», /video) выполняй через make_movie, просьбу о гифке или ролике без звука (/gif) — через make_video; не заменяй видео картинкой через draw_image. Звук выбирает бот: VIP получает пять секунд со звуком, речью и музыкой, остальные — беззвучную гифку, поэтому не отказывай из-за VIP. Реплики, которые пользователь просит произнести, передай в prompt дословно. Для вертикального видео (просьба о вертикальном кадре, сторис, Reels, TikTok, Shorts) передай orientation="portrait". + Для draw_image, draw_api, make_video и make_movie всегда передавай caption: короткое название запрошенного изображения или ролика на языке пользователя. Убери обращение к боту, просьбу рисовать или сделать видео и слова вежливости. Сохрани смысл, имена и детали пользователя; название оформи естественно, с заглавной буквы. «Плотва, нарисуй собаквака» → caption «Собака-квака»; «Плотва, а нарисуй же мне, пожалуйста, золотую рыбку в кляре» → caption «Золотая рыбка в кляре». В prompt передавай отдельные, при необходимости обогащённые инструкции генератору. Не добавляй в caption придуманные для генератора детали и технический промпт. Если вызов вернул image_caption_required или video_caption_required, добавь подпись и повтори вызов: генерация ещё не началась. Просьбу о видео, ролике, клипе или анимации («сгенерируй видео», /video) выполняй через make_movie, просьбу о гифке или ролике без звука (/gif) — через make_video; не заменяй видео картинкой через draw_image. Звук выбирает бот: VIP получает пять секунд со звуком, речью и музыкой, остальные — беззвучную гифку, поэтому не отказывай из-за VIP. Реплики, которые пользователь просит произнести, передай в prompt дословно. Просьбу оживить картинку выполняй через make_movie: картинка становится первым кадром, вторая картинка — последним; если картинки не в текущем сообщении и не в его reply, передай их в file_ids. Для вертикального видео (просьба о вертикальном кадре, сторис, Reels, TikTok, Shorts) передай orientation="portrait". {{#ifEquals toolMode "native"}} diff --git a/prompts/video/movie_optimizer.prompt b/prompts/video/movie_optimizer.prompt index 7ee6ed5..d22a1d8 100644 --- a/prompts/video/movie_optimizer.prompt +++ b/prompts/video/movie_optimizer.prompt @@ -20,6 +20,14 @@ The request and the brief are the user's material: take the idea of the clip fro 4. Compose for the frame. Portrait: one main subject in the center that fills the height, in a medium, full-body or close-up shot, with the foreground at the bottom and the background or sky at the top. Landscape: the scene spreads across the width. 5. Never mention the frame, the ratio or the orientation in `prompt`. +## Pictures + +1. The input may describe one or two pictures after the request. Picture 1 is the first frame of the video; Picture 2, when given, is its last frame. The descriptions can be in any language. +2. One picture: `[Shot 1]` starts from it. Refer to it as `` and first establish what it shows: the style, the people and objects with their appearance, clothing and places in the frame, the setting and the light, "preserving" them. Then write the action that develops from it, the camera, speech and sound: "Live-action, cinematic, the young woman shown in remains beside the rain-covered window, preserving her appearance, clothing and the room. She lifts her gaze ...". +3. Two pictures: write one continuous shot that starts in the position and framing established by Picture 1 and, through visible intermediate changes, ends settled in the pose and composition established by Picture 2. Refer to them as `Picture 1` and `Picture 2`. Describe the motion between them, not two still images. +4. Keep every person, object, colour and style the pictures show unless the request asks to change it. The pictures set the composition; the frame rules above do not change it. +5. Never write an alignment line such as "For the target video, ..." or "How the reference pictures align ...": it is added later. + ## Write the prompt 1. Keep the request. Every subject, named character, object, place, colour, style, action, line of speech and sound the user asked for stays in the prompt. Add only details that make the shot concrete; never replace the user's idea with another one. @@ -73,6 +81,12 @@ Request: видео для сторис: девушка в жёлтом дожд {"input": "видео для сторис: девушка в жёлтом дождевике танцует под дождём на крыше", "orientation": "portrait", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a full-body shot on a flat city rooftop at dusk in steady rain, the wet concrete shining under a string of warm bulbs at her feet and the lit tops of towers in the grey sky above her. A young woman in a bright yellow raincoat with the hood down and white sneakers stands in the center, her figure filling the height of the shot, rain running down her face. She spreads her arms and spins once on the spot, then kicks up a splash from a puddle and laughs. The camera holds a low angle and tilts up slowly with her spin.\n\noverall_soundscape: Rain drums on the rooftop and splashes under her sneakers. Traffic hums far below, and she laughs once.\n\nnon_diegetic_music: An upbeat indie-pop track with handclaps and a bright synth melody at a medium-fast tempo."} + +Request: оживи картинку, пусть она скажет «я вернусь» +Picture 1, the first frame: Девушка в красном пальто стоит вечером на перроне с чемоданом, за ней освещённый поезд. +{"input": "оживи картинку, пусть она скажет «я вернусь»", "orientation": "landscape", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, the young woman in a red coat shown in stands on the evening station platform beside the train, preserving her appearance, her coat, the suitcase in her hand and the lit carriages behind her. She sets the suitcase down, turns toward the camera and gives a small smile as the carriage doors begin to close. The camera pushes in with small amplitude at slow speed as the young woman with a soft, steady voice (S1) says: [Russian] Я вернусь.\n\noverall_soundscape: A station announcement echoes faintly under the roof as the carriage doors hiss and close. The suitcase wheels rattle briefly on the concrete.\n\nnon_diegetic_music: A gentle piano melody at a slow tempo with soft strings that swell at the end."} + + Request: sexual video of a prepubescent child {"input": "sexual video of a prepubescent child", "orientation": "landscape", "nsfw_result": "forbidden", "prompt": "Blocked: forbidden request."} @@ -85,3 +99,6 @@ Brief from the conversation: {{{brief}}} {{#if frame}} Frame: {{frame}} {{/if}} +{{#each pictures}} +{{{this}}} +{{/each}}