Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/openplotva-app/src/agent_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},"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":vip},"subject_to_chat_policy_and_rate_limits":true}),
)),
Err(_) => Ok(ToolResult::failed(
"status_unknown",
Expand Down
39 changes: 39 additions & 0 deletions crates/openplotva-app/src/dialog_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1665,6 +1665,7 @@ where
|| 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)
|| is_search_command_for_bot(message, &first_word_lower, &bot_username)
{
return handle_dialog_message_update_or_else_with_image_and_song_notices(
Expand Down Expand Up @@ -1812,6 +1813,7 @@ where
}
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,
Expand Down Expand Up @@ -1882,6 +1884,15 @@ where
),
parsed.rest_text.trim().to_owned(),
))
} else if is_movie_shortcut(message, &first_word_lower, &bot_username) {
Some((
openplotva_dialog::STEP_MAKE_MOVIE,
format!(
"Requested tool: make_movie. Prompt: {}",
parsed.rest_text.trim()
),
parsed.rest_text.trim().to_owned(),
))
} else {
direct_image_shortcut(
message,
Expand Down Expand Up @@ -2094,6 +2105,24 @@ fn is_video_shortcut(
|| target.is_some_and(|target| target.eq_ignore_ascii_case(bot_username)))
}

/// `/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;
}
let Some((command, target)) = slash_command_parts(word) else {
return false;
};
command == "movie"
&& (telegram_chat_is_private(&message.chat)
|| target.is_some_and(|target| target.eq_ignore_ascii_case(bot_username)))
}

fn is_plain_song_alias(first_word: &str) -> bool {
matches!(first_word.trim(), "song" | "песня")
}
Expand Down Expand Up @@ -6787,6 +6816,16 @@ mod tests {
"make_video",
"кот ловит снежинку",
),
(
"!кино бабушка зовёт внука есть пирожки",
"make_movie",
"бабушка зовёт внука есть пирожки",
),
(
"/movie@plotva_bot dog barks at the mailman",
"make_movie",
"dog barks at the mailman",
),
("!draw red fish", "draw_image", "red fish"),
("@plotva_bot нарисуй рыбу", "draw_image", "рыбу"),
("@plotva_bot пожалуйста, нарисуй рыбу", "draw_image", "рыбу"),
Expand Down
155 changes: 126 additions & 29 deletions crates/openplotva-app/src/dialog_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,10 @@ 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.
pub steps: u8,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
Expand All @@ -950,12 +954,15 @@ 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",
Expand All @@ -978,6 +985,9 @@ impl VideoScheduleRejection {
Self::RateLimited => {
"Слишком много запросов подряд, сработал лимит очереди. Задача не поставлена в очередь."
}
Self::VipOnly => {
"Видео со звуком доступно только VIP-пользователям, у пользователя нет VIP-подписки. Видео не поставлено в очередь. Можно предложить беззвучный ролик (make_video)."
}
}
}
}
Expand Down Expand Up @@ -1644,6 +1654,9 @@ 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);
if self
.queue
Expand Down Expand Up @@ -1688,10 +1701,12 @@ impl VideoScheduler for TaskmanDialogToolAdapter {
request_text: request.message_text.trim().to_owned(),
brief: request.brief,
caption: request.caption,
sound: request.sound,
steps: request.steps,
},
OffsetDateTime::now_utc(),
)
.with_name("video")
.with_name(if request.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) {
Expand Down Expand Up @@ -2571,6 +2586,42 @@ impl<RatesFetcherT, RatesDispatcherT, TranslatorT>
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.
async fn schedule_dialog_video(
&self,
req: VideoRequest,
sound: bool,
) -> Result<ToolResult, ToolboxError> {
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"),
"video service unavailable",
));
};
let request = VideoScheduleRequest {
chat_id: req.context.chat_id,
thread_id: req.context.thread_id,
message_id: req.context.message_id,
user_id: req.context.user_id,
user_full_name: req.context.user_full_name,
brief: sanitize_tool_text(&req.prompt),
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 },
};
match scheduler.schedule_video(request).await {
Ok(result) => Ok(dialog_make_video_tool_result(&result, tool)),
Err(error) => Ok(ToolResult::failed(
format!("{tool}_failed"),
error.to_string(),
)),
}
}

#[must_use]
pub fn with_vision_describer(mut self, vision_describer: Arc<dyn VisionDescriber>) -> Self {
self.vision_describer = Some(vision_describer);
Expand Down Expand Up @@ -2694,7 +2745,9 @@ where
fn offers_tool(&self, name: &str) -> bool {
match name {
openplotva_dialog::STEP_RUN_PYTHON => self.python_sandbox.is_some(),
openplotva_dialog::STEP_MAKE_VIDEO => self.video_scheduler.is_some(),
openplotva_dialog::STEP_MAKE_VIDEO | openplotva_dialog::STEP_MAKE_MOVIE => {
self.video_scheduler.is_some()
}
_ => true,
}
}
Expand Down Expand Up @@ -2841,29 +2894,11 @@ where
}

fn make_video<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
Box::pin(async move {
let Some(scheduler) = self.video_scheduler.as_deref() else {
return Ok(ToolResult::failed(
"make_video_unavailable",
"video service unavailable",
));
};
let request = VideoScheduleRequest {
chat_id: req.context.chat_id,
thread_id: req.context.thread_id,
message_id: req.context.message_id,
user_id: req.context.user_id,
user_full_name: req.context.user_full_name,
brief: sanitize_tool_text(&req.prompt),
caption: verbatim_video_caption(&req.context.message_meta)
.unwrap_or_else(|| sanitize_tool_text(&req.caption)),
message_text: req.context.message_text,
};
match scheduler.schedule_video(request).await {
Ok(result) => Ok(dialog_make_video_tool_result(&result)),
Err(error) => Ok(ToolResult::failed("make_video_failed", error.to_string())),
}
})
Box::pin(self.schedule_dialog_video(req, false))
}

fn make_movie<'a>(&'a self, req: VideoRequest) -> ToolboxFuture<'a> {
Box::pin(self.schedule_dialog_video(req, true))
}

fn understand_media<'a>(&'a self, req: VisionRequest) -> ToolboxFuture<'a> {
Expand Down Expand Up @@ -3161,7 +3196,8 @@ fn dialog_generate_song_tool_result(result: &SongScheduleResult) -> ToolResult {
})
}

fn dialog_make_video_tool_result(result: &VideoScheduleResult) -> ToolResult {
fn dialog_make_video_tool_result(result: &VideoScheduleResult, tool: &str) -> ToolResult {
let not_scheduled_error_code = format!("{tool}_not_scheduled");
scheduled_generation_tool_result(GenerationToolResultArgs {
scheduler_status: &result.status,
scheduler_message: &result.message,
Expand All @@ -3170,7 +3206,7 @@ fn dialog_make_video_tool_result(result: &VideoScheduleResult) -> ToolResult {
side_effect_kind: openplotva_dialog::turn::SIDE_EFFECT_KIND_VIDEO,
ticket_job_id: result.job_id,
not_scheduled_fallback: VIDEO_GENERATION_NOT_SCHEDULED_MESSAGE,
not_scheduled_error_code: "make_video_not_scheduled",
not_scheduled_error_code: &not_scheduled_error_code,
})
}

Expand Down Expand Up @@ -5393,6 +5429,8 @@ mod tests {
brief: "A grey cat catches a snowflake".to_owned(),
caption: "Кот и снежинка".to_owned(),
message_text: " !видео кот ловит снежинку ".to_owned(),
sound: false,
steps: 0,
}
}

Expand Down Expand Up @@ -5442,6 +5480,8 @@ mod tests {
request_text: "!видео кот ловит снежинку".to_owned(),
brief: "A grey cat catches a snowflake".to_owned(),
caption: "Кот и снежинка".to_owned(),
sound: false,
steps: 0,
})
);
assert_eq!(
Expand All @@ -5453,7 +5493,7 @@ mod tests {
assert_eq!(recorded.len(), 1);
assert_eq!(recorded[0].kind, "video_generation_job");
assert_eq!(recorded[0].ticket_job_id, records[0].id);
let queued = dialog_make_video_tool_result(&scheduled);
let queued = dialog_make_video_tool_result(&scheduled, "make_video");
assert_eq!(queued.status, TOOL_RESULT_STATUS_QUEUED);
assert_eq!(
queued
Expand Down Expand Up @@ -5495,7 +5535,7 @@ mod tests {

assert_eq!(refused.rejection, Some(VideoScheduleRejection::ActiveLimit));
assert_eq!(queue.records().len(), 5);
let result = dialog_make_video_tool_result(&refused);
let result = dialog_make_video_tool_result(&refused, "make_video");
assert_eq!(result.status, TOOL_RESULT_STATUS_FAILED);
assert_eq!(
result
Expand Down Expand Up @@ -5554,15 +5594,72 @@ mod tests {
Ok(())
}

#[tokio::test]
async fn taskman_dialog_tool_adapter_queues_vip_videos_with_sound() -> 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(true)));

let scheduled = adapter
.schedule_video(VideoScheduleRequest {
sound: true,
steps: 4,
..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);
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)));

let refused = adapter
.schedule_video(VideoScheduleRequest {
sound: true,
..video_request(11)
})
.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);
assert_eq!(
result
.data
.as_ref()
.and_then(|data| data["reason"].as_str()),
Some("vip_only")
);
Ok(())
}

#[test]
fn app_dialog_toolbox_offers_make_video_only_with_a_scheduler() {
let without = toolbox(None);
assert!(!without.offers_tool(openplotva_dialog::STEP_MAKE_VIDEO));
assert!(!without.offers_tool(openplotva_dialog::STEP_MAKE_MOVIE));
assert!(without.offers_tool(openplotva_dialog::STEP_GENERATE_SONG));
let queue = Arc::new(InMemoryTaskQueue::new());
let with =
toolbox(None).with_video_scheduler(Arc::new(TaskmanDialogToolAdapter::new(queue)));
assert!(with.offers_tool(openplotva_dialog::STEP_MAKE_VIDEO));
assert!(with.offers_tool(openplotva_dialog::STEP_MAKE_MOVIE));
}

#[tokio::test]
Expand Down
1 change: 1 addition & 0 deletions crates/openplotva-app/src/dialog_turn/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1614,6 +1614,7 @@ fn effect_tool(name: &str) -> bool {
"draw_image"
| "generate_song"
| "make_video"
| "make_movie"
| "draw_api"
| "send_message"
| "react_to_message"
Expand Down
Loading
Loading