diff --git a/crates/openplotva-app/src/agent_tools.rs b/crates/openplotva-app/src/agent_tools.rs
index bbb8283..bfa1b91 100644
--- a/crates/openplotva-app/src/agent_tools.rs
+++ b/crates/openplotva-app/src/agent_tools.rs
@@ -81,7 +81,7 @@ impl DialogToolbox for AgentContextTools {
.await
{
Ok(vip) => Ok(ok(
- json!({"user_id":ctx.user_id, "status":"verified", "vip":vip, "entitlements":{"generate_song":vip,"edit_image":vip,"draw_image":true,"make_video":true,"make_movie":vip},"subject_to_chat_policy_and_rate_limits":true}),
+ json!({"user_id":ctx.user_id, "status":"verified", "vip":vip, "entitlements":{"generate_song":vip,"edit_image":vip,"draw_image":true,"make_video":true,"make_movie":true,"video_with_sound":vip},"subject_to_chat_policy_and_rate_limits":true}),
)),
Err(_) => Ok(ToolResult::failed(
"status_unknown",
diff --git a/crates/openplotva-app/src/dialog_messages.rs b/crates/openplotva-app/src/dialog_messages.rs
index 21228c0..492fcaf 100644
--- a/crates/openplotva-app/src/dialog_messages.rs
+++ b/crates/openplotva-app/src/dialog_messages.rs
@@ -12,14 +12,16 @@ use openplotva_core::{
};
use openplotva_dialog::PROVIDER_AIFARM;
use openplotva_taskman::{
- DIALOG_AIFARM_QUEUE_NAME, DialogJobParams, HIGH_PRIORITY, InMemoryTaskQueue, TEXT_QUEUE_NAME,
- TaskQueueSchedule, clean_unicode_non_printables, new_dialog_job_at,
+ ADMIN_COMMAND_PRIORITY, DIALOG_AIFARM_QUEUE_NAME, DialogJobParams, HIGH_PRIORITY,
+ InMemoryTaskQueue, TEXT_QUEUE_NAME, TaskQueueSchedule, clean_unicode_non_printables,
+ new_dialog_job_at,
};
use openplotva_telegram::{
- ChatRef, DispatcherQueue, OutboundBuildError, PhotoMessageRequest, PhotoSource,
- ReplyMessageRef, ReplyParametersPlan, StickerMessageRequest, TelegramClient,
- TelegramOutboundMethod, TelegramOutboundMethodKind, TelegramOutboundResponse,
- TextMessageRequest,
+ ChatRef, DeleteMessageRequest, DispatcherQueue, OutboundBuildError, PhotoMessageRequest,
+ PhotoSource, ReplyMessageRef, ReplyParametersPlan, StickerMessageRequest,
+ TELEGRAM_PARSE_MODE_HTML, TelegramClient, TelegramOutboundMethod, TelegramOutboundMethodKind,
+ TelegramOutboundResponse, TextMessageRequest, build_delete_message_method,
+ escape_telegram_html_text,
};
use openplotva_updates::{
FetcherMessageContext, HistoryTextEntry, build_fetcher_message_context,
@@ -215,6 +217,14 @@ pub struct DirectDrawFailurePlan {
pub restriction_notice: DirectSongNoticePlan,
}
+/// Usage hint for a generation command sent without a subject.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CommandUsageHintPlan {
+ pub notice: DirectSongNoticePlan,
+ /// The empty command message; deleted where the bot may delete it.
+ pub command_message: DeleteMessageRequest,
+}
+
/// Boxed future returned by direct song notice side effects.
pub type DirectSongNoticeFuture<'a> = Pin> + Send + 'a>>;
/// Boxed future returned by direct draw failure side effects.
@@ -233,6 +243,13 @@ pub trait DirectSongNoticeEffects: Send + Sync {
) -> DirectDrawFailureFuture<'a> {
Box::pin(async { Ok(()) })
}
+
+ fn send_command_usage_hint<'a>(
+ &'a self,
+ _plan: CommandUsageHintPlan,
+ ) -> DirectSongNoticeFuture<'a> {
+ Box::pin(async { Ok(()) })
+ }
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -799,6 +816,9 @@ impl crate::dialog_tools::ImageFallbackNoticeSender for DrawQueueNoticeDispatche
pub struct RandomDialogDispatcherEffects {
queue: Arc,
next_virtual_id: VirtualIdFactory,
+ /// Deletes an empty command message directly: the bot may lack the right, and a
+ /// refused delete must not wait in the outbound queue.
+ telegram: Option,
}
impl RandomDialogDispatcherEffects {
@@ -808,9 +828,17 @@ impl RandomDialogDispatcherEffects {
Self {
queue,
next_virtual_id: monotonic_virtual_id_factory("random-dialog-vmsg"),
+ telegram: None,
}
}
+ /// Delete empty command messages through this client.
+ #[must_use]
+ pub fn with_telegram(mut self, telegram: TelegramClient) -> Self {
+ self.telegram = Some(telegram);
+ self
+ }
+
/// Override virtual-message ID generation for deterministic tests.
#[must_use]
pub fn with_virtual_id_factory(mut self, next_virtual_id: VirtualIdFactory) -> Self {
@@ -854,6 +882,31 @@ impl RandomDialogEffects for RandomDialogDispatcherEffects {
}
impl DirectSongNoticeEffects for RandomDialogDispatcherEffects {
+ fn send_command_usage_hint<'a>(
+ &'a self,
+ plan: CommandUsageHintPlan,
+ ) -> DirectSongNoticeFuture<'a> {
+ Box::pin(async move {
+ self.send_direct_song_notice(plan.notice).await?;
+ let Some(telegram) = &self.telegram else {
+ return Ok(());
+ };
+ let method = build_delete_message_method(&plan.command_message)
+ .map_err(|error| error.to_string())?;
+ if let Err(error) =
+ openplotva_telegram::execute_telegram_method(telegram, method.into()).await
+ {
+ tracing::debug!(
+ chat_id = plan.command_message.chat_id,
+ message_id = plan.command_message.message_id,
+ %error,
+ "empty command message stays: the bot may not delete it"
+ );
+ }
+ Ok(())
+ })
+ }
+
fn send_direct_song_notice<'a>(
&'a self,
plan: DirectSongNoticePlan,
@@ -1136,7 +1189,9 @@ impl DialogMessageScheduler for TaskmanDialogMessageScheduler {
user_id: schedule.sender_id,
thread_id: schedule.thread_id.unwrap_or_default().into(),
};
- if let Some(rate_limit) = self.task_enqueue_rate_limit.as_deref() {
+ // An admin shortcut neither waits for the debounce nor counts against the limit.
+ let admin_command = schedule.meta.admin_command;
+ if !admin_command && let Some(rate_limit) = self.task_enqueue_rate_limit.as_deref() {
let report = rate_limit
.check_task_enqueue_rate_limit(
schedule.chat_id,
@@ -1162,7 +1217,11 @@ impl DialogMessageScheduler for TaskmanDialogMessageScheduler {
}
}
let now = OffsetDateTime::now_utc();
- let delay = InMemoryDialogDebounce::delay_or_default(self.debounce_delay);
+ let delay = if admin_command {
+ Duration::ZERO
+ } else {
+ InMemoryDialogDebounce::delay_or_default(self.debounce_delay)
+ };
let params = DialogJobParams {
chat_id: schedule.chat_id,
message_id: schedule.message_id,
@@ -1375,6 +1434,8 @@ pub enum DialogMessageUpdateRoute {
},
SongMissingTopic,
ImageEditMissingPrompt,
+ /// A generation command without a subject: the bot showed how to use it.
+ CommandUsageHint,
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
@@ -1660,12 +1721,11 @@ where
.as_ref()
.map(ToString::to_string)
.unwrap_or_default();
+ let admin = config
+ .admin_ids
+ .contains(&resolve_message_sender(Some(message)).id);
if parsed.is_addressed
- || is_bang_draw_shortcut(&first_word_lower)
- || is_bang_song_shortcut(&first_word_lower)
- || is_song_command_for_bot(message, &first_word_lower, &bot_username)
- || is_video_shortcut(message, &first_word_lower, &bot_username)
- || is_movie_shortcut(message, &first_word_lower, &bot_username)
+ || generation_invocation(message, &first_word_lower, &bot_username, admin).is_some()
|| is_search_command_for_bot(message, &first_word_lower, &bot_username)
{
return handle_dialog_message_update_or_else_with_image_and_song_notices(
@@ -1811,25 +1871,11 @@ where
{
parsed.is_addressed = true;
}
- parsed.is_addressed |= is_bang_draw_shortcut(&first_word_lower)
- || is_video_shortcut(message, &first_word_lower, &bot_username)
- || is_movie_shortcut(message, &first_word_lower, &bot_username)
- || direct_song_shortcut_topic(
- message,
- parsed.is_addressed,
- &first_word_lower,
- &parsed.rest_text,
- &bot_username,
- )
- .is_some();
+ let admin = config.admin_ids.contains(&sender.id);
+ let invocation = generation_invocation(message, &first_word_lower, &bot_username, admin);
+ parsed.is_addressed |= invocation.is_some();
let parsed = parsed;
if !parsed.is_addressed {
- if is_bang_draw_shortcut(&first_word_lower) {
- return Ok(DialogMessageUpdateRoute::DrawImageScheduled {
- status: "not_scheduled".to_owned(),
- no_reply: true,
- });
- }
handle_other(update)
.await
.map_err(|error| DialogMessageUpdateError::Downstream {
@@ -1837,6 +1883,23 @@ where
})?;
return Ok(DialogMessageUpdateRoute::Delegated);
}
+ if let Some(invocation) = invocation
+ && command_subject_missing(message, &parsed.rest_text)
+ {
+ if let Some(effects) = shortcuts.2
+ && let Err(error) = effects
+ .send_command_usage_hint(command_usage_hint_plan(
+ message,
+ chat_id,
+ message_id,
+ invocation.command,
+ ))
+ .await
+ {
+ tracing::warn!(chat_id, message_id, %error, "failed to send the command usage hint");
+ }
+ return Ok(DialogMessageUpdateRoute::CommandUsageHint);
+ }
let mut context = build_fetcher_message_context(message);
if let Some(TelegramReplyTo::Message(reply)) = &message.reply_to {
@@ -1861,11 +1924,10 @@ where
parsed.rest_text.trim().to_owned(),
))
} else if let Some(topic) = direct_song_shortcut_topic(
- message,
+ invocation,
parsed.is_addressed,
&first_word_lower,
&parsed.rest_text,
- &bot_username,
) {
Some((
"generate_song",
@@ -1875,20 +1937,11 @@ where
),
String::new(),
))
- } else if is_video_shortcut(message, &first_word_lower, &bot_username) {
- Some((
- openplotva_dialog::STEP_MAKE_VIDEO,
- format!(
- "Requested tool: make_video. Prompt: {}",
- parsed.rest_text.trim()
- ),
- parsed.rest_text.trim().to_owned(),
- ))
- } else if is_movie_shortcut(message, &first_word_lower, &bot_username) {
+ } else if let Some(tool) = invocation.and_then(|invocation| invocation.command.video_tool()) {
Some((
- openplotva_dialog::STEP_MAKE_MOVIE,
+ tool,
format!(
- "Requested tool: make_movie. Prompt: {}",
+ "Requested tool: {tool}. Prompt: {}",
parsed.rest_text.trim()
),
parsed.rest_text.trim().to_owned(),
@@ -1900,6 +1953,7 @@ where
&first_word_lower,
&parsed.rest_text,
editable,
+ invocation.is_some_and(|invocation| invocation.command == GenerationCommand::Draw),
)
.map(|action| match action {
DirectImageShortcut::Draw(prompt) => (
@@ -1925,6 +1979,8 @@ where
context.meta.draw_request = draw_request;
context.meta.annotation.push_str(&format!("\n{intent}"));
}
+ let admin_shortcut = invocation.is_some_and(|invocation| invocation.admin_shortcut);
+ context.meta.admin_command = admin_shortcut;
if !dialog_context_has_payload(&context) {
return Ok(DialogMessageUpdateRoute::SkippedEmptyDialogTrigger);
@@ -1956,7 +2012,11 @@ where
thread_id,
meta: &context.meta,
title: "dialog trigger",
- priority: HIGH_PRIORITY,
+ priority: if admin_shortcut {
+ ADMIN_COMMAND_PRIORITY
+ } else {
+ HIGH_PRIORITY
+ },
queue_name: &config.queue_name,
max_output_tokens,
processing_timeout_seconds: config.processing_timeout_seconds,
@@ -1978,23 +2038,15 @@ where
}
fn direct_song_shortcut_topic(
- message: &carapax::types::Message,
+ invocation: Option,
is_addressed: bool,
first_word_lower: &str,
rest_text: &str,
- bot_username: &str,
) -> Option {
- let word = first_word_lower.trim();
- if is_bang_song_shortcut(word) {
- return Some(rest_text.trim().to_owned());
- }
- if is_song_command_for_bot(message, word, bot_username) {
- return Some(rest_text.trim().to_owned());
- }
- if is_addressed && is_plain_song_alias(word) {
- return Some(rest_text.trim().to_owned());
- }
- None
+ let song_command =
+ invocation.is_some_and(|invocation| invocation.command == GenerationCommand::Song);
+ (song_command || (is_addressed && is_plain_song_alias(first_word_lower)))
+ .then(|| rest_text.trim().to_owned())
}
fn resolve_song_topic(message: &carapax::types::Message, raw_topic: &str) -> Option {
@@ -2040,25 +2092,6 @@ fn trimmed_non_empty(value: &str) -> Option {
(!trimmed.is_empty()).then(|| trimmed.to_owned())
}
-fn is_song_command_for_bot(
- message: &carapax::types::Message,
- first_word_lower: &str,
- bot_username: &str,
-) -> bool {
- let Some(command) = slash_command_parts(first_word_lower) else {
- return false;
- };
- if command.0 != "song" {
- return false;
- }
- if telegram_chat_is_private(&message.chat) {
- return true;
- }
- command
- .1
- .is_some_and(|target| target.eq_ignore_ascii_case(bot_username))
-}
-
fn is_search_command_for_bot(
message: &carapax::types::Message,
first_word_lower: &str,
@@ -2087,48 +2120,161 @@ fn slash_command_parts(word: &str) -> Option<(&str, Option<&str>)> {
Some((name, target))
}
-/// `/video` (with the bot's name in groups), `!video` or `!видео`.
-fn is_video_shortcut(
+/// A generation the user asks for by command or shortcut.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum GenerationCommand {
+ Draw,
+ Song,
+ /// A video: with sound for VIP users, a silent clip for everyone else.
+ Video,
+ Gif,
+}
+
+impl GenerationCommand {
+ /// The video tool the command requests; the scheduler still decides about sound.
+ const fn video_tool(self) -> Option<&'static str> {
+ match self {
+ Self::Video => Some(openplotva_dialog::STEP_MAKE_MOVIE),
+ Self::Gif => Some(openplotva_dialog::STEP_MAKE_VIDEO),
+ Self::Draw | Self::Song => None,
+ }
+ }
+
+ /// What to write after the command, with its leading punctuation, and an example subject.
+ const fn usage(self) -> (&'static str, &'static str) {
+ match self {
+ Self::Draw => (", что нарисовать", "рыжий кот в скафандре на Луне"),
+ Self::Song => (
+ " тему песни (песни доступны с VIP)",
+ "весёлый рок про кота, который ворует сосиски",
+ ),
+ Self::Video => (
+ ", что показать в видео (с VIP — со звуком, без VIP — гифка)",
+ "бабушка достаёт пирожки из печки и зовёт внука к столу",
+ ),
+ Self::Gif => (", что показать в гифке", "кот ловит снежинку"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+struct GenerationInvocation {
+ command: GenerationCommand,
+ /// A configured admin's `!` shortcut: its jobs jump every queue.
+ admin_shortcut: bool,
+}
+
+/// `/draw`, `/song`, `/video` and `/gif` work for everyone (in groups with the bot's name);
+/// the `!` shortcuts only for configured admins.
+fn generation_invocation(
message: &carapax::types::Message,
first_word_lower: &str,
bot_username: &str,
-) -> bool {
+ admin: bool,
+) -> Option {
let word = first_word_lower.trim();
- if matches!(word, "!video" | "!видео") {
- return true;
+ if admin && let Some(command) = bang_generation_command(word) {
+ return Some(GenerationInvocation {
+ command,
+ admin_shortcut: true,
+ });
}
- let Some((command, target)) = slash_command_parts(word) else {
- return false;
+ let (name, target) = slash_command_parts(word)?;
+ if !telegram_chat_is_private(&message.chat)
+ && !target.is_some_and(|target| target.eq_ignore_ascii_case(bot_username))
+ {
+ return None;
+ }
+ let command = match name {
+ "draw" => GenerationCommand::Draw,
+ "song" => GenerationCommand::Song,
+ "video" => GenerationCommand::Video,
+ "gif" => GenerationCommand::Gif,
+ _ => return None,
};
- command == "video"
- && (telegram_chat_is_private(&message.chat)
- || target.is_some_and(|target| target.eq_ignore_ascii_case(bot_username)))
+ Some(GenerationInvocation {
+ command,
+ admin_shortcut: false,
+ })
}
-/// `/movie` (with the bot's name in groups), `!movie` or `!кино`: a video with sound (VIP).
-fn is_movie_shortcut(
- message: &carapax::types::Message,
- first_word_lower: &str,
- bot_username: &str,
-) -> bool {
- let word = first_word_lower.trim();
- if matches!(word, "!movie" | "!кино") {
- return true;
+fn bang_generation_command(word: &str) -> Option {
+ match word {
+ "!рис" | "!draw" => Some(GenerationCommand::Draw),
+ "!песня" | "!song" => Some(GenerationCommand::Song),
+ "!видео" | "!video" | "!кино" | "!movie" => Some(GenerationCommand::Video),
+ "!гиф" | "!gif" => Some(GenerationCommand::Gif),
+ _ => None,
}
- let Some((command, target)) = slash_command_parts(word) else {
- return false;
+}
+
+/// A command with nothing to generate: no text after it, no reply and no attached media. In a
+/// forum topic every message replies to the topic's first message, which is not a subject.
+fn command_subject_missing(message: &carapax::types::Message, rest_text: &str) -> bool {
+ let replies = match &message.reply_to {
+ Some(TelegramReplyTo::Message(reply)) => message.message_thread_id != Some(reply.id),
+ Some(_) => true,
+ None => false,
};
- command == "movie"
- && (telegram_chat_is_private(&message.chat)
- || target.is_some_and(|target| target.eq_ignore_ascii_case(bot_username)))
+ rest_text.trim().is_empty()
+ && !replies
+ && openplotva_updates::collect_media_attachments(Some(message), &[]).is_empty()
}
-fn is_plain_song_alias(first_word: &str) -> bool {
- matches!(first_word.trim(), "song" | "песня")
+/// How long the usage hint for an empty command stays in the chat.
+const COMMAND_USAGE_HINT_TTL: Duration = Duration::from_secs(120);
+
+fn command_usage_hint_plan(
+ message: &carapax::types::Message,
+ chat_id: i64,
+ message_id: i32,
+ command: GenerationCommand,
+) -> CommandUsageHintPlan {
+ let typed = fetcher_message_text(message)
+ .split_whitespace()
+ .next()
+ .map(escape_telegram_html_text)
+ .unwrap_or_default();
+ let (subject, example) = command.usage();
+ let chat = ChatRef {
+ direct_messages_topic_id: message
+ .direct_messages_topic
+ .as_ref()
+ .map(|topic| topic.topic_id),
+ id: chat_id,
+ is_forum: message.message_thread_id.is_some(),
+ };
+ let message_thread_id = message.message_thread_id.unwrap_or_default();
+ CommandUsageHintPlan {
+ notice: DirectSongNoticePlan {
+ message: TextMessageRequest {
+ chat: Some(chat),
+ message_thread_id,
+ disable_notification: true,
+ allow_sending_without_reply: Some(true),
+ text: format!(
+ "Напишите после {typed}{subject}. Например:\n{typed} {example}"
+ ),
+ render_as: TELEGRAM_PARSE_MODE_HTML.to_owned(),
+ reply_markup: None,
+ },
+ reply_to: ReplyMessageRef {
+ message_id: i64::from(message_id),
+ chat,
+ is_topic_message: message.message_thread_id.is_some(),
+ message_thread_id,
+ },
+ delete_after: COMMAND_USAGE_HINT_TTL,
+ },
+ command_message: DeleteMessageRequest {
+ chat_id,
+ message_id: i64::from(message_id),
+ },
+ }
}
-fn is_bang_song_shortcut(first_word: &str) -> bool {
- matches!(first_word.trim(), "!song" | "!песня")
+fn is_plain_song_alias(first_word: &str) -> bool {
+ matches!(first_word.trim(), "song" | "песня")
}
fn telegram_chat_is_private(chat: &TelegramChat) -> bool {
@@ -2220,6 +2366,7 @@ fn direct_image_shortcut(
first_word_lower: &str,
rest_text: &str,
has_edit_target: bool,
+ draw_command: bool,
) -> Option {
let edit_text = if rest_text.trim().is_empty() {
first_word_lower.to_owned()
@@ -2229,7 +2376,7 @@ fn direct_image_shortcut(
if has_edit_target && let Some(prompt) = parse_edit_command(&edit_text) {
return Some(DirectImageShortcut::Edit(prompt));
}
- if is_bang_draw_shortcut(first_word_lower) {
+ if draw_command {
return Some(DirectImageShortcut::Draw(rest_text.trim().to_owned()));
}
is_addressed
@@ -2423,10 +2570,6 @@ where
.is_some_and(|settings| settings.disable_random_reactivity)
}
-fn is_bang_draw_shortcut(first_word: &str) -> bool {
- matches!(first_word.trim(), "!рис" | "!draw")
-}
-
fn dialog_context_has_payload(context: &openplotva_updates::FetcherMessageContext) -> bool {
!context.text.trim().is_empty()
|| !context.original_text.trim().is_empty()
@@ -6798,22 +6941,21 @@ mod tests {
-> Result<(), Box> {
for (text, tool, draw_request) in [
("!song neon rain", "generate_song", ""),
- ("!song", "generate_song", ""),
("/song@plotva_bot neon rain", "generate_song", ""),
("@plotva_bot песня про море", "generate_song", ""),
(
"!video кот ловит снежинку",
- "make_video",
+ "make_movie",
"кот ловит снежинку",
),
(
"!видео кот ловит снежинку",
- "make_video",
+ "make_movie",
"кот ловит снежинку",
),
(
"/video@plotva_bot кот ловит снежинку",
- "make_video",
+ "make_movie",
"кот ловит снежинку",
),
(
@@ -6822,11 +6964,17 @@ mod tests {
"бабушка зовёт внука есть пирожки",
),
(
- "/movie@plotva_bot dog barks at the mailman",
- "make_movie",
- "dog barks at the mailman",
+ "/gif@plotva_bot кот ловит снежинку",
+ "make_video",
+ "кот ловит снежинку",
+ ),
+ (
+ "!гиф кот ловит снежинку",
+ "make_video",
+ "кот ловит снежинку",
),
("!draw red fish", "draw_image", "red fish"),
+ ("/draw@plotva_bot red fish", "draw_image", "red fish"),
("@plotva_bot нарисуй рыбу", "draw_image", "рыбу"),
("@plotva_bot пожалуйста, нарисуй рыбу", "draw_image", "рыбу"),
("@plotva_bot можешь нарисовать рыбу", "draw_image", "рыбу"),
@@ -6865,6 +7013,188 @@ mod tests {
Ok(())
}
+ #[tokio::test]
+ async fn bang_shortcuts_are_only_for_admins_and_jump_the_queue()
+ -> Result<(), Box> {
+ let not_admin = DialogMessageUpdateConfig {
+ admin_ids: vec![1],
+ ..test_config()
+ };
+ for text in [
+ "!draw red fish",
+ "!рис рыба",
+ "!песня море",
+ "!видео кот",
+ "!кино кот",
+ ] {
+ let scheduler = SchedulerStub::default();
+ let route = handle_dialog_message_update_or_else(
+ &scheduler,
+ ¬_admin,
+ group_message_update(text)?,
+ |_| async { Ok::<(), std::io::Error>(()) },
+ )
+ .await?;
+ assert_eq!(route, DialogMessageUpdateRoute::Delegated, "{text}");
+ assert!(scheduler.calls().is_empty(), "{text}");
+ }
+
+ for (text, admin_shortcut) in [
+ ("!draw red fish", true),
+ ("!кино кот", true),
+ ("/draw@plotva_bot red fish", false),
+ ("/video@plotva_bot кот", false),
+ ] {
+ let scheduler = SchedulerStub::default();
+ handle_dialog_message_update_or_else(
+ &scheduler,
+ &test_config(),
+ group_message_update(text)?,
+ |_| async { Err::<(), std::io::Error>(std::io::Error::other("delegated")) },
+ )
+ .await?;
+ assert_eq!(scheduler.metas()[0].admin_command, admin_shortcut, "{text}");
+ assert_eq!(
+ scheduler.priorities(),
+ [if admin_shortcut {
+ ADMIN_COMMAND_PRIORITY
+ } else {
+ HIGH_PRIORITY
+ }],
+ "{text}"
+ );
+ }
+
+ let scheduler = SchedulerStub::default();
+ let route = handle_dialog_message_update_or_else(
+ &scheduler,
+ &test_config(),
+ group_message_update("/movie@plotva_bot кот")?,
+ |_| async { Ok::<(), std::io::Error>(()) },
+ )
+ .await?;
+ assert_eq!(route, DialogMessageUpdateRoute::Delegated, "/movie is gone");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn an_empty_generation_command_shows_how_to_use_it_instead_of_a_turn()
+ -> Result<(), Box> {
+ let settings = SettingsStoreStub::with_chat(random_chat_settings(0, false));
+ let rng = RngStub {
+ random_response: 99,
+ obscenifier: 1,
+ obscenify_variant: 0,
+ };
+ for (text, typed) in [
+ ("/video@plotva_bot", "/video@plotva_bot"),
+ ("/gif@plotva_bot", "/gif@plotva_bot"),
+ ("/draw@plotva_bot", "/draw@plotva_bot"),
+ ("/song@plotva_bot ", "/song@plotva_bot"),
+ ("!кино", "!кино"),
+ ] {
+ let scheduler = SchedulerStub::default();
+ let effects = EffectsStub::default();
+ let route = handle_dialog_or_random_message_update_or_else(
+ &scheduler,
+ &settings,
+ &effects,
+ &rng,
+ &test_config(),
+ group_message_update(text)?,
+ |_| async { Err::<(), std::io::Error>(std::io::Error::other("delegated")) },
+ )
+ .await?;
+ assert_eq!(route, DialogMessageUpdateRoute::CommandUsageHint, "{text}");
+ assert!(scheduler.calls().is_empty(), "{text}");
+ let hints = effects.sent_usage_hints();
+ assert_eq!(hints.len(), 1, "{text}");
+ let hint = &hints[0];
+ assert!(
+ hint.notice
+ .message
+ .text
+ .starts_with(&format!("Напишите после {typed}")),
+ "{text}: {}",
+ hint.notice.message.text
+ );
+ assert!(
+ hint.notice
+ .message
+ .text
+ .contains(&format!("{typed} "))
+ );
+ assert_eq!(hint.notice.delete_after, COMMAND_USAGE_HINT_TTL);
+ assert_eq!(hint.notice.message.allow_sending_without_reply, Some(true));
+ assert_eq!(
+ (
+ hint.command_message.chat_id,
+ hint.command_message.message_id
+ ),
+ (-100, 78),
+ "{text}"
+ );
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn a_reply_or_media_gives_an_empty_command_its_subject()
+ -> Result<(), Box> {
+ let message =
+ |extra: serde_json::Value| -> Result {
+ let mut value = json!({
+ "message_id": 77,
+ "date": 1_710_000_000,
+ "chat": {"id": 42, "type": "private", "first_name": "Ada"},
+ "from": {"id": 99, "is_bot": false, "first_name": "Ada"},
+ });
+ value
+ .as_object_mut()
+ .expect("message object")
+ .extend(extra.as_object().expect("extra object").clone());
+ serde_json::from_value(value)
+ };
+ assert!(command_subject_missing(
+ &message(json!({"text": "/video"}))?,
+ ""
+ ));
+ assert!(!command_subject_missing(
+ &message(json!({"text": "/video"}))?,
+ "кот"
+ ));
+ let reply = message(json!({
+ "text": "/video",
+ "reply_to_message": {
+ "message_id": 70,
+ "date": 1_709_999_000,
+ "chat": {"id": 42, "type": "private", "first_name": "Ada"},
+ "text": "кот на крыше"
+ }
+ }))?;
+ assert!(!command_subject_missing(&reply, ""));
+ let topic_root = message(json!({
+ "text": "/video",
+ "message_thread_id": 70,
+ "reply_to_message": {
+ "message_id": 70,
+ "date": 1_709_999_000,
+ "chat": {"id": 42, "type": "private", "first_name": "Ada"},
+ "text": "Видео"
+ }
+ }))?;
+ assert!(
+ command_subject_missing(&topic_root, ""),
+ "the topic's first message is not a subject"
+ );
+ let photo = message(json!({
+ "caption": "/video",
+ "photo": [{"file_id": "f", "file_unique_id": "u", "width": 64, "height": 64}]
+ }))?;
+ assert!(!command_subject_missing(&photo, ""));
+ Ok(())
+ }
+
#[tokio::test]
async fn draw_api_shortcut_is_only_for_admins() -> Result<(), Box> {
let scheduler = SchedulerStub::default();
@@ -6917,6 +7247,7 @@ mod tests {
struct SchedulerStub {
calls: Mutex>,
metas: Mutex>,
+ priorities: Mutex>,
}
impl SchedulerStub {
@@ -6927,6 +7258,10 @@ mod tests {
fn metas(&self) -> Vec {
lock(&self.metas).clone()
}
+
+ fn priorities(&self) -> Vec {
+ lock(&self.priorities).clone()
+ }
}
impl DialogMessageScheduler for SchedulerStub {
@@ -6939,6 +7274,7 @@ mod tests {
Box::pin(async move {
lock(&self.calls).push(schedule.message_text.to_owned());
lock(&self.metas).push(schedule.meta.clone());
+ lock(&self.priorities).push(schedule.priority);
Ok(DialogMessageScheduleReport {
queue_name: schedule.queue_name.to_owned(),
delay: Duration::ZERO,
@@ -7636,6 +7972,7 @@ mod tests {
texts: Mutex>,
song_notices: Mutex>,
draw_failures: Mutex>,
+ usage_hints: Mutex>,
}
impl EffectsStub {
@@ -7643,6 +7980,10 @@ mod tests {
lock(&self.texts).clone()
}
+ fn sent_usage_hints(&self) -> Vec {
+ lock(&self.usage_hints).clone()
+ }
+
fn sent_song_notices(&self) -> Vec {
lock(&self.song_notices).clone()
}
@@ -7682,6 +8023,16 @@ mod tests {
Ok(())
})
}
+
+ fn send_command_usage_hint<'a>(
+ &'a self,
+ plan: CommandUsageHintPlan,
+ ) -> DirectSongNoticeFuture<'a> {
+ Box::pin(async move {
+ lock(&self.usage_hints).push(plan);
+ Ok(())
+ })
+ }
}
#[derive(Clone)]
diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs
index bc096d0..df0bde7 100644
--- a/crates/openplotva-app/src/dialog_tools.rs
+++ b/crates/openplotva-app/src/dialog_tools.rs
@@ -21,12 +21,13 @@ use openplotva_dialog::{
verbatim_draw_caption, verbatim_video_caption,
};
use openplotva_history::{StoredSummary, SummaryContent};
+use openplotva_media::video::VideoOrientation;
use openplotva_taskman::{
- DEFAULT_PRIORITY, HIGHEST_PRIORITY, IMAGE_REGULAR_QUEUE_NAME, IMAGE_VIP_PRIORITY,
- IMAGE_VIP_QUEUE_NAME, ImageEditJobParams, ImageGenJobParams, InMemoryTaskQueue,
- MUSIC_VIP_QUEUE_NAME, MusicGenJobParams, 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,
+ 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,
+ 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,
};
use serde_json::json;
use time::{OffsetDateTime, UtcOffset, format_description::well_known::Rfc3339};
@@ -724,6 +725,8 @@ pub struct DrawImageScheduleRequest {
pub seed: String,
/// Readable caption; stored independently from the technical generation prompt.
pub original_prompt: String,
+ /// Asked with an admin shortcut: the job jumps every queue.
+ pub admin_command: bool,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
@@ -928,10 +931,14 @@ pub struct VideoScheduleRequest {
pub caption: String,
/// The user's message that asked for the clip.
pub message_text: String,
- /// A video with sound (VIP only) instead of a silent clip.
- pub sound: bool,
- /// Sampling steps of a video with sound (4 for "high" quality); 0 keeps the farm's default.
+ /// Sampling steps if the clip becomes a video with sound (4 for "high" quality); 0 keeps
+ /// the farm's default.
pub steps: u8,
+ /// Frame of a video with sound: "portrait", "landscape" or empty to let the optimizer
+ /// infer it.
+ pub orientation: String,
+ /// Asked with an admin shortcut: the job jumps every queue.
+ pub admin_command: bool,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
@@ -954,15 +961,12 @@ pub enum VideoScheduleRejection {
GenerationRateLimited,
/// Enqueue throttled by the task-enqueue rate limit.
RateLimited,
- /// A video with sound was requested by a user without VIP.
- VipOnly,
}
impl VideoScheduleRejection {
#[must_use]
pub const fn reason_code(self) -> &'static str {
match self {
- Self::VipOnly => "vip_only",
Self::VideoNotAllowed => "video_not_allowed",
Self::ActiveLimit => "active_job_limit",
Self::GenerationRateLimited => "generation_rate_limited",
@@ -985,13 +989,32 @@ impl VideoScheduleRejection {
Self::RateLimited => {
"Слишком много запросов подряд, сработал лимит очереди. Задача не поставлена в очередь."
}
- Self::VipOnly => {
- "Видео со звуком доступно только VIP-пользователям, у пользователя нет VIP-подписки. Видео не поставлено в очередь. Можно предложить беззвучный ролик (make_video)."
- }
}
}
}
+/// A VIP gets a video with sound unless the message asks for a GIF or a clip without sound;
+/// everyone else gets a silent clip. The bot decides, whichever video tool the model called.
+fn video_with_sound(has_vip: bool, message_text: &str) -> bool {
+ has_vip && !asks_for_silent_clip(message_text)
+}
+
+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| {
+ (word.starts_with("gif") && !word.starts_with("gift"))
+ || word.starts_with("гиф")
+ || word.starts_with("гіф")
+ || word.starts_with("беззвуч")
+ || word == "silent"
+ || word == "muted"
+ });
+ gif_word
+ || ["без звука", "no sound", "without sound"]
+ .iter()
+ .any(|phrase| text.contains(phrase))
+}
+
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SongQueueNotice {
pub position: usize,
@@ -1408,7 +1431,7 @@ impl ImageScheduler for TaskmanDialogToolAdapter {
Some(vip_status) => vip_status.is_draw_image_vip(request.user_id).await,
None => false,
};
- let plan = image_gen_queue_plan(has_vip && !request.agent_gift);
+ let plan = image_gen_queue_plan(has_vip && !request.agent_gift, request.admin_command);
if self
.queue
.user_active_count(plan.queue_name, request.user_id)
@@ -1563,6 +1586,7 @@ impl SongScheduler for TaskmanDialogToolAdapter {
let reference_file_unique_id =
song_reference_unique_id(&request.reference_file_unique_id, &request.message_meta);
let is_gift = request.message_meta.agent_gift;
+ let admin_command = request.message_meta.admin_command;
let mut meta = serde_json::to_value(request.message_meta).unwrap_or_else(|_| json!({}));
crate::music_jobs::SongJobMeta {
request_text: request.message_text.trim().to_owned(),
@@ -1598,7 +1622,9 @@ impl SongScheduler for TaskmanDialogToolAdapter {
.with_name("music")
.with_priority(HIGHEST_PRIORITY);
- if is_gift {
+ if admin_command {
+ job.priority = ADMIN_COMMAND_PRIORITY;
+ } else if is_gift {
job.priority = openplotva_taskman::DEFAULT_PRIORITY;
}
if self
@@ -1654,10 +1680,8 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
Some(vip_status) => vip_status.is_draw_image_vip(request.user_id).await,
None => false,
};
- if request.sound && !has_vip {
- return Ok(not_scheduled_video(VideoScheduleRejection::VipOnly));
- }
- let plan = image_gen_queue_plan(has_vip);
+ let sound = video_with_sound(has_vip, &request.message_text);
+ let plan = image_gen_queue_plan(has_vip, request.admin_command);
if self
.queue
.user_active_count(plan.queue_name, request.user_id)
@@ -1701,12 +1725,17 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
request_text: request.message_text.trim().to_owned(),
brief: request.brief,
caption: request.caption,
- sound: request.sound,
- steps: request.steps,
+ sound,
+ steps: if sound { request.steps } else { 0 },
+ orientation: if sound {
+ request.orientation
+ } else {
+ String::new()
+ },
},
OffsetDateTime::now_utc(),
)
- .with_name(if request.sound { "movie" } else { "video" })
+ .with_name(if sound { "movie" } else { "video" })
.with_priority(plan.priority);
let queue_position = self.image_queue_position(plan);
match self.assign_image_job(plan.queue_name, job, plan.max_active_jobs) {
@@ -1812,7 +1841,7 @@ impl TaskmanDialogToolAdapter {
return Ok(not_scheduled_draw(DrawImageScheduleRejection::VipOnly));
}
- let plan = image_gen_queue_plan(true);
+ let plan = image_gen_queue_plan(true, request.admin_command);
let prompt = request.prompt.trim().to_owned();
let chat_id = request.chat_id;
let user_id = request.user_id;
@@ -2037,7 +2066,15 @@ struct ImageGenQueuePlan {
max_active_jobs: usize,
}
-fn image_gen_queue_plan(has_vip: bool) -> ImageGenQueuePlan {
+/// An admin shortcut runs in the VIP queue ahead of every other job.
+fn image_gen_queue_plan(has_vip: bool, admin_command: bool) -> ImageGenQueuePlan {
+ if admin_command {
+ return ImageGenQueuePlan {
+ queue_name: IMAGE_VIP_QUEUE_NAME,
+ priority: ADMIN_COMMAND_PRIORITY,
+ max_active_jobs: 10,
+ };
+ }
if has_vip {
return ImageGenQueuePlan {
queue_name: IMAGE_VIP_QUEUE_NAME,
@@ -2264,7 +2301,7 @@ fn draw_rate_limit_response_text(limit_msg: &str, has_vip: bool) -> String {
return limit_msg.trim().to_owned();
}
format!(
- "{}\n\nПриобретите VIP-подписку c помощью /vip и получите:\n⚡ Приоритетное выполнение запросов вне очереди\n🔄 Вдвое увеличенные лимиты на рисование\n🖼️ Изображения лучшего качества с меньшей цензурой\n🎵 Генерацию песен по команде /song\n🚀 Доступ к новым функциям и фичам (в разработке)",
+ "{}\n\nПриобретите VIP-подписку c помощью /vip и получите:\n⚡ Приоритетное выполнение запросов вне очереди\n🔄 Вдвое увеличенные лимиты на рисование\n🖼️ Изображения лучшего качества с меньшей цензурой\n🎵 Генерацию песен по команде /song\n🎬 Видео со звуком по команде /video\n🚀 Доступ к новым функциям и фичам (в разработке)",
limit_msg.trim()
)
}
@@ -2586,14 +2623,13 @@ impl
self
}
- /// `make_video` (a silent clip) and `make_movie` (a video with sound, VIP only) share the
- /// clip scheduler; the refusal codes name the tool the model called.
+ /// `make_video` and `make_movie` share the clip scheduler, which decides between a video
+ /// with sound and a silent clip; the refusal codes name the tool the model called.
async fn schedule_dialog_video(
&self,
req: VideoRequest,
- sound: bool,
+ tool: &'static str,
) -> Result {
- let tool = if sound { "make_movie" } else { "make_video" };
let Some(scheduler) = self.video_scheduler.as_deref() else {
return Ok(ToolResult::failed(
format!("{tool}_unavailable"),
@@ -2610,8 +2646,12 @@ impl
caption: verbatim_video_caption(&req.context.message_meta)
.unwrap_or_else(|| sanitize_tool_text(&req.caption)),
message_text: req.context.message_text,
- sound,
- steps: if sound && req.quality == "high" { 4 } else { 0 },
+ steps: if req.quality == "high" { 4 } else { 0 },
+ orientation: VideoOrientation::parse(&req.orientation)
+ .map(VideoOrientation::as_str)
+ .unwrap_or_default()
+ .to_owned(),
+ admin_command: req.context.message_meta.admin_command,
};
match scheduler.schedule_video(request).await {
Ok(result) => Ok(dialog_make_video_tool_result(&result, tool)),
@@ -2829,6 +2869,7 @@ where
aspect_ratio: sanitize_tool_text(&req.aspect_ratio),
seed: sanitize_tool_text(&req.seed),
original_prompt: sanitize_tool_text(&req.caption),
+ admin_command: req.context.message_meta.admin_command,
};
if let Some(caption) = verbatim_draw_caption(&req.context.message_meta)
&& (!request_has_image_attachment(&request) || request.original_prompt.is_empty())
@@ -2894,11 +2935,11 @@ where
}
fn make_video<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
- Box::pin(self.schedule_dialog_video(req, false))
+ Box::pin(self.schedule_dialog_video(req, openplotva_dialog::STEP_MAKE_VIDEO))
}
fn make_movie<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
- Box::pin(self.schedule_dialog_video(req, true))
+ Box::pin(self.schedule_dialog_video(req, openplotva_dialog::STEP_MAKE_MOVIE))
}
fn understand_media<'a>(&'a self, req: VisionRequest) -> ToolboxFuture<'a> {
@@ -4800,6 +4841,7 @@ mod tests {
aspect_ratio: "16:9".to_owned(),
seed: "42".to_owned(),
original_prompt: "Объединённые картинки".to_owned(),
+ admin_command: false,
}]
);
Ok(())
@@ -5429,11 +5471,19 @@ mod tests {
brief: "A grey cat catches a snowflake".to_owned(),
caption: "Кот и снежинка".to_owned(),
message_text: " !видео кот ловит снежинку ".to_owned(),
- sound: false,
steps: 0,
+ orientation: String::new(),
+ admin_command: false,
}
}
+ fn scheduled_video_params(queue: &InMemoryTaskQueue) -> VideoGenJobParams {
+ let records = queue.records();
+ assert_eq!(records.len(), 1);
+ openplotva_taskman::video_gen_job_params_from_payload(&records[0].job.data)
+ .expect("video job params")
+ }
+
fn queued_drawing(user_id: i64, message_id: i32) -> openplotva_taskman::StatelessJobItem {
new_image_gen_job_at(
ImageGenJobParams {
@@ -5482,6 +5532,7 @@ mod tests {
caption: "Кот и снежинка".to_owned(),
sound: false,
steps: 0,
+ orientation: String::new(),
})
);
assert_eq!(
@@ -5594,61 +5645,211 @@ mod tests {
Ok(())
}
- #[tokio::test]
- async fn taskman_dialog_tool_adapter_queues_vip_videos_with_sound() -> Result<(), ToolboxError>
- {
+ async fn schedule_video_as(
+ vip: bool,
+ request: VideoScheduleRequest,
+ ) -> Result<(Arc, VideoScheduleResult), ToolboxError> {
let queue = Arc::new(InMemoryTaskQueue::new());
let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue))
.with_video_permission(Arc::new(VideoPermissionStub(true)))
- .with_draw_image_vip_status(Arc::new(DrawImageVipStatusStub::new(true)));
+ .with_draw_image_vip_status(Arc::new(DrawImageVipStatusStub::new(vip)));
+ let result = adapter.schedule_video(request).await?;
+ Ok((queue, result))
+ }
- let scheduled = adapter
- .schedule_video(VideoScheduleRequest {
- sound: true,
- steps: 4,
- ..video_request(11)
- })
+ #[tokio::test]
+ async fn vip_video_requests_become_videos_with_sound_with_their_steps_and_frame()
+ -> Result<(), ToolboxError> {
+ for text in [
+ "!видео кот ловит снежинку",
+ "Плотва, сделай анимацию: кот ловит снежинку",
+ "/video котик для тиктока",
+ "сделай видео-подарок маме, a gift for mom",
+ ] {
+ let (queue, scheduled) = schedule_video_as(
+ true,
+ VideoScheduleRequest {
+ message_text: text.to_owned(),
+ steps: 4,
+ orientation: "portrait".to_owned(),
+ ..video_request(11)
+ },
+ )
+ .await?;
+ assert_eq!(scheduled.status, "scheduled", "{text}");
+ let records = queue.records();
+ assert_eq!(records[0].queue_name, IMAGE_VIP_QUEUE_NAME);
+ assert_eq!(records[0].job.title, "movie");
+ let params = scheduled_video_params(&queue);
+ assert!(params.sound, "{text}");
+ assert_eq!(params.steps, 4);
+ assert_eq!(params.orientation, "portrait");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn a_vip_who_asks_for_a_gif_or_no_sound_gets_a_silent_clip() -> Result<(), ToolboxError> {
+ for text in [
+ "/gif кот ловит снежинку",
+ "Плотва, сделай гифку с котом",
+ "видео без звука: кот ловит снежинку",
+ "make a silent clip of a cat",
+ "беззвучный ролик с котом",
+ "make a GIF of a cat",
+ ] {
+ let (queue, scheduled) = schedule_video_as(
+ true,
+ VideoScheduleRequest {
+ message_text: text.to_owned(),
+ steps: 4,
+ orientation: "portrait".to_owned(),
+ ..video_request(11)
+ },
+ )
.await?;
+ assert_eq!(scheduled.status, "scheduled", "{text}");
+ assert_eq!(queue.records()[0].job.title, "video");
+ let params = scheduled_video_params(&queue);
+ assert!(!params.sound, "{text}");
+ assert_eq!(params.steps, 0, "steps apply only to a video with sound");
+ assert_eq!(params.orientation, "", "FastFrames renders landscape only");
+ }
+ Ok(())
+ }
+ #[tokio::test]
+ async fn users_without_vip_get_a_silent_clip_for_any_video_request() -> Result<(), ToolboxError>
+ {
+ for text in [
+ "/video кот",
+ "сгенерируй видео со звуком: кот поёт",
+ "!кино кот",
+ ] {
+ let (queue, scheduled) = schedule_video_as(
+ false,
+ VideoScheduleRequest {
+ message_text: text.to_owned(),
+ steps: 4,
+ orientation: "portrait".to_owned(),
+ ..video_request(11)
+ },
+ )
+ .await?;
+ assert_eq!(scheduled.status, "scheduled", "{text}");
+ assert_eq!(scheduled.rejection, None);
+ assert_eq!(queue.records()[0].queue_name, IMAGE_REGULAR_QUEUE_NAME);
+ let params = scheduled_video_params(&queue);
+ assert!(!params.sound, "{text}");
+ assert_eq!((params.steps, params.orientation.as_str()), (0, ""));
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn an_admin_shortcut_puts_every_generation_ahead_of_all_queues()
+ -> Result<(), ToolboxError> {
+ let (queue, scheduled) = schedule_video_as(
+ false,
+ VideoScheduleRequest {
+ admin_command: true,
+ ..video_request(11)
+ },
+ )
+ .await?;
assert_eq!(scheduled.status, "scheduled");
let records = queue.records();
assert_eq!(records[0].queue_name, IMAGE_VIP_QUEUE_NAME);
- let params = openplotva_taskman::video_gen_job_params_from_payload(&records[0].job.data)
- .map_err(|error| Box::new(error) as ToolboxError)?;
- assert!(params.sound);
- assert_eq!(params.steps, 4);
+ assert_eq!(records[0].job.priority, ADMIN_COMMAND_PRIORITY);
+ assert_eq!(
+ image_gen_queue_plan(true, true).priority,
+ ADMIN_COMMAND_PRIORITY
+ );
+ assert_eq!(
+ image_gen_queue_plan(true, false).priority,
+ IMAGE_VIP_PRIORITY
+ );
+ assert_eq!(
+ image_gen_queue_plan(false, false).priority,
+ DEFAULT_PRIORITY
+ );
Ok(())
}
- #[tokio::test]
- async fn taskman_dialog_tool_adapter_refuses_videos_with_sound_without_vip()
- -> Result<(), ToolboxError> {
- let queue = Arc::new(InMemoryTaskQueue::new());
- let adapter = TaskmanDialogToolAdapter::new(Arc::clone(&queue))
- .with_video_permission(Arc::new(VideoPermissionStub(true)))
- .with_draw_image_vip_status(Arc::new(DrawImageVipStatusStub::new(false)));
+ #[derive(Default)]
+ struct VideoSchedulerRecorder(Mutex>);
- let refused = adapter
- .schedule_video(VideoScheduleRequest {
- sound: true,
- ..video_request(11)
+ impl VideoScheduler for VideoSchedulerRecorder {
+ fn schedule_video<'a>(&'a self, request: VideoScheduleRequest) -> ScheduleVideoFuture<'a> {
+ self.0.lock().expect("videos").push(request);
+ Box::pin(async {
+ Ok(VideoScheduleResult {
+ status: "scheduled".to_owned(),
+ job_id: Some(1),
+ ..VideoScheduleResult::default()
+ })
})
- .await?;
+ }
+ }
- assert_eq!(refused.rejection, Some(VideoScheduleRejection::VipOnly));
- assert!(queue.records().is_empty());
- let result = dialog_make_video_tool_result(&refused, "make_movie");
- assert_eq!(result.status, TOOL_RESULT_STATUS_FAILED);
+ #[tokio::test]
+ async fn both_video_tools_hand_quality_frame_and_admin_flag_to_the_scheduler()
+ -> Result<(), ToolboxError> {
+ let scheduler = Arc::new(VideoSchedulerRecorder::default());
+ let toolbox = toolbox(None).with_video_scheduler(scheduler.clone());
+ let request = |quality: &str, orientation: &str| VideoRequest {
+ context: ToolContext {
+ message_meta: ChatMessageMeta {
+ admin_command: true,
+ ..ChatMessageMeta::default()
+ },
+ ..context()
+ },
+ prompt: "A cat dances".to_owned(),
+ caption: "Кот танцует".to_owned(),
+ quality: quality.to_owned(),
+ orientation: orientation.to_owned(),
+ };
+ toolbox.make_video(request("high", "portrait")).await?;
+ toolbox.make_movie(request("", "square")).await?;
+ let recorded = scheduler.0.lock().expect("videos");
assert_eq!(
- result
- .data
- .as_ref()
- .and_then(|data| data["reason"].as_str()),
- Some("vip_only")
+ recorded
+ .iter()
+ .map(|request| (
+ request.steps,
+ request.orientation.as_str(),
+ request.admin_command
+ ))
+ .collect::>(),
+ [(4, "portrait", true), (0, "", true)]
);
Ok(())
}
+ #[test]
+ fn silent_clip_wording_is_recognized_in_any_case_and_language() {
+ for text in [
+ "GIF с котом",
+ "гифон",
+ "гіфку",
+ "без звука",
+ "Without sound",
+ "/gif@plotva_bot кот",
+ ] {
+ assert!(asks_for_silent_clip(text), "{text}");
+ }
+ for text in [
+ "видео с котом",
+ "a gift video",
+ "анимация",
+ "giraffe",
+ "звук погромче",
+ ] {
+ assert!(!asks_for_silent_clip(text), "{text}");
+ }
+ }
+
#[test]
fn app_dialog_toolbox_offers_make_video_only_with_a_scheduler() {
let without = toolbox(None);
@@ -6756,7 +6957,7 @@ mod tests {
);
assert_eq!(
blocked.message,
- "Вы часто повторяете этот запрос. Попробуйте снова через 1 мин.\n\nПриобретите VIP-подписку c помощью /vip и получите:\n⚡ Приоритетное выполнение запросов вне очереди\n🔄 Вдвое увеличенные лимиты на рисование\n🖼️ Изображения лучшего качества с меньшей цензурой\n🎵 Генерацию песен по команде /song\n🚀 Доступ к новым функциям и фичам (в разработке)"
+ "Вы часто повторяете этот запрос. Попробуйте снова через 1 мин.\n\nПриобретите VIP-подписку c помощью /vip и получите:\n⚡ Приоритетное выполнение запросов вне очереди\n🔄 Вдвое увеличенные лимиты на рисование\n🖼️ Изображения лучшего качества с меньшей цензурой\n🎵 Генерацию песен по команде /song\n🎬 Видео со звуком по команде /video\n🚀 Доступ к новым функциям и фичам (в разработке)"
);
assert_eq!(rate_limit.checks(), vec![("castle".to_owned(), 42, false)]);
assert!(rate_limit.grows().is_empty());
diff --git a/crates/openplotva-app/src/help.rs b/crates/openplotva-app/src/help.rs
index 2e65449..2a4a847 100644
--- a/crates/openplotva-app/src/help.rs
+++ b/crates/openplotva-app/src/help.rs
@@ -30,7 +30,7 @@ const FALLBACK_BOT_NAME: &str = "бот";
pub const HELP_INTRO_MESSAGE_TEMPLATE: &str = r#"Привет! Я {{.BotName}}
-Я тут для общения, рисования и полезных задач.
+Я тут для общения, рисования, видео и полезных задач.
Хочешь познакомиться с возможностями? Нажми кнопку ниже.
"#;
@@ -39,7 +39,7 @@ pub const HELP_REDIRECT_MESSAGE: &str =
pub const HELP_MESSAGE_TEMPLATE: &str = r#"Привет! Я {{.BotName}}
-Я тут для общения, рисунков и полезных задач. Я стараюсь быть живой и понятной.
+Я тут для общения, рисунков, видео и полезных задач. Я стараюсь быть живой и понятной.
Как со мной общаться
@@ -51,7 +51,7 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"Привет! Я {{.BotName}} Рисование и правки
-Я могу рисовать по твоим запросам: {{.BotName}}, нарисуй кота в космосе
+Я могу рисовать по твоим запросам: {{.BotName}}, нарисуй кота в космосе или /draw кот в космосе
Правки: ответь на картинку или пришли новую и напиши, что изменить.
@@ -59,6 +59,12 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"Привет! Я {{.BotName}} Ограничения: примерно 5/10/20 картинок на пользователя в течение окна в 10/15/30 минут.
+Видео и гифки
+
+Гифка: /gif кот ловит снежинку или «{{.BotName}}, сделай гифку…».
+
+Видео: /video бабушка достаёт пирожки из печки или «{{.BotName}}, сгенерируй видео…». С VIP видео идёт со звуком: речь, шумы и музыка, а реплики в кавычках звучат дословно. Можно попросить вертикальное видео (для сторис, Reels, TikTok) и высокое качество — это дольше. Без VIP вместо видео будет гифка.
+
Полезности
Ищу в интернете, читаю ссылки, кратко пересказываю YouTube, перевожу тексты и показываю курсы валют.
@@ -77,7 +83,7 @@ pub const HELP_MESSAGE_TEMPLATE: &str = r#"Привет! Я {{.BotName}} VIP
-Если хочется быстрее и больше: приоритетная VIP очередь, в 2 раза больше генераций, лучшее качество и генерация песен по команде /song.
+Если хочется быстрее и больше: приоритетная VIP очередь, в 2 раза больше генераций, лучшее качество, видео со звуком по команде /video и генерация песен по команде /song.
Оформить можно через /vip.
diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs
index c7f8014..60cdb33 100644
--- a/crates/openplotva-app/src/image_jobs.rs
+++ b/crates/openplotva-app/src/image_jobs.rs
@@ -92,7 +92,12 @@ pub const AIFARM_DRAW_API_DEFAULT_POLL_INTERVAL: StdDuration = StdDuration::from
pub const AIFARM_DRAW_API_DEFAULT_CAPACITY_WAIT: StdDuration = StdDuration::from_secs(4 * 60);
/// Local slack over `capacity_wait` for the held submit round-trip itself.
const AIFARM_DRAW_API_SUBMIT_MARGIN: StdDuration = StdDuration::from_secs(30);
-const AIFARM_DRAW_API_POLL_TIMEOUT: StdDuration = StdDuration::from_secs(30);
+/// One status poll, body included. A finished job carries its result (an MP4 is several MB of
+/// base64), and the farm link can drop to 180 KB/s, so the bound covers the download.
+const AIFARM_DRAW_API_POLL_TIMEOUT: StdDuration = StdDuration::from_secs(90);
+/// Error text of a finished job whose result was lost: Discovery deletes a terminal job once
+/// it has been read, so a status read that failed while downloading the result leaves a 404.
+pub const DRAW_API_RESULT_LOST: &str = "draw-api result lost";
const AIFARM_DRAW_API_MAX_POLL_RETRY_DELAY: StdDuration = StdDuration::from_secs(10);
/// Bound for one Telegram call made by a media generation worker. The worker
/// holds the accelerator slot while it waits, and the shared HTTP timeout is
@@ -773,12 +778,23 @@ pub struct DrawApiVideo {
pub fps: i64,
}
+/// Options of a MiniMax-H3 render; `None` keeps the farm's default (2 steps, 480p landscape).
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
+pub struct DrawApiVideoOptions {
+ /// Sampling steps: 2 or 4.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub steps: Option,
+ /// "landscape" or "portrait".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub orientation: Option<&'static str>,
+}
+
#[derive(Serialize)]
struct DrawApiVideoRequest<'a> {
prompt: &'a str,
format: &'a str,
- #[serde(skip_serializing_if = "Option::is_none")]
- steps: Option,
+ #[serde(flatten)]
+ options: DrawApiVideoOptions,
}
/// AIFarm draw-api image generator.
@@ -934,13 +950,13 @@ where
})
}
- /// Generate one MP4 clip from an English video prompt.
- /// Render one clip on a draw-api video `endpoint`: FastFrames (silent) or MiniMax-H3 (sound).
+ /// Render one MP4 clip on a draw-api video `endpoint`: FastFrames (silent) or MiniMax-H3
+ /// (sound, with its `options`).
pub async fn generate_video_with_job_id(
&self,
endpoint: &str,
prompt: &str,
- steps: Option,
+ options: DrawApiVideoOptions,
job_id: &str,
) -> Result {
let prompt = prompt.trim();
@@ -952,7 +968,7 @@ where
let payload = serde_json::to_vec(&DrawApiVideoRequest {
prompt,
format: "mp4",
- steps,
+ options,
})
.map_err(|err| ImageGenerationError::Provider(err.to_string()))?;
let job_id = self
@@ -1087,6 +1103,15 @@ where
}
self.cfg.poll_interval
}
+ Err(DrawApiPollError::NotFound(error)) => {
+ return Err(if poll_failures > 0 {
+ ImageGenerationError::Provider(format!(
+ "{DRAW_API_RESULT_LOST}: job {job_id} is gone after a failed status read"
+ ))
+ } else {
+ error
+ });
+ }
Err(DrawApiPollError::Terminal(error)) => return Err(error),
Err(DrawApiPollError::Retryable(error)) => {
if Instant::now() >= deadline {
@@ -1146,10 +1171,10 @@ where
response.status_code,
String::from_utf8_lossy(&response.body).trim()
));
- return Err(if matches!(response.status_code, 408 | 429 | 500..=599) {
- DrawApiPollError::Retryable(error)
- } else {
- DrawApiPollError::Terminal(error)
+ return Err(match response.status_code {
+ 408 | 429 | 500..=599 => DrawApiPollError::Retryable(error),
+ 404 => DrawApiPollError::NotFound(error),
+ _ => DrawApiPollError::Terminal(error),
});
}
let envelope =
@@ -1179,6 +1204,8 @@ where
enum DrawApiPollError {
Retryable(ImageGenerationError),
+ /// The job is gone; after a failed read it means its result was lost.
+ NotFound(ImageGenerationError),
Terminal(ImageGenerationError),
}
@@ -8824,7 +8851,7 @@ mod tests {
.generate_video_with_job_id(
AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME,
" A grey cat catches a snowflake. ",
- None,
+ DrawApiVideoOptions::default(),
"video-77",
)
.await
@@ -8887,7 +8914,10 @@ mod tests {
.generate_video_with_job_id(
AIFARM_DRAW_API_H3VIDEO_ENDPOINT_NAME,
"rain",
- Some(4),
+ DrawApiVideoOptions {
+ steps: Some(4),
+ orientation: None,
+ },
"video-78"
)
.await,
@@ -8970,10 +9000,14 @@ mod tests {
let probe = transport.clone();
let generator = fastframes_generator(transport);
- let video =
- crate::video_jobs::VideoGenerator::generate_video(&generator, "rain", 77, false, 0)
- .await
- .expect("the second submission renders the clip");
+ let video = crate::video_jobs::VideoGenerator::generate_video(
+ &generator,
+ "rain",
+ 77,
+ crate::video_jobs::VideoRender::default(),
+ )
+ .await
+ .expect("the second submission renders the clip");
assert_eq!(video.bytes, clip.to_vec());
assert_eq!(
@@ -8997,10 +9031,18 @@ mod tests {
let probe = transport.clone();
let generator = fastframes_generator(transport);
- let error =
- crate::video_jobs::VideoGenerator::generate_video(&generator, "rain", 78, true, 4)
- .await
- .expect_err("a bad request fails the clip");
+ let error = crate::video_jobs::VideoGenerator::generate_video(
+ &generator,
+ "rain",
+ 78,
+ crate::video_jobs::VideoRender {
+ sound: true,
+ steps: 4,
+ orientation: openplotva_media::video::VideoOrientation::Portrait,
+ },
+ )
+ .await
+ .expect_err("a bad request fails the clip");
assert!(error.contains("draw-api status 400"), "{error}");
assert_eq!(submitted_idempotency_keys(&probe), ["video-78"]);
@@ -9010,6 +9052,89 @@ mod tests {
job.invocation.endpoint_name, AIFARM_DRAW_API_H3VIDEO_ENDPOINT_NAME,
"a video with sound renders on the MiniMax-H3 endpoint"
);
+ 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"})
+ );
+ }
+
+ #[tokio::test]
+ async fn a_result_lost_after_a_failed_status_read_is_rendered_again() {
+ let clip = [0_u8, 0, 0, 24, b'f', b't', b'y', b'p'];
+ let clip_reply = serde_json::to_vec(&json!({
+ "request_id": "video-79-retry",
+ "video_b64": general_purpose::STANDARD.encode(clip),
+ "mime_type": "video/mp4",
+ "width": 480,
+ "height": 832,
+ "frames": 124,
+ "fps": 24
+ }))
+ .expect("video payload");
+ let transport = AifarmTransportStub::new(vec![
+ Ok(json_response(
+ json!({"job_id": "job-1", "state": "processing"}),
+ )),
+ Err("error decoding response body".into()),
+ Ok(AifarmHttpResponse {
+ status_code: 404,
+ body: br#"{"detail":"job not found"}"#.to_vec(),
+ ..AifarmHttpResponse::default()
+ }),
+ Ok(json_response(
+ json!({"job_id": "job-2", "state": "processing"}),
+ )),
+ Ok(json_response(draw_reply("job-2", 200, &clip_reply))),
+ ]);
+ let probe = transport.clone();
+ let generator = fastframes_generator(transport);
+
+ let video = crate::video_jobs::VideoGenerator::generate_video(
+ &generator,
+ "rain",
+ 79,
+ crate::video_jobs::VideoRender {
+ sound: true,
+ ..crate::video_jobs::VideoRender::default()
+ },
+ )
+ .await
+ .expect("the second submission delivers the video");
+
+ assert_eq!(video.bytes, clip.to_vec());
+ assert_eq!(
+ submitted_idempotency_keys(&probe),
+ ["video-79", "video-79-retry"]
+ );
+ }
+
+ #[tokio::test]
+ async fn a_missing_job_without_a_failed_read_is_not_rendered_again() {
+ let transport = AifarmTransportStub::new(vec![
+ Ok(json_response(
+ json!({"job_id": "job-1", "state": "processing"}),
+ )),
+ Ok(AifarmHttpResponse {
+ status_code: 404,
+ body: br#"{"detail":"job not found"}"#.to_vec(),
+ ..AifarmHttpResponse::default()
+ }),
+ ]);
+ let probe = transport.clone();
+ let generator = fastframes_generator(transport);
+
+ let error = crate::video_jobs::VideoGenerator::generate_video(
+ &generator,
+ "rain",
+ 80,
+ crate::video_jobs::VideoRender::default(),
+ )
+ .await
+ .expect_err("an unknown job fails the clip");
+
+ assert!(error.contains("status 404"), "{error}");
+ assert_eq!(submitted_idempotency_keys(&probe), ["video-80"]);
}
async fn submitted_draw_request(endpoint_name: &str, request: ImageGenerationRequest) -> Value {
@@ -9360,18 +9485,18 @@ mod tests {
#[tokio::test(start_paused = true)]
async fn aifarm_draw_api_poll_recovers_from_a_hanging_request() {
let transport = DelayedAifarmTransport::new(
- vec![(StdDuration::from_secs(90), completed_draw_poll_response())],
+ vec![(StdDuration::from_secs(600), completed_draw_poll_response())],
completed_draw_poll_response(),
);
let generator =
AifarmDrawApiImageGenerator::with_transport(draw_poll_test_config(), transport);
let started = Instant::now();
let result = generator
- .wait_draw_api_job("accepted-job", started + StdDuration::from_secs(60))
+ .wait_draw_api_job("accepted-job", started + StdDuration::from_secs(300))
.await
.expect("retry a hung status request within the inference budget");
assert_eq!(result.urls, vec!["https://img.test/recovered.png"]);
- assert!(started.elapsed() < StdDuration::from_secs(60));
+ assert!(started.elapsed() < AIFARM_DRAW_API_POLL_TIMEOUT + StdDuration::from_secs(5));
}
#[tokio::test]
diff --git a/crates/openplotva-app/src/lib.rs b/crates/openplotva-app/src/lib.rs
index fb6d285..f0e8405 100644
--- a/crates/openplotva-app/src/lib.rs
+++ b/crates/openplotva-app/src/lib.rs
@@ -4957,9 +4957,12 @@ async fn start_runtime_workers(
))
.with_task_enqueue_rate_limit(task_enqueue_rate_limit.clone()),
);
- let random_dialog_effects = Arc::new(dialog_messages::RandomDialogDispatcherEffects::new(
- Arc::clone(&dispatcher_queue_for_updates),
- ));
+ let random_dialog_effects = Arc::new(
+ dialog_messages::RandomDialogDispatcherEffects::new(Arc::clone(
+ &dispatcher_queue_for_updates,
+ ))
+ .with_telegram(telegram.clone()),
+ );
let terminal = Arc::new(RuntimeUnhandledUpdateHandler);
let dialog_terminal = Arc::new(
dialog_messages::DialogMessageUpdateHandler::new(
diff --git a/crates/openplotva-app/src/media.rs b/crates/openplotva-app/src/media.rs
index fd6e355..d88a035 100644
--- a/crates/openplotva-app/src/media.rs
+++ b/crates/openplotva-app/src/media.rs
@@ -183,13 +183,13 @@ impl MediaPromptOptimizer for RoutedMediaPromptOptimizer {
}
impl RoutedMediaPromptOptimizer {
- /// Write the FastFrames prompt for a clip over the media optimizer route. Only
+ /// Write the video model's prompt for a clip over the media optimizer route. Only
/// OpenAI-compatible attempts serve it.
pub async fn optimize_video_prompt(
&self,
request: &str,
brief: &str,
- sound: bool,
+ target: openplotva_media::video::VideoPromptTarget,
) -> Result {
let request = request.to_owned();
let brief = brief.to_owned();
@@ -216,7 +216,7 @@ impl RoutedMediaPromptOptimizer {
AifarmStructuredJsonGenerator::new(cfg).with_prompt_store(prompt_store);
let mut ignore_status = |_status: StatusUpdate| {};
optimizer
- .optimize_video_prompt(&request, &brief, sound, &mut ignore_status)
+ .optimize_video_prompt(&request, &brief, target, &mut ignore_status)
.await
.map_err(|err| MediaPromptOptimizerError::Provider(err.to_string()))
}
diff --git a/crates/openplotva-app/src/payments.rs b/crates/openplotva-app/src/payments.rs
index 259b0eb..044ecc6 100644
--- a/crates/openplotva-app/src/payments.rs
+++ b/crates/openplotva-app/src/payments.rs
@@ -6027,11 +6027,13 @@ const VIP_BENEFITS_TEXT: &str = "⚡ Приоритетное выполнени
🔄 Вдвое больше рисунков за то же время\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Доступ к новым функциям и фичам (в разработке)";
const VIP_BENEFITS_EXTENDED: &str = "⚡ Приоритетное выполнение запросов на рисование вне очереди\n\
🔄 Вдвое увеличенные лимиты на рисование\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Ранний доступ к будущим улучшениям и фичам";
#[cfg(test)]
@@ -9309,6 +9311,7 @@ mod tests {
🔄 Вдвое больше рисунков за то же время\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Доступ к новым функциям и фичам (в разработке)"
);
assert_eq!(message.button_text, "💎 Оформить VIP подписку");
@@ -9467,6 +9470,7 @@ mod tests {
🔄 Вдвое больше рисунков за то же время\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Доступ к новым функциям и фичам (в разработке)"
);
assert!(message.show_cancel_button);
@@ -9544,6 +9548,7 @@ mod tests {
🔄 Вдвое больше рисунков за то же время\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Доступ к новым функциям и фичам (в разработке)"
);
assert!(!message.show_cancel_button);
@@ -11707,6 +11712,7 @@ mod tests {
🔄 Вдвое увеличенные лимиты на рисование\n\
🖼️ Изображения лучшего качества с меньшей цензурой\n\
🎵 Генерация песен по теме через /song (с поддержкой audio reference)\n\
+ 🎬 Видео со звуком через /video: речь, шумы и музыка\n\
🚀 Ранний доступ к будущим улучшениям и фичам"
.to_owned()
}
diff --git a/crates/openplotva-app/src/video_jobs.rs b/crates/openplotva-app/src/video_jobs.rs
index f1a1e6b..9a708da 100644
--- a/crates/openplotva-app/src/video_jobs.rs
+++ b/crates/openplotva-app/src/video_jobs.rs
@@ -9,7 +9,10 @@ use std::{future::Future, pin::Pin, sync::Arc};
use openplotva_llm::aifarm::AifarmHttpTransport;
use openplotva_llm::retry::{FailureReason, retryable_reason_from_message};
-use openplotva_media::{NsfwResult, video::VideoOptimize};
+use openplotva_media::{
+ NsfwResult,
+ video::{VideoOptimize, VideoOrientation, VideoPromptTarget},
+};
use openplotva_server::ACTION_SEND_VIDEO;
use openplotva_taskman::{
InMemoryTaskQueue, TaskQueueWorkItem, VideoGenJobParams, video_gen_job_params_from_payload,
@@ -22,8 +25,8 @@ use openplotva_telegram::{
use time::OffsetDateTime;
use crate::image_jobs::{
- AifarmDrawApiImageGenerator, DrawApiVideo, ImageGenerationError, ImageJobTelegramSender,
- build_image_generation_caption,
+ AifarmDrawApiImageGenerator, DrawApiVideo, DrawApiVideoOptions, ImageGenerationError,
+ ImageJobTelegramSender, build_image_generation_caption,
};
use crate::permissions::{ChatPermissionPolicy, ChatPermissionStore};
use crate::telegram_activity::{TelegramActivityAction, TelegramActivityPulse};
@@ -33,12 +36,13 @@ const VIDEO_FILE_NAME: &str = "video.mp4";
pub type VideoJobFuture<'a, T> = Pin + Send + 'a>>;
pub trait VideoPromptOptimizer: Send + Sync {
- /// `sound` selects the MiniMax-H3 prompt (speech, soundscape, music) over FastFrames'.
+ /// `target.sound` selects the MiniMax-H3 prompt (speech, soundscape, music) over
+ /// FastFrames'; its optimizer also returns the frame it composed for.
fn optimize_video_prompt<'a>(
&'a self,
request: &'a str,
brief: &'a str,
- sound: bool,
+ target: VideoPromptTarget,
) -> VideoJobFuture<'a, Result>;
}
@@ -47,11 +51,11 @@ impl VideoPromptOptimizer for crate::media::RoutedMediaPromptOptimizer {
&'a self,
request: &'a str,
brief: &'a str,
- sound: bool,
+ target: VideoPromptTarget,
) -> VideoJobFuture<'a, Result> {
Box::pin(async move {
crate::media::RoutedMediaPromptOptimizer::optimize_video_prompt(
- self, request, brief, sound,
+ self, request, brief, target,
)
.await
.map_err(|error| format!("video prompt optimizer: {error}"))
@@ -59,16 +63,43 @@ 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)]
+pub struct VideoRender {
+ pub sound: bool,
+ pub steps: u8,
+ pub orientation: VideoOrientation,
+}
+
+impl VideoRender {
+ fn endpoint(&self) -> &'static str {
+ if self.sound {
+ crate::image_jobs::AIFARM_DRAW_API_H3VIDEO_ENDPOINT_NAME
+ } else {
+ crate::image_jobs::AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME
+ }
+ }
+
+ 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()),
+ }
+ }
+}
+
pub trait VideoGenerator: Send + Sync {
- /// Render one clip; `job_id` makes the farm submission idempotent. `sound` renders a
- /// video with sound (MiniMax-H3, `steps` 2 or 4, 0 for the farm default) instead of a
- /// silent clip (FastFrames).
+ /// Render one clip; `job_id` makes the farm submission idempotent.
fn generate_video<'a>(
&'a self,
prompt: &'a str,
job_id: i64,
- sound: bool,
- steps: u8,
+ render: VideoRender,
) -> VideoJobFuture<'a, Result>;
}
@@ -80,18 +111,12 @@ where
&'a self,
prompt: &'a str,
job_id: i64,
- sound: bool,
- steps: u8,
+ render: VideoRender,
) -> VideoJobFuture<'a, Result> {
Box::pin(async move {
- let steps = (sound && steps > 0).then_some(steps);
- let endpoint = if sound {
- crate::image_jobs::AIFARM_DRAW_API_H3VIDEO_ENDPOINT_NAME
- } else {
- crate::image_jobs::AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME
- };
+ let (endpoint, options) = (render.endpoint(), render.options());
let first = self
- .generate_video_with_job_id(endpoint, prompt, steps, &format!("video-{job_id}"))
+ .generate_video_with_job_id(endpoint, prompt, options, &format!("video-{job_id}"))
.await;
let error = match first {
Err(error) if video_render_retryable(&error) => error,
@@ -105,7 +130,7 @@ where
self.generate_video_with_job_id(
endpoint,
prompt,
- steps,
+ options,
&format!("video-{job_id}-retry"),
)
.await
@@ -115,12 +140,15 @@ where
}
/// A second farm job can render the clip when the first one met a draw-api server error
-/// (a worker that died is loaded again) or an unreachable farm; a bad request, a safety
-/// refusal or a watchdog timeout ends the clip.
+/// (a worker that died is loaded again), an unreachable farm or a result lost in transfer; a
+/// bad request, a safety refusal or a watchdog timeout ends the clip.
fn video_render_retryable(error: &ImageGenerationError) -> bool {
let ImageGenerationError::Provider(message) = error else {
return false;
};
+ if message.starts_with(crate::image_jobs::DRAW_API_RESULT_LOST) {
+ return true;
+ }
let server_error = message
.split("draw-api status ")
.skip(1)
@@ -260,6 +288,7 @@ where
delivery: VideoDelivery,
) -> VideoJobFuture<'a, Result, String>> {
Box::pin(async move {
+ let uploaded_bytes = delivery.video.bytes.len();
let sent = if delivery.sound {
let method = video_method(&delivery)?;
crate::image_jobs::within_media_job_telegram_timeout(self.telegram.execute(method))
@@ -269,13 +298,37 @@ where
crate::image_jobs::within_media_job_telegram_timeout(self.telegram.execute(method))
.await
};
- sent.map_err(|error| format!("send video: {error}"))?
- .map(|message| i32::try_from(message.id).ok())
- .map_err(|error| format!("send video: {error}"))
+ let message = sent
+ .map_err(|error| format!("send video: {error}"))?
+ .map_err(|error| format!("send video: {error}"))?;
+ log_stored_clip(&message, uploaded_bytes);
+ Ok(i32::try_from(message.id).ok())
})
}
}
+/// What Telegram stored for an upload: the same size means it kept the file as sent, and
+/// `qualities` counts the versions it transcoded besides the original.
+fn log_stored_clip(message: &carapax::types::Message, uploaded_bytes: usize) {
+ let (kind, stored_bytes, qualities) = match &message.data {
+ carapax::types::MessageData::Video(video) => (
+ "video",
+ video.data.file_size,
+ video.data.qualities.as_ref().map_or(0, Vec::len),
+ ),
+ carapax::types::MessageData::Animation(animation) => ("animation", animation.file_size, 0),
+ _ => return,
+ };
+ tracing::info!(
+ message_id = message.id,
+ kind,
+ uploaded_bytes,
+ stored_bytes,
+ qualities,
+ "Telegram stored the clip"
+ );
+}
+
fn upload_request(delivery: &VideoDelivery) -> UploadMessageRequest {
let thread_id = i64::from(delivery.thread_id.unwrap_or_default());
UploadMessageRequest {
@@ -374,8 +427,16 @@ where
effects
.signal_progress(params.chat_id, params.message_id)
.await;
+ let requested_orientation = VideoOrientation::parse(¶ms.orientation);
let optimized = optimizer
- .optimize_video_prompt(¶ms.request_text, ¶ms.brief, params.sound)
+ .optimize_video_prompt(
+ ¶ms.request_text,
+ ¶ms.brief,
+ VideoPromptTarget {
+ sound: params.sound,
+ orientation: requested_orientation,
+ },
+ )
.await?;
if optimized.nsfw_result == NsfwResult::Forbidden {
let message_id = effects
@@ -386,8 +447,15 @@ where
.await;
return Ok(VideoJobOutcome::Blocked { message_id });
}
+ let render = VideoRender {
+ sound: params.sound,
+ steps: params.steps,
+ orientation: requested_orientation
+ .or(optimized.orientation)
+ .unwrap_or_default(),
+ };
let video = generator
- .generate_video(&optimized.prompt, job_id, params.sound, params.steps)
+ .generate_video(&optimized.prompt, job_id, render)
.await?;
let adult = optimized.nsfw_result == NsfwResult::Adult;
let message_id = effects
@@ -549,16 +617,29 @@ mod tests {
use super::*;
- struct FixedOptimizer(Result);
+ struct FixedOptimizer {
+ result: Result,
+ targets: Mutex>,
+ }
+
+ impl FixedOptimizer {
+ fn new(result: Result) -> Self {
+ Self {
+ result,
+ targets: Mutex::default(),
+ }
+ }
+ }
impl VideoPromptOptimizer for FixedOptimizer {
fn optimize_video_prompt<'a>(
&'a self,
_request: &'a str,
_brief: &'a str,
- _sound: bool,
+ target: VideoPromptTarget,
) -> VideoJobFuture<'a, Result> {
- let result = self.0.clone();
+ self.targets.lock().expect("targets").push(target);
+ let result = self.result.clone();
Box::pin(async move { result })
}
}
@@ -566,7 +647,7 @@ mod tests {
#[derive(Default)]
struct RecordingGenerator {
prompts: Mutex>,
- sound: Mutex>,
+ renders: Mutex>,
fail: bool,
}
@@ -575,14 +656,13 @@ mod tests {
&'a self,
prompt: &'a str,
job_id: i64,
- sound: bool,
- _steps: u8,
+ render: VideoRender,
) -> VideoJobFuture<'a, Result> {
self.prompts
.lock()
.expect("prompts")
.push((prompt.to_owned(), job_id));
- self.sound.lock().expect("sound").push(sound);
+ self.renders.lock().expect("renders").push(render);
let fail = self.fail;
Box::pin(async move {
if fail {
@@ -667,9 +747,10 @@ mod tests {
const BLOCKED_MESSAGE_ID: i32 = 502;
fn optimized(nsfw_result: NsfwResult) -> FixedOptimizer {
- FixedOptimizer(Ok(VideoOptimize {
+ FixedOptimizer::new(Ok(VideoOptimize {
prompt: "A grey cat catches a snowflake.".to_owned(),
nsfw_result,
+ orientation: None,
}))
}
@@ -685,6 +766,7 @@ mod tests {
caption: "Кот и снежинка".to_owned(),
sound: false,
steps: 0,
+ orientation: String::new(),
}
}
@@ -869,7 +951,7 @@ mod tests {
let effects = RecordingEffects::default();
let poll = run_next(
&queue,
- &FixedOptimizer(Err("video prompt optimizer: all attempts failed".to_owned())),
+ &FixedOptimizer::new(Err("video prompt optimizer: all attempts failed".to_owned())),
&RecordingGenerator::default(),
&effects,
)
@@ -972,12 +1054,100 @@ mod tests {
)
.await;
assert!(matches!(outcome, Ok(VideoJobOutcome::Delivered { .. })));
- assert_eq!(generator.sound.lock().expect("sound").as_slice(), [true]);
+ assert_eq!(
+ generator.renders.lock().expect("renders").as_slice(),
+ [VideoRender {
+ sound: true,
+ ..VideoRender::default()
+ }]
+ );
let sent = effects.sent.lock().expect("sent");
assert_eq!(sent.len(), 1);
assert!(sent[0].sound);
}
+ async fn rendered_orientation(
+ requested: &str,
+ inferred: Option,
+ sound: bool,
+ ) -> (VideoPromptTarget, VideoRender) {
+ let optimizer = FixedOptimizer::new(Ok(VideoOptimize {
+ prompt: "A fox runs through snow.".to_owned(),
+ nsfw_result: NsfwResult::Safe,
+ orientation: inferred,
+ }));
+ let generator = RecordingGenerator::default();
+ execute_video_gen_job(
+ &optimizer,
+ &generator,
+ &RecordingEffects::default(),
+ &VideoGenJobParams {
+ sound,
+ steps: 4,
+ orientation: requested.to_owned(),
+ ..params()
+ },
+ 9,
+ true,
+ )
+ .await
+ .expect("delivered");
+ let target = optimizer.targets.lock().expect("targets")[0];
+ let render = generator.renders.lock().expect("renders")[0];
+ (target, render)
+ }
+
+ #[tokio::test]
+ async fn the_dialog_frame_wins_and_the_optimizer_fills_it_in_when_the_dialog_gave_none() {
+ use VideoOrientation::{Landscape, Portrait};
+
+ let (target, render) = rendered_orientation("portrait", Some(Landscape), true).await;
+ assert_eq!(
+ target.orientation,
+ Some(Portrait),
+ "the optimizer composes for it"
+ );
+ assert_eq!(render.orientation, 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);
+
+ let (_, render) = rendered_orientation("", None, true).await;
+ assert_eq!(render.orientation, Landscape, "landscape by default");
+ assert_eq!(
+ render.options(),
+ DrawApiVideoOptions {
+ steps: Some(4),
+ orientation: None,
+ }
+ );
+ }
+
+ #[tokio::test]
+ async fn a_silent_clip_sends_no_video_options() {
+ let (target, render) =
+ rendered_orientation("portrait", Some(VideoOrientation::Portrait), false).await;
+ assert!(!target.sound);
+ assert_eq!(render.options(), DrawApiVideoOptions::default());
+ assert_eq!(
+ render.endpoint(),
+ crate::image_jobs::AIFARM_DRAW_API_FASTFRAMES_ENDPOINT_NAME
+ );
+ let portrait_movie = VideoRender {
+ sound: true,
+ steps: 0,
+ orientation: VideoOrientation::Portrait,
+ };
+ assert_eq!(
+ portrait_movie.options(),
+ DrawApiVideoOptions {
+ steps: None,
+ orientation: Some("portrait"),
+ }
+ );
+ }
+
#[test]
fn only_farm_side_render_failures_get_a_second_submission() {
use crate::image_jobs::ImageGenerationError::{Forbidden, Provider};
diff --git a/crates/openplotva-core/src/lib.rs b/crates/openplotva-core/src/lib.rs
index a26db77..02b9142 100644
--- a/crates/openplotva-core/src/lib.rs
+++ b/crates/openplotva-core/src/lib.rs
@@ -244,6 +244,10 @@ pub struct ChatMessageMeta {
/// Server-granted permission for one spontaneous gift; never copied from a tool argument.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub agent_gift: bool,
+ /// Set by the bot when a configured admin used a `!` shortcut: the generation it asks
+ /// for jumps every queue.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub admin_command: bool,
#[serde(default, rename = "type", skip_serializing_if = "String::is_empty")]
pub message_type: String,
diff --git a/crates/openplotva-dialog/src/dispatch.rs b/crates/openplotva-dialog/src/dispatch.rs
index 2914a35..603a03f 100644
--- a/crates/openplotva-dialog/src/dispatch.rs
+++ b/crates/openplotva-dialog/src/dispatch.rs
@@ -120,11 +120,8 @@ pub async fn dispatch_dialog_tool(
context: meta.clone(),
prompt,
caption: step.caption.clone(),
- quality: if movie {
- step.quality.trim().to_lowercase()
- } else {
- String::new()
- },
+ quality: step.quality.trim().to_lowercase(),
+ orientation: step.orientation.trim().to_lowercase(),
};
if movie {
toolbox.make_movie(request).await
@@ -610,44 +607,73 @@ mod tests {
}
#[derive(Default)]
- struct MovieRecorder(Mutex>);
+ struct MovieRecorder(Mutex>);
impl DialogToolbox for MovieRecorder {
+ fn make_video<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
+ self.0.lock().expect("movies").push((
+ STEP_MAKE_VIDEO,
+ req.prompt,
+ req.quality,
+ req.orientation,
+ ));
+ Box::pin(async { Ok(ToolResult::default()) })
+ }
+
fn make_movie<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
- self.0
- .lock()
- .expect("movies")
- .push((req.prompt, req.quality));
+ self.0.lock().expect("movies").push((
+ STEP_MAKE_MOVIE,
+ req.prompt,
+ req.quality,
+ req.orientation,
+ ));
Box::pin(async { Ok(ToolResult::default()) })
}
}
#[test]
- fn make_movie_passes_the_brief_and_the_requested_quality() {
+ fn both_video_tools_pass_the_brief_quality_and_orientation() {
let toolbox = MovieRecorder::default();
let meta = ToolContext {
message_text: "сгенерируй видео: бабушка печёт пирожки".to_owned(),
..ToolContext::default()
};
- for quality in ["", " High "] {
+ for (tool, quality, orientation) in [
+ (STEP_MAKE_MOVIE, "", ""),
+ (STEP_MAKE_MOVIE, " High ", " Portrait "),
+ (STEP_MAKE_VIDEO, "high", "portrait"),
+ ] {
poll_ready(dispatch_dialog_tool(
&toolbox,
&meta,
&ToolStep {
- step: STEP_MAKE_MOVIE.to_owned(),
+ step: tool.to_owned(),
prompt: "Grandma bakes pies".to_owned(),
caption: "Бабушка и пирожки".to_owned(),
quality: quality.to_owned(),
+ orientation: orientation.to_owned(),
..ToolStep::default()
},
))
.expect("dispatch");
}
+ let brief = || "Grandma bakes pies".to_owned();
assert_eq!(
toolbox.0.lock().expect("movies").as_slice(),
[
- ("Grandma bakes pies".to_owned(), String::new()),
- ("Grandma bakes pies".to_owned(), "high".to_owned()),
+ (STEP_MAKE_MOVIE, brief(), String::new(), String::new()),
+ (
+ STEP_MAKE_MOVIE,
+ brief(),
+ "high".to_owned(),
+ "portrait".to_owned()
+ ),
+ (
+ STEP_MAKE_VIDEO,
+ brief(),
+ "high".to_owned(),
+ "portrait".to_owned()
+ ),
]
);
let empty = poll_ready(dispatch_dialog_tool(
diff --git a/crates/openplotva-dialog/src/lib.rs b/crates/openplotva-dialog/src/lib.rs
index 88ba77b..914262a 100644
--- a/crates/openplotva-dialog/src/lib.rs
+++ b/crates/openplotva-dialog/src/lib.rs
@@ -300,9 +300,12 @@ pub struct VideoRequest {
/// Short clip title in the user's language.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub caption: String,
- /// `make_movie` render quality: "high" (more detail, about twice the time) or empty.
+ /// Render quality of a video with sound: "high" (more detail, slower) or empty.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub quality: String,
+ /// Frame of a video with sound: "portrait" (vertical) or empty for landscape.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub orientation: String,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
@@ -545,6 +548,7 @@ const INLINE_TOOL_ARG_KEYS: &[&str] = &[
"caption",
"topic",
"quality",
+ "orientation",
"file_id",
"file_ids",
"query",
@@ -687,6 +691,8 @@ const GENERATE_SONG_ARGS: &[ToolArgSpec] = &[
},
];
+/// `make_video` and `make_movie` share their arguments: the bot, not the tool name, decides
+/// between a video with sound and a silent clip.
const MAKE_VIDEO_ARGS: &[ToolArgSpec] = &[
ToolArgSpec {
name: "prompt",
@@ -702,16 +708,20 @@ const MAKE_VIDEO_ARGS: &[ToolArgSpec] = &[
politeness. Start with a capital letter. Never include technical instructions \
or details added for generation.",
},
-];
-
-const MAKE_MOVIE_ARGS: &[ToolArgSpec] = &[
- MAKE_VIDEO_ARGS[0],
- MAKE_VIDEO_ARGS[1],
+ ToolArgSpec {
+ name: "orientation",
+ required: false,
+ description: "\"portrait\" for a vertical video: the user asks for a vertical, upright, \
+ 9:16, portrait or phone-screen video, or the video is for Stories, Reels, \
+ TikTok, Shorts or another vertical feed, in the latest message or earlier in the \
+ conversation. \"landscape\" only when the user asks for a horizontal or \
+ widescreen video. Omit it otherwise: videos are landscape by default.",
+ },
ToolArgSpec {
name: "quality",
required: false,
- description: "\"high\" only when the user explicitly asks for a more detailed or higher-quality \
- video; it takes about twice as long. Omit it otherwise.",
+ 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.",
},
];
@@ -949,11 +959,11 @@ const ALTERNATIVE_DIALOG_TOOL_CATALOG: &[ToolSpec] = &[
},
ToolSpec {
name: STEP_MAKE_VIDEO,
- summary: "Generate a short silent video clip (a GIF-like animation) from a text description.",
- when_to_use: "Use when the latest user message asks for a GIF, animation, silent clip or \
- moving picture (гифка, анимация, оживи), or for a video or clip when the user \
- is not VIP or explicitly wants no sound. It makes one continuous five-second \
- shot without sound from text only; it cannot animate an attached picture.",
+ 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.",
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.",
@@ -962,19 +972,19 @@ const ALTERNATIVE_DIALOG_TOOL_CATALOG: &[ToolSpec] = &[
},
ToolSpec {
name: STEP_MAKE_MOVIE,
- summary: "Generate a five-second video with sound (speech, effects, music) from a text \
- description. VIP only.",
- when_to_use: "Use when a VIP user's latest message asks for a video, clip or short film \
- (видео, ролик, клип, фильм, сгенерируй видео), and always when the clip needs \
- sound: speech, dialogue, singing, music or sound effects. Pass any line the \
- user wants spoken verbatim in prompt. For a user without VIP it is refused; \
- offer make_video (a silent clip) instead. It renders from text only; it cannot \
- animate an attached picture.",
+ summary: "Generate a five-second video from a text description: with sound (speech, \
+ effects, music) for VIP users, a silent GIF-like clip for other users.",
+ when_to_use: "Use when the latest user message asks for a video, clip, short film, \
+ 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.",
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.",
continuation: ToolContinuation::MayTerminateOnSuccess,
- args: MAKE_MOVIE_ARGS,
+ args: MAKE_VIDEO_ARGS,
},
ToolSpec {
name: STEP_UNDERSTAND_MEDIA,
@@ -1448,6 +1458,12 @@ fn tool_argument_schema(arg: &ToolArgSpec) -> Value {
json!(["day", "hours", "messages", "since"]),
);
}
+ "orientation" => {
+ schema.insert("enum".to_owned(), json!(["landscape", "portrait"]));
+ }
+ "quality" => {
+ schema.insert("enum".to_owned(), json!(["standard", "high"]));
+ }
_ => {}
}
if !arg.description.trim().is_empty() {
@@ -2708,6 +2724,9 @@ pub struct ToolStep {
/// Render quality of a video with sound: "high" or empty.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub quality: String,
+ /// Frame of a video: "portrait", "landscape" or empty.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub orientation: String,
/// Vision attachment handle.
#[serde(default, rename = "file_id", skip_serializing_if = "String::is_empty")]
pub file_id: String,
@@ -5188,6 +5207,9 @@ fn populate_tool_args(mut lookup: impl FnMut(&str) -> Option, step: &mut
if let Some(value) = lookup("quality") {
step.quality = value;
}
+ if let Some(value) = lookup("orientation") {
+ step.orientation = value;
+ }
if let Some(value) = lookup("file_id") {
step.file_id = value;
}
@@ -5444,6 +5466,7 @@ fn normalize_and_validate_step(mut step: ToolStep) -> Result bool {
step.prompt.as_str(),
step.topic.as_str(),
step.quality.as_str(),
+ step.orientation.as_str(),
step.file_id.as_str(),
step.query.as_str(),
step.url.as_str(),
diff --git a/crates/openplotva-llm/src/aifarm.rs b/crates/openplotva-llm/src/aifarm.rs
index 295bab7..cf6fd16 100644
--- a/crates/openplotva-llm/src/aifarm.rs
+++ b/crates/openplotva-llm/src/aifarm.rs
@@ -2411,12 +2411,12 @@ where
}
/// Write the video model's prompt for a clip from the user's `request` and the dialog's
- /// `brief`: FastFrames for a silent clip, MiniMax-H3 for a video with `sound`.
+ /// `brief`: FastFrames for a silent clip, MiniMax-H3 for a video with sound.
pub async fn optimize_video_prompt(
&self,
request: &str,
brief: &str,
- sound: bool,
+ target: openplotva_media::video::VideoPromptTarget,
on_status: &mut (dyn FnMut(StatusUpdate) + Send),
) -> Result {
if request.trim().is_empty() && brief.trim().is_empty() {
@@ -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, sound,
+ prompts, request, brief, target,
)?,
None => {
- openplotva_media::video::render_video_optimizer_messages(request, brief, sound)?
+ openplotva_media::video::render_video_optimizer_messages(request, brief, target)?
}
}
.into_iter()
@@ -2441,7 +2441,7 @@ where
AifarmStructuredJsonRequest {
name: openplotva_media::video::VIDEO_OPTIMIZER_TOOL_NAME.to_owned(),
messages,
- schema: openplotva_media::video::video_optimizer_schema(),
+ schema: openplotva_media::video::video_optimizer_schema(target.sound),
max_tokens: aifarm_optimizer_max_tokens(1),
temperature: 0.3,
..AifarmStructuredJsonRequest::default()
diff --git a/crates/openplotva-media/src/video.rs b/crates/openplotva-media/src/video.rs
index 520e1b4..119599e 100644
--- a/crates/openplotva-media/src/video.rs
+++ b/crates/openplotva-media/src/video.rs
@@ -11,12 +11,51 @@ pub const VIDEO_OPTIMIZER_PROMPT_NAME: &str = "video/optimizer";
pub const MOVIE_OPTIMIZER_PROMPT_NAME: &str = "video/movie_optimizer";
pub const VIDEO_OPTIMIZER_TOOL_NAME: &str = "optimize_video_prompt";
+/// Frame of a video with sound. FastFrames renders landscape only.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub enum VideoOrientation {
+ #[default]
+ Landscape,
+ Portrait,
+}
+
+impl VideoOrientation {
+ /// `"landscape"` or `"portrait"`, any case; anything else is `None`.
+ #[must_use]
+ pub fn parse(value: &str) -> Option {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "landscape" => Some(Self::Landscape),
+ "portrait" => Some(Self::Portrait),
+ _ => None,
+ }
+ }
+
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Landscape => "landscape",
+ Self::Portrait => "portrait",
+ }
+ }
+}
+
+/// The clip the optimizer writes a prompt for.
+#[derive(Clone, Copy, 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,
+}
+
/// One optimized clip prompt with the safety verdict for the request.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct VideoOptimize {
/// English prompt for the video model.
pub prompt: String,
pub nsfw_result: NsfwResult,
+ /// Frame the prompt was composed for; `None` when the optimizer did not return one.
+ pub orientation: Option,
}
#[derive(Debug, Error)]
@@ -33,6 +72,8 @@ struct VideoOptimizePayload {
nsfw_result: NsfwResult,
#[serde(default)]
prompt: String,
+ #[serde(default)]
+ orientation: Option,
}
/// `sound` picks the MiniMax-H3 prompt instead of the FastFrames one; both share the schema.
@@ -47,11 +88,11 @@ const fn optimizer_prompt_name(sound: bool) -> &'static str {
pub fn render_video_optimizer_messages(
request: &str,
brief: &str,
- sound: bool,
+ target: VideoPromptTarget,
) -> Result, openplotva_prompts::PromptError> {
openplotva_prompts::render_messages(
- optimizer_prompt_name(sound),
- &video_optimizer_template_data(request, brief),
+ optimizer_prompt_name(target.sound),
+ &video_optimizer_template_data(request, brief, target),
)
}
@@ -59,16 +100,17 @@ pub fn render_video_optimizer_messages_with(
prompts: &openplotva_prompts::PromptStore,
request: &str,
brief: &str,
- sound: bool,
+ target: VideoPromptTarget,
) -> Result, openplotva_prompts::PromptError> {
prompts.render_messages(
- optimizer_prompt_name(sound),
- &video_optimizer_template_data(request, brief),
+ optimizer_prompt_name(target.sound),
+ &video_optimizer_template_data(request, brief, target),
)
}
-/// The brief is shown only when it adds something to the request.
-fn video_optimizer_template_data(request: &str, brief: &str) -> Value {
+/// 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 {
let request = request.trim();
let brief = brief.trim();
let (request, brief) = if request.is_empty() {
@@ -78,11 +120,32 @@ fn video_optimizer_template_data(request: &str, brief: &str) -> Value {
} else {
(request, brief)
};
- json!({ "request": request, "brief": brief })
+ let frame = target
+ .orientation
+ .filter(|_| target.sound)
+ .map_or("", VideoOrientation::as_str);
+ json!({ "request": request, "brief": brief, "frame": frame })
}
+/// A video with sound also returns its frame, before the prompt written for it.
#[must_use]
-pub fn video_optimizer_schema() -> Value {
+pub fn video_optimizer_schema(sound: bool) -> Value {
+ if sound {
+ return json!({
+ "type": "object",
+ "properties": {
+ "input": { "type": "string", "description": "the request, copied" },
+ "orientation": { "type": "string", "enum": ["landscape", "portrait"] },
+ "nsfw_result": { "type": "string", "enum": ["safe", "adult", "forbidden"] },
+ "prompt": {
+ "type": "string",
+ "description": "the three MiniMax-H3 fields, 90-170 words in total"
+ }
+ },
+ "required": ["input", "orientation", "nsfw_result", "prompt"],
+ "additionalProperties": false
+ });
+ }
json!({
"type": "object",
"properties": {
@@ -107,6 +170,10 @@ pub fn decode_video_optimize_payload(content: &str) -> Result serde_json::Value {
if params.steps > 0 {
meta[VIDEO_JOB_STEPS_META_KEY] = serde_json::Value::from(params.steps);
}
+ if !params.orientation.is_empty() {
+ meta[VIDEO_JOB_ORIENTATION_META_KEY] = serde_json::Value::from(params.orientation.as_str());
+ }
meta
}
@@ -2942,6 +2950,13 @@ pub fn video_gen_job_params_from_payload(
.image_data
.as_ref()
.ok_or(VideoGenJobPayloadError::MissingVideoData)?;
+ let meta_text = |key: &str| {
+ clip.meta
+ .get(key)
+ .and_then(serde_json::Value::as_str)
+ .unwrap_or_default()
+ .to_owned()
+ };
Ok(VideoGenJobParams {
chat_id: telegram_data.chat_id,
message_id: telegram_data.message_id,
@@ -2950,12 +2965,7 @@ pub fn video_gen_job_params_from_payload(
thread_id: telegram_data.thread_message_id,
request_text: clip.original_text.clone(),
brief: clip.prompt.clone(),
- caption: clip
- .meta
- .get(VIDEO_JOB_CAPTION_META_KEY)
- .and_then(serde_json::Value::as_str)
- .unwrap_or_default()
- .to_owned(),
+ caption: meta_text(VIDEO_JOB_CAPTION_META_KEY),
sound: clip
.meta
.get(VIDEO_JOB_SOUND_META_KEY)
@@ -2967,6 +2977,7 @@ pub fn video_gen_job_params_from_payload(
.and_then(serde_json::Value::as_u64)
.and_then(|steps| u8::try_from(steps).ok())
.unwrap_or(0),
+ orientation: meta_text(VIDEO_JOB_ORIENTATION_META_KEY),
})
}
@@ -5111,6 +5122,7 @@ mod tests {
caption: "Бабушка".to_owned(),
sound: true,
steps: 4,
+ orientation: "portrait".to_owned(),
..VideoGenJobParams::default()
};
let movie = new_video_gen_job_at(params.clone(), now);
@@ -5123,6 +5135,7 @@ mod tests {
VideoGenJobParams {
sound: false,
steps: 0,
+ orientation: String::new(),
..params
},
now,
diff --git a/crates/openplotva-telegram/src/lib.rs b/crates/openplotva-telegram/src/lib.rs
index d4f0162..54b1c83 100644
--- a/crates/openplotva-telegram/src/lib.rs
+++ b/crates/openplotva-telegram/src/lib.rs
@@ -376,6 +376,18 @@ pub const PRIVATE_COMMANDS: &[CommandSpec] = &[
command: "vip",
description: "Оформить VIP-подписку",
},
+ CommandSpec {
+ command: "draw",
+ description: "Нарисовать картинку",
+ },
+ CommandSpec {
+ command: "video",
+ description: "Сгенерировать видео (со звуком для VIP)",
+ },
+ CommandSpec {
+ command: "gif",
+ description: "Сгенерировать гифку",
+ },
CommandSpec {
command: "song",
description: "Сгенерировать песню (VIP)",
@@ -395,6 +407,18 @@ pub const GROUP_COMMANDS: &[CommandSpec] = &[
command: "vip",
description: "Оформить VIP-подписку",
},
+ CommandSpec {
+ command: "draw",
+ description: "Нарисовать картинку",
+ },
+ CommandSpec {
+ command: "video",
+ description: "Сгенерировать видео (со звуком для VIP)",
+ },
+ CommandSpec {
+ command: "gif",
+ description: "Сгенерировать гифку",
+ },
CommandSpec {
command: "song",
description: "Сгенерировать песню (VIP)",
@@ -427,6 +451,18 @@ pub const GROUP_ADMIN_COMMANDS: &[CommandSpec] = &[
command: "vip",
description: "Оформить VIP-подписку",
},
+ CommandSpec {
+ command: "draw",
+ description: "Нарисовать картинку",
+ },
+ CommandSpec {
+ command: "video",
+ description: "Сгенерировать видео (со звуком для VIP)",
+ },
+ CommandSpec {
+ command: "gif",
+ description: "Сгенерировать гифку",
+ },
CommandSpec {
command: "song",
description: "Сгенерировать песню (VIP)",
@@ -757,14 +793,26 @@ mod tests {
.iter()
.map(|command| command.command)
.collect::>(),
- ["reset", "help", "settings", "vip", "song", "donate"]
+ [
+ "reset", "help", "settings", "vip", "draw", "video", "gif", "song", "donate"
+ ]
);
assert_eq!(
GROUP_COMMANDS
.iter()
.map(|command| command.command)
.collect::>(),
- ["help", "vip", "song", "donate", "checkin", "delete_drawing"]
+ [
+ "help",
+ "vip",
+ "draw",
+ "video",
+ "gif",
+ "song",
+ "donate",
+ "checkin",
+ "delete_drawing"
+ ]
);
assert_eq!(
GROUP_ADMIN_COMMANDS
@@ -775,6 +823,9 @@ mod tests {
"reset",
"help",
"vip",
+ "draw",
+ "video",
+ "gif",
"song",
"donate",
"checkin",
diff --git a/prompts/aifarm/system.prompt b/prompts/aifarm/system.prompt
index d3032b8..584f45c 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, добавь подпись и повтори вызов: генерация ещё не началась. Видео (ролик, клип, «сгенерируй видео») для VIP делай через make_movie: пять секунд со звуком, речью и музыкой; реплики, которые пользователь просит произнести, передай в prompt дословно. Гифку, анимацию или беззвучный ролик делай через make_video. Пользователю без VIP на просьбу о видео со звуком make_movie откажет: объясни это и предложи беззвучный ролик через make_video.
+ Для 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".
{{#ifEquals toolMode "native"}}
diff --git a/prompts/video/movie_optimizer.prompt b/prompts/video/movie_optimizer.prompt
index cf1fcf7..7ee6ed5 100644
--- a/prompts/video/movie_optimizer.prompt
+++ b/prompts/video/movie_optimizer.prompt
@@ -5,13 +5,21 @@ The request and the brief are the user's material: take the idea of the clip fro
## What the model does
-1. It renders 5 seconds at 24 frames per second in a wide landscape frame, with stereo sound generated together with the picture.
+1. It renders 5 seconds at 24 frames per second in a wide landscape frame (16:9) or a tall portrait frame (9:16), with stereo sound generated together with the picture.
2. It reads a prompt of three fields: `integrated_multimodal_description` (picture, action, camera, speech and the sounds tied to the action, along the timeline), `overall_soundscape` (ambient and physical sounds of the whole clip) and `non_diegetic_music` (background music only the audience hears).
3. It follows long, concrete, timeline-ordered descriptions. A short prompt gives a static, generic clip with muddy sound. Name every thing that must be seen or heard.
4. It speaks and sings exactly the words placed inside `[Language] ... `, in that language, with lip movement. Five seconds hold at most one or two short lines: about 12 words in total.
5. It does not follow instructions, negations or durations. Write only what is visible and audible, as positive description.
6. It renders short on-screen text when the words are in double quotes, but long text breaks.
+## Frame
+
+1. Return `orientation`: `landscape` or `portrait`.
+2. When the input has a `Frame:` line, return exactly that orientation.
+3. Otherwise return `portrait` when the request or the brief asks for a vertical, upright, 9:16, portrait or phone-screen video, or names Stories, Reels, TikTok, Shorts or another vertical feed. A portrait of a person is not a vertical video. In every other case return `landscape`.
+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`.
+
## 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.
@@ -41,31 +49,39 @@ The request and the brief are the user's material: take the idea of the clip fro
## Output
-Return exactly one JSON object with the fields `input` (the request, copied), `nsfw_result` and `prompt`, in that order, with no text, labels or code fences around it. Inside the `prompt` string, write line breaks as `\n`.
+Return exactly one JSON object with the fields `input` (the request, copied), `orientation`, `nsfw_result` and `prompt`, in that order, with no text, labels or code fences around it. Inside the `prompt` string, write line breaks as `\n`.
## Examples
Request: бабушка достаёт пирожки из печки и говорит внуку садиться за стол
-{"input": "бабушка достаёт пирожки из печки и говорит внуку садиться за стол", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a warm medium shot inside a cozy wooden village kitchen on a winter evening, frost on the small window and a white brick stove in the background. An elderly woman in her seventies with a flowered headscarf, a knitted grey cardigan and flour on her hands takes a tray of golden pies out of the oven and sets it on the table. The camera pushes in with small amplitude at slow speed as she turns toward the camera and smiles, and the elderly woman with a warm, slightly hoarse voice (S1) says: [Russian] Садись за стол, пирожки горячие! Steam rises from the pies in the soft lamp light.\n\noverall_soundscape: The oven door creaks and the metal tray scrapes on the wooden table. Firewood crackles in the stove while a wall clock ticks.\n\nnon_diegetic_music: N/A"}
+{"input": "бабушка достаёт пирожки из печки и говорит внуку садиться за стол", "orientation": "landscape", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a warm medium shot inside a cozy wooden village kitchen on a winter evening, frost on the small window and a white brick stove in the background. An elderly woman in her seventies with a flowered headscarf, a knitted grey cardigan and flour on her hands takes a tray of golden pies out of the oven and sets it on the table. The camera pushes in with small amplitude at slow speed as she turns toward the camera and smiles, and the elderly woman with a warm, slightly hoarse voice (S1) says: [Russian] Садись за стол, пирожки горячие! Steam rises from the pies in the soft lamp light.\n\noverall_soundscape: The oven door creaks and the metal tray scrapes on the wooden table. Firewood crackles in the stove while a wall clock ticks.\n\nnon_diegetic_music: N/A"}
Request: корги катается на сёрфе на закате
-{"input": "корги катается на сёрфе на закате", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a golden-hour seascape with a low orange sun over a turquoise ocean and long glassy waves rolling toward a sandy beach. A fluffy corgi with a red and white coat and a small blue life vest stands on a bright yellow surfboard in the center of the frame, ears up. The corgi crouches as the board climbs the face of a wave, then rides down the curl while white spray bursts behind the board and droplets sparkle in the light. The camera tracks alongside the board at water level, slightly ahead of it.\n\noverall_soundscape: Waves roar and crash, water hisses under the board, and the corgi gives one happy bark. Seagulls cry in the distance.\n\nnon_diegetic_music: A bright surf-rock guitar riff at a fast tempo with a driving drum beat."}
+{"input": "корги катается на сёрфе на закате", "orientation": "landscape", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] Live-action, cinematic, a golden-hour seascape with a low orange sun over a turquoise ocean and long glassy waves rolling toward a sandy beach. A fluffy corgi with a red and white coat and a small blue life vest stands on a bright yellow surfboard in the center of the frame, ears up. The corgi crouches as the board climbs the face of a wave, then rides down the curl while white spray bursts behind the board and droplets sparkle in the light. The camera tracks alongside the board at water level, slightly ahead of it.\n\noverall_soundscape: Waves roar and crash, water hisses under the board, and the corgi gives one happy bark. Seagulls cry in the distance.\n\nnon_diegetic_music: A bright surf-rock guitar riff at a fast tempo with a driving drum beat."}
Request: anime samurai girl in neon rain draws her katana and says "it ends tonight"
-{"input": "anime samurai girl in neon rain draws her katana and says \"it ends tonight\"", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] 2D-animated, anime style, a medium shot of a narrow neon-lit city street at night in heavy rain, pink and cyan signs reflected in the puddles. A young swordswoman in a long black coat with a red scarf stands in the middle of the street, a katana in a black sheath at her hip, rain dripping from her hood. She lowers her head, then draws the katana in one smooth arc as the blade flashes with reflected neon. The camera pushes in from a low angle at slow speed as the young woman with a cold, quiet voice (S1) says: [English] It ends tonight. \n\noverall_soundscape: Heavy rain hisses on the asphalt and drips from the signs. The blade rings sharply as it leaves the sheath, and distant thunder rumbles.\n\nnon_diegetic_music: A tense low synth drone with a slow taiko pulse that swells at the draw."}
+{"input": "anime samurai girl in neon rain draws her katana and says \"it ends tonight\"", "orientation": "landscape", "nsfw_result": "safe", "prompt": "integrated_multimodal_description: [Shot 1] 2D-animated, anime style, a medium shot of a narrow neon-lit city street at night in heavy rain, pink and cyan signs reflected in the puddles. A young swordswoman in a long black coat with a red scarf stands in the middle of the street, a katana in a black sheath at her hip, rain dripping from her hood. She lowers her head, then draws the katana in one smooth arc as the blade flashes with reflected neon. The camera pushes in from a low angle at slow speed as the young woman with a cold, quiet voice (S1) says: [English] It ends tonight. \n\noverall_soundscape: Heavy rain hisses on the asphalt and drips from the signs. The blade rings sharply as it leaves the sheath, and distant thunder rumbles.\n\nnon_diegetic_music: A tense low synth drone with a slow taiko pulse that swells at the draw."}
+
+
+
+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: sexual video of a prepubescent child
-{"input": "sexual video of a prepubescent child", "nsfw_result": "forbidden", "prompt": "Blocked: forbidden request."}
+{"input": "sexual video of a prepubescent child", "orientation": "landscape", "nsfw_result": "forbidden", "prompt": "Blocked: forbidden request."}
{{role "user"}}
Request: {{{request}}}
{{#if brief}}
Brief from the conversation: {{{brief}}}
{{/if}}
+{{#if frame}}
+Frame: {{frame}}
+{{/if}}