joeyutong commented on code in PR #1382: URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4695361963
########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,548 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.agents.plan.resource.python; + +import org.apache.flink.agents.api.chat.messages.AudioBlock; +import org.apache.flink.agents.api.chat.messages.DataContentBlock; +import org.apache.flink.agents.api.chat.messages.ImageBlock; +import org.apache.flink.agents.api.chat.messages.TextBlock; +import org.apache.flink.agents.api.chat.messages.VideoBlock; +import org.apache.flink.agents.api.media.AsyncJobModel; +import org.apache.flink.agents.api.media.AsyncJobPolling; +import org.apache.flink.agents.api.media.BaseImageGenerationModelSetup; +import org.apache.flink.agents.api.media.BaseMediaModelSetup; +import org.apache.flink.agents.api.media.BaseSpeechSynthesisModelSetup; +import org.apache.flink.agents.api.media.BaseTranscriptionModelSetup; +import org.apache.flink.agents.api.media.BaseVideoGenerationModelSetup; +import org.apache.flink.agents.api.media.ImageGenerationRequest; +import org.apache.flink.agents.api.media.MediaJob; +import org.apache.flink.agents.api.media.MediaJobState; +import org.apache.flink.agents.api.media.MediaResult; +import org.apache.flink.agents.api.media.SpeechSynthesisRequest; +import org.apache.flink.agents.api.media.TranscriptionRequest; +import org.apache.flink.agents.api.media.VideoGenerationRequest; +import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup; +import org.apache.flink.agents.api.resource.PythonResourceDescriptor; +import org.apache.flink.agents.api.resource.ResourceContext; +import org.apache.flink.agents.api.resource.ResourceDescriptor; +import org.apache.flink.agents.api.resource.ResourceType; +import org.apache.flink.agents.api.utils.StringValidationUtils; +import org.apache.flink.agents.plan.exceptions.UncapturableException; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +/** + * Factory creating Java {@link BaseMediaModelSetup} bridges around Python {@link + * ResourceType#MEDIA_MODEL} setup instances. + * + * <p>Each created resource extends the task-specific {@code Base*ModelSetup} class and implements + * {@link AsyncJobModel} if and only if the underlying Python resource supports async jobs. + */ +public final class PythonMediaModelSetup { + private PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + Objects.requireNonNull(descriptor, "descriptor"); + Object inspection = adapter.invoke("python_java_utils.inspect_media_model", resource); + if (!(inspection instanceof Map)) { + throw new IllegalStateException("Invalid MediaModel inspection result from Python"); + } + Map<?, ?> metadata = (Map<?, ?>) inspection; + Object taskValue = metadata.get("task"); + Object asyncValue = metadata.get("async"); + if (!(taskValue instanceof String) || !(asyncValue instanceof Boolean)) { + throw new IllegalStateException("Invalid MediaModel inspection result from Python"); + } + String task = (String) taskValue; + boolean async = (Boolean) asyncValue; + final String connectionName; + final String model; + @Nullable final String voice; + try { + connectionName = + StringValidationUtils.requireNonBlank(metadata.get("connection"), "connection"); + model = StringValidationUtils.requireNonBlank(metadata.get("model"), "model"); + voice = + "speech_synthesis".equals(task) + ? StringValidationUtils.optionalNonBlank(metadata.get("voice"), "voice") + : null; + } catch (IllegalArgumentException e) { + throw new IllegalStateException("Invalid MediaModel inspection result from Python", e); + } + ResourceDescriptor effectiveDescriptor = + descriptorWithInspectedMetadata(descriptor, connectionName, model, voice); + Handle handle = new Handle(adapter, resource, task, effectiveDescriptor, resourceContext); + switch (task) { + case "speech_synthesis": + return async ? new AsyncSpeech(handle) : new Speech(handle); + case "transcription": + return async ? new AsyncTranscription(handle) : new Transcription(handle); + case "image_generation": + return async ? new AsyncImage(handle) : new Image(handle); + case "video_generation": + return async ? new AsyncVideo(handle) : new Video(handle); + default: + throw new IllegalStateException("Invalid MediaModel inspection result from Python"); + } + } + + private static ResourceDescriptor descriptorWithInspectedMetadata( + ResourceDescriptor descriptor, + String connectionName, + String model, + @Nullable String voice) { + Map<String, Object> mergedArgs = + descriptor.getInitialArguments() != null + ? new HashMap<>(descriptor.getInitialArguments()) + : new HashMap<>(); + mergedArgs.put("connection", connectionName); + mergedArgs.put("model", model); + if (voice != null) { + mergedArgs.put("voice", voice); + } else { + mergedArgs.remove("voice"); + } + if (descriptor instanceof PythonResourceDescriptor) { + return new PythonResourceDescriptor( + descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + return new ResourceDescriptor(descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + + static final class Handle { + private final PythonResourceAdapter adapter; + private final PyObject resource; + private final String task; + private final ResourceDescriptor descriptor; + @Nullable private final ResourceContext resourceContext; + private volatile boolean closed; + + private Handle( + PythonResourceAdapter adapter, + PyObject resource, + String task, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + this.adapter = adapter; + this.resource = resource; + this.task = task; + this.descriptor = descriptor; + this.resourceContext = resourceContext; + } + + private void open() { + adapter.callMethod(resource, "open", Map.of()); Review Comment: Done. Propagated the owning `ResourceContext` through `PythonResourceAdapter.initPythonResource(..., resourceContext)` (backed by scoped child adapters in `PythonResourceAdapterImpl` with `JavaResourceAdapter.withResourceContext(...)` and cleanup on `close()`), updated `PythonResourceProvider` to pass it in the shared initialization path, and added unit and native bridge coverage for both child-only connections and child overrides (`PythonResourceAdapterImplTest`, `PythonResourceProviderTest`, `MediaModelCancellationBridgeTest`). ########## python/flink_agents/integrations/media_models/tests/test_dashscope_video_generation.py: ########## @@ -0,0 +1,346 @@ +################################################################################ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################# +from collections.abc import Callable +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import httpx +import pytest + +from flink_agents.api.chat_message import ( + AudioBlock, + DocumentBlock, + ImageBlock, + TextBlock, + UnsupportedContentBlockError, + VideoBlock, +) +from flink_agents.api.media import ( + BaseVideoGenerationModelSetup, + MediaJobStatus, + MediaResult, +) +from flink_agents.integrations.media_models.dashscope_media_model import ( + DashScopeVideoGenerationModelSetup, +) + +_IMAGE = "https://example.test/frame.png" +_VIDEO = "https://oss.example/out.mp4?Expires=1700000000" + + [email protected] +def model_factory( + setup_factory: Callable[..., BaseVideoGenerationModelSetup], +) -> Callable[..., BaseVideoGenerationModelSetup]: + def create(**overrides: Any) -> BaseVideoGenerationModelSetup: + values: dict[str, Any] = {"model": "custom-video-deployment"} + values.update(overrides) + return setup_factory(DashScopeVideoGenerationModelSetup, **values) + + return create + + +def test_text_submission_forwards_model_and_parameters( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory(resolution="720P", duration=3) + model._client().videos.jobs = sdk_jobs + + job = model.submit("a cat", model_parameters={"duration": 5}) + + assert job.job_id == "job-1" + assert job.expires_at_ms == job.submitted_at_ms + 24 * 60 * 60 * 1000 + assert sdk_jobs.created == [ + { + "model": "custom-video-deployment", + "prompt": "a cat", + "media": None, + "parameters": {"resolution": "720P", "duration": 5}, + } + ] + assert model.model_kwargs == { + "model": "custom-video-deployment", + "resolution": "720P", + "duration": 3, + } + + [email protected]( + ("call_parameters", "role"), + [ + (None, "reference_image"), + ({"video_media_roles": ("first_frame",)}, "first_frame"), + ], +) +def test_media_roles_use_configuration_or_call_override( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + call_parameters: dict[str, Any] | None, + role: str, +) -> None: + model = model_factory( + video_media_roles=["reference_image"], additional_kwargs={"format": "mp4"} + ) + model._client().videos.jobs = sdk_jobs + + model.submit( + media=[ImageBlock.from_url("image/png", _IMAGE)], + model_parameters=call_parameters, + ) + + assert sdk_jobs.created[0]["prompt"] is None + assert sdk_jobs.created[0]["media"] == [{"type": role, "url": _IMAGE}] + assert sdk_jobs.created[0]["parameters"] == {"format": "mp4"} + assert model.video_media_roles == ["reference_image"] + assert model.additional_kwargs == {"format": "mp4"} + + +def test_mixed_media_preserves_sources_order_and_roles( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + audio = "https://example.test/drive.mp3" + clip = "https://example.test/clip.mp4" + document = "oss://dashscope-instant/demo/notes.pdf" + page = "https://example.test/article" + + model.submit( + "Animate these references.", + media=[ + ImageBlock.from_url("image/png", _IMAGE), + ImageBlock.from_base64("image/png", "YQ=="), + AudioBlock.from_url("audio/mpeg", audio), + AudioBlock.from_base64("audio/mpeg", "YQ=="), + VideoBlock.from_url("video/mp4", clip), + DocumentBlock.from_url("application/pdf", document), + DocumentBlock.from_url("text/html", page), + ], + model_parameters={ + "video_media_roles": [ + "reference_image", + "reference_image", + "driving_audio", + "driving_audio", + "first_clip", + "file", + "custom-provider-role", + ] + }, + ) + + assert sdk_jobs.created == [ + { + "model": "custom-video-deployment", + "prompt": "Animate these references.", + "media": [ + {"type": "reference_image", "url": _IMAGE}, + {"type": "reference_image", "url": "data:image/png;base64,YQ=="}, + {"type": "driving_audio", "url": audio}, + {"type": "driving_audio", "url": "data:audio/mpeg;base64,YQ=="}, + {"type": "first_clip", "url": clip}, + {"type": "file", "url": document}, + {"type": "custom-provider-role", "url": page}, + ], + "parameters": None, + } + ] + + +def test_empty_request_is_rejected_before_submission( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(ValueError, match="requires a prompt or at least one media"): + model.submit() + + assert sdk_jobs.created == [] + + [email protected]( + ("prompt", "media"), + [ + (None, None), + ("Animate this.", [TextBlock(text="Not a media input.")]), + ("Animate this.", ImageBlock.from_url("image/png", _IMAGE)), + ], +) +def test_submit_rejects_invalid_inputs_before_request( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + prompt: Any, + media: Any, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(TypeError): + model.submit( + prompt, + media=media, + model_parameters={"video_media_roles": ["reference_image"]}, + ) + + assert sdk_jobs.created == [] + + [email protected]( + ("roles", "message"), + [ + (None, "video_media_roles is required"), + (["first_frame", "last_frame"], "one entry for each media block"), + ], +) +def test_media_requires_one_role_per_block( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + roles: list[str] | None, + message: str, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + media = [ImageBlock.from_url("image/png", _IMAGE)] + + with pytest.raises(ValueError, match=message): + model.submit(media=media, model_parameters={"video_media_roles": roles}) + + assert sdk_jobs.created == [] + + [email protected]( + "roles", + ["first_frame", {"first_frame"}, {"first_frame": "reference_image"}, [1], [""]], +) +def test_roles_require_an_ordered_sequence_of_nonempty_strings( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + roles: Any, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(TypeError, match="video_media_roles"): + model.submit( + media=[ImageBlock.from_url("image/png", _IMAGE)], + model_parameters={"video_media_roles": roles}, + ) + + assert sdk_jobs.created == [] + + +def test_fetch_reads_the_video_result( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + task_responses: Callable[..., list[dict[str, Any]]], +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + calls = task_responses( + model, + httpx.Response( + 200, + json={ + "request_id": "req-1", + "usage": {"duration": 5}, + "output": {"task_status": "SUCCEEDED", "video_url": _VIDEO}, + }, + ), + ) + job = model.submit("a cat") + + state = model.fetch(job) + + assert [(call["method"], call["path"]) for call in calls] == [ + ("GET", "/tasks/job-1") + ] + assert state.status is MediaJobStatus.SUCCEEDED + assert isinstance(state.result, MediaResult[VideoBlock]) + restored = type(state).model_validate_json(state.model_dump_json()) + assert isinstance(restored.result, MediaResult[VideoBlock]) + assert len(state.result.content) == 1 + block = state.result.content[0] + assert isinstance(block, VideoBlock) + assert block.media_type == "video/mp4" + assert block.source.url == _VIDEO + assert state.result.expires_at_ms == 1_700_000_000_000 + assert state.result.usage == {"duration": 5} + assert state.result.request_id == "req-1" + + +def test_submit_rejects_local_file_and_file_uri_before_sdk_upload( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + local_file = tmp_path / "secret.png" + local_file.write_bytes(b"secret") + + def forbid_call(*_args: Any, **_kwargs: Any) -> Any: + msg = "SDK upload or HTTP transport must not run for disallowed schemes" + raise AssertionError(msg) + + model = model_factory() + monkeypatch.setattr("dashscope.resources.videos.upload_media_value", forbid_call) + monkeypatch.setattr(model._client().transport, "request", forbid_call) + monkeypatch.setattr(model._client().transport, "request_api", forbid_call) Review Comment: Done. Added `raising=False` to the `request_api` monkeypatch in `test_dashscope_video_generation.py` so it works on DashScope 2.0.4. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
