Best practices for using video understanding and one-click video creation
This topic describes how to use the video understanding and one-click video creation features of Quanmiao to generate short videos from long videos and perform video imitation.
Required Alibaba Cloud products
-
Alibaba Cloud Model Studio > App Square > Film and Media Video Understanding
-
Quanmiao - Team Standard Edition or later > One-click Video Creation
Workflow for creating short videos from long videos
Overall approach
-
Source material: One long video.
-
Objective: To edit a short video.
-
Method:
- Use the Film and Media Video Understanding application to analyze the long video and generate a short video script based on the analysis results.
- Use the generated short video script and the long video as inputs for One-click Video Creation to generate a short video.
Procedure
Create Function Compute functions
Create two Function Compute functions. One function calls the video understanding application, and the other calls the one-click video creation feature of Quanmiao.
1.1 Video understanding function
Create an event-triggered function. Select Python 3.10 as the programming language and set the runtime timeout to 600 s.
-
On the code editor page, you can install the SDK for the video understanding application in the terminal.
Note: The period (.) at the end of the sample code indicates installation to the current directory. Do not omit it.
pip install alibabacloud-tea-openapi-sse==1.0.2 -t .
- The following sample code is for reference. To ensure that the code runs correctly and returns the expected results, replace the AK and SK and the workspaceId with your actual values.
# -*- coding: utf-8 -*-
import logging
import json
from alibabacloud_tea_openapi_sse.client import Client as OpenApiClient
from alibabacloud_tea_openapi_sse import models as open_api_models
from alibabacloud_tea_util_sse import models as util_models
import asyncio
# To enable the initializer feature (https://help.aliyun.com/en/functioncompute/lifecycle-hooks-for-function-instances-1
# please implement the initializer function as below:
# def initializer(context):
# logger = logging.getLogger()
# logger.info('initializing')
class LightApp:
def __init__(self, ak, sk, token, workspace_id, videoUrl, vlPrompt, llmPrompt) -> None:
# Leaking project code may expose your AccessKey and compromise the security of all resources under your account. The following sample code is for reference only.
# We recommend using a more secure method, such as Security Token Service (STS). For more information about authentication methods, see: https://help.aliyun.com/en/sdk/developer-reference/v2-manage-python-access-credentials
self.access_key_id = ak
self.access_key_secret = sk
self.token = token
self.videoUrl = videoUrl
self.videoModelCustomPromptTemplate = vlPrompt
self.modelCustomPromptTemplate = llmPrompt
self.workspace_id = workspace_id
# Replace the preceding fields with your actual values.
self.endpoint = 'quanmiaolightapp.cn-beijing.aliyuncs.com'
self._client = None
self._api_info = self._create_api_info()
self._runtime = util_models.RuntimeOptions(read_timeout=1000 * 100)
self._client = self._create_client(self.access_key_id, self.access_key_secret, self.token, self.endpoint)
def _create_client(
self,
access_key_id: str,
access_key_secret: str,
token: str,
endpoint: str,
) -> OpenApiClient:
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret,
endpoint=endpoint
)
return OpenApiClient(config)
def _create_api_info(self) -> open_api_models.Params:
"""
API information
@param path: params
@return: OpenApi.Params
"""
params = open_api_models.Params(
# API name
action='RunVideoAnalysis',
# API version
version='2024-08-01',
# API protocol
protocol='HTTPS',
# HTTP method
method='POST',
auth_type='AK',
style='RPC',
# API path,
pathname='/'+self.workspace_id+'/quanmiao/lightapp/runVideoAnalysis',
# Request body format,
req_body_type='formData',
# Response body format,
body_type='sse'
)
return params
async def do_sse_query(self):
body = {
'videoUrl': self.videoUrl,
"videoModelId":"qwen3-vl-plus", # Model list: https://help.aliyun.com/en/model-studio/models
"videoModelCustomPromptTemplate": self.videoModelCustomPromptTemplate,
"modelCustomPromptTemplate": self.modelCustomPromptTemplate
}
request = open_api_models.OpenApiRequest(
body=body
)
sse_receiver = self._client.call_sse_api_async(params=self._api_info, request=request, runtime=self._runtime)
return sse_receiver
# API call
async def run(fc_event, context):
creds = context.credentials
event_obj = json.loads(fc_event)
light_app = LightApp(creds.access_key_id, creds.access_key_secret, creds.security_token, creds.workspace_id, event_obj['videoUrl'], event_obj['vlPrompt'], event_obj['llmPrompt'])
async for res in await light_app.do_sse_query():
try:
data = json.loads(res.get('event').data)
header = data['header']
event = header['event']
if event == 'task-finished':
print(data['payload']['output']['videoGenerateResult']['text'])
return data['payload']['output']['videoGenerateResult']['text']
except json.JSONDecodeError:
print('------json.JSONDecodeError--------')
print(res.get('headers'))
print(res.get('event').data)
print('------json.JSONDecodeError-end--------')
continue
print('------end--------')
def handler(event, context):
# evt = json.loads(event)
logger = logging.getLogger()
logger.info(event)
result = asyncio.run(run(event, context))
return {'videoContent':result}
1.2 One-click video creation function
Create an event-triggered function. Select Python 3.10 as the programming language and set the runtime timeout to 600 s.
-
On the code editor page, you can install the SDK in the terminal.
Note: The period (.) at the end of the sample code indicates installation to the current directory. Do not omit it.
pip install alibabacloud-tea-openapi -t .
- The following sample code is for reference. To ensure that the code runs correctly and returns the expected results, replace the AK and SK and the workspaceId with your actual values.
# -*- coding: utf-8 -*-
import logging
import json
import time
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
class AiMiaoBi:
def __init__(self, ak, sk, token, workspace_id) -> None:
# Leaking project code may expose your AccessKey and compromise the security of all resources under your account. The following sample code is for reference only.
# We recommend using a more secure method, such as Security Token Service (STS). For more information about authentication methods, see: https://help.aliyun.com/en/sdk/developer-reference/v2-manage-python-access-credentials
self.access_key_id = ak
self.access_key_secret = sk
self.workspace_id = workspace_id
# Replace the preceding fields with your actual values.
self.endpoint = 'aimiaobi.cn-beijing.aliyuncs.com'
self._client = None
self.token = token
self._submit_api_info = self._create_submit_api_info()
self._get_status_api_info = self._create_get_status_api_info()
self._runtime = util_models.RuntimeOptions(read_timeout=1000 * 100)
self._client = self._create_client(self.access_key_id, self.access_key_secret, self.token, self.endpoint)
def _create_client(
self,
access_key_id: str,
access_key_secret: str,
token: str,
endpoint: str,
) -> OpenApiClient:
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret,
endpoint=endpoint
)
return OpenApiClient(config)
def _create_submit_api_info(self) -> open_api_models.Params:
"""
API information
@param path: params
@return: OpenApi.Params
"""
params = open_api_models.Params(
# API name
action='SubmitSmartClipTask',
# API version
version='2023-08-01',
# API protocol
protocol='HTTPS',
# HTTP method
method='POST',
auth_type='AK',
style='RPC',
# API path,
pathname='/',
# Request body format,
req_body_type='formData',
# Response body format,
body_type='json'
)
return params
def _create_get_status_api_info(self) -> open_api_models.Params:
params = open_api_models.Params(
# API name
action='GetSmartClipTask',
# API version
version='2023-08-01',
# API protocol
protocol='HTTPS',
# HTTP method
method='POST',
auth_type='AK',
style='RPC',
# API path,
pathname='/',
# Request body format,
req_body_type='formData',
# Response body format,
body_type='json'
)
return params
def do_submit(self, video_url, speech):
input_config = {
"VideoIds": [
{
"Type": "url",
"Id": video_url
}
],
"SpeechTexts": [
speech
]
}
output_config = {
"FileName": "test_{index}",
"SaveToGeneratedContent": True
}
body = {
"WorkspaceId": self.workspace_id,
"InputConfig": json.dumps(input_config),
"OutputConfig": json.dumps(output_config)
}
request = open_api_models.OpenApiRequest(
body=body
)
response = self._client.call_api(params=self._submit_api_info, request=request, runtime=self._runtime)
print(response)
resp_body = response['body']
task_id = resp_body['Data']['TaskId']
return task_id
def do_check_status(self, task_id):
body = {
"WorkspaceId": self.workspace_id,
"TaskId": task_id
}
request = open_api_models.OpenApiRequest(
body=body
)
response = self._client.call_api(params=self._get_status_api_info, request=request, runtime=self._runtime)
print(response)
resp_body = response['body']
return resp_body
# API call
def run(video_url, speech, context):
creds = context.credentials
ai_miaobi = AiMiaoBi(creds.access_key_id, creds.access_key_secret, creds.security_token, creds.workspace_id)
task_id = ai_miaobi.do_submit(video_url, speech)
max_wait_time = 1800 # Maximum wait time: 1800 seconds
poll_interval = 15 # Polling interval: 15 seconds
elapsed_time = 0
while elapsed_time < max_wait_time:
resp_body = ai_miaobi.do_check_status(task_id)
status = resp_body['Data']['Status']
if status == "SUCCESSED":
output_url = resp_body['Data']['SubJobs'][0]['FileAttr']['TmpUrl']
return output_url
time.sleep(poll_interval)
elapsed_time += poll_interval
raise Exception(f"Task timeout after {max_wait_time} seconds")
def handler(event, context):
evt = json.loads(event)
logger = logging.getLogger()
logger.info(event)
outputUrl = run(evt['videoUrl'], evt['speech'], context)
return {'outputUrl': outputUrl}
1.3 One-click video creation function that supports multiple source materials
# -*- coding: utf-8 -*-
import logging
import json
import time
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
class AiMiaoBi:
def __init__(self, ak, sk, token, workspace_id) -> None:
# Leaking project code may expose your AccessKey and compromise the security of all resources under your account. The following sample code is for reference only.
# We recommend using a more secure method, such as Security Token Service (STS). For more information about authentication methods, see: https://help.aliyun.com/en/sdk/developer-reference/v2-manage-python-access-credentials
self.access_key_id = ak
self.access_key_secret = sk
self.workspace_id = workspace_id
# Replace the preceding fields with your actual values.
self.endpoint = 'aimiaobi.cn-beijing.aliyuncs.com'
self._client = None
self.token = token
self._submit_api_info = self._create_submit_api_info()
self._get_status_api_info = self._create_get_status_api_info()
self._runtime = util_models.RuntimeOptions(read_timeout=1000 * 100)
self._client = self._create_client(self.access_key_id, self.access_key_secret, self.token, self.endpoint)
def _create_client(
self,
access_key_id: str,
access_key_secret: str,
token: str,
endpoint: str,
) -> OpenApiClient:
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret,
endpoint=endpoint
)
return OpenApiClient(config)
def _create_submit_api_info(self) -> open_api_models.Params:
"""
API information
@param path: params
@return: OpenApi.Params
"""
params = open_api_models.Params(
# API name
action='SubmitSmartClipTask',
# API version
version='2023-08-01',
# API protocol
protocol='HTTPS',
# HTTP method
method='POST',
auth_type='AK',
style='RPC',
# API path,
pathname='/',
# Request body format,
req_body_type='formData',
# Response body format,
body_type='json'
)
return params
def _create_get_status_api_info(self) -> open_api_models.Params:
params = open_api_models.Params(
# API name
action='GetSmartClipTask',
# API version
version='2023-08-01',
# API protocol
protocol='HTTPS',
# HTTP method
method='POST',
auth_type='AK',
style='RPC',
# API path,
pathname='/',
# Request body format,
req_body_type='formData',
# Response body format,
body_type='json'
)
return params
def do_submit(self, video_material_urls, speech):
input_config = {
"VideoIds": [
{
"Type": "url",
"Id": video_url
}
for video_url in video_material_urls
],
"SpeechTexts": [
speech
]
}
output_config = {
"FileName": "test_{index}",
"SaveToGeneratedContent": True
}
body = {
"WorkspaceId": self.workspace_id,
"InputConfig": json.dumps(input_config),
"OutputConfig": json.dumps(output_config)
}
request = open_api_models.OpenApiRequest(
body=body
)
response = self._client.call_api(params=self._submit_api_info, request=request, runtime=self._runtime)
print(response)
resp_body = response['body']
task_id = resp_body['Data']['TaskId']
return task_id
def do_check_status(self, task_id):
body = {
"WorkspaceId": self.workspace_id,
"TaskId": task_id
}
request = open_api_models.OpenApiRequest(
body=body
)
response = self._client.call_api(params=self._get_status_api_info, request=request, runtime=self._runtime)
print(response)
resp_body = response['body']
return resp_body
# API call
def run(video_material_urls, speech, context):
creds = context.credentials
ai_miaobi = AiMiaoBi(creds.access_key_id, creds.access_key_secret, creds.security_token, creds.workspace_id)
task_id = ai_miaobi.do_submit(video_material_urls, speech)
max_wait_time = 1800 # Maximum wait time: 1800 seconds
poll_interval = 15 # Polling interval: 15 seconds
elapsed_time = 0
while elapsed_time < max_wait_time:
resp_body = ai_miaobi.do_check_status(task_id)
status = resp_body['Data']['Status']
if status == "SUCCESSED":
output_url = resp_body['Data']['SubJobs'][0]['FileAttr']['TmpUrl']
return output_url
time.sleep(poll_interval)
elapsed_time += poll_interval
raise Exception(f"Task timeout after {max_wait_time} seconds")
def handler(event, context):
evt = json.loads(event)
logger = logging.getLogger()
logger.info(event)
outputUrl = run(evt['videoMaterialUrls'], evt['speech'], context)
return {'outputUrl': outputUrl}
Create a CloudFlow
After you create a CloudFlow instance, you can copy the following YAML file for configuration. This saves you from configuring the workflow from scratch.
Replace
${ALIUID},${VIDEO_ANALYSIS_FUNCTION_NAME}, and${VIDEO_CUT_FUNCTION_NAME}with your account ID and the names of the two Function Compute functions.
Workflow that supports one source material:
Type: StateMachine
Name: video_edit
SpecVersion: v1
StartAt: Video Understanding
States:
- Type: Task
Name: Video Understanding
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_ANALYSIS_FUNCTION_NAME}/LATEST
body:
videoUrl.$: $Input.videoUrl
vlPrompt.$: $Input.vlPrompt
llmPrompt.$: $Input.llmPrompt
OutputConstructor:
returnID.$: uuid()
videoContent.$: $Output.Body.videoContent
Next: One-click Video Creation
- Type: Task
Name: One-click Video Creation
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_CUT_FUNCTION_NAME}/LATEST
body:
videoUrl.$: $Context.Execution.Input.videoUrl
speech.$: $Input.videoContent
OutputConstructor:
outputUrl.$: $Output.Body.outputUrl
Next: Succeed
- Type: Succeed
Name: Succeed
End: true
Workflows for multiple source materials:
Type: StateMachine
Name: video_learning
SpecVersion: v1
StartAt: Video Understanding
States:
- Type: Task
Name: Video Understanding
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_ANALYSIS_FUNCTION_NAME}/LATEST
body:
videoUrl.$: $Input.videoUrl
vlPrompt.$: $Input.vlPrompt
llmPrompt.$: $Input.llmPrompt
OutputConstructor:
returnID.$: uuid()
videoContent.$: $Output.Body.videoContent
Next: One-click Video Creation
- Type: Task
Name: One-click Video Creation
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_CUT_FUNCTION_NAME}/LATEST
body:
videoMaterialUrls.$: $Context.Execution.Input.videoMaterialUrls
speech.$: $Input.videoContent
OutputConstructor:
outputUrl.$: $Output.Body.outputUrl
Next: Succeed
- Type: Succeed
Name: Succeed
End: true
Start a workflow execution
For a single source, refer to the following input parameters:
{
"videoUrl": "https://abc.com/xyz.mp4",
"vlPrompt": "# Role\nYou are a video analyst who excels at understanding various video clips.\n\n# Task Description\nGiven multiple keyframes from a video clip, complete the following tasks.\n- Output the visual information for each image, including people, objects, actions, text, captions, camera language, and a one-sentence summary.\n- Combine the information from each image to generate a detailed summary of the video, reconstructing the plot of the clip.\n\n# Constraints\n- The analysis must be strictly limited to the provided video sub-clip. Do not include any speculation or background information beyond the video.\n- The summary must be strictly based on the video content. Do not add personal speculation or creative content.\n- Maintain high-fidelity reproduction of all video elements, especially text and captions, to avoid information loss or misunderstanding.\n\n# Input Data\n## ASR information for the video clip (ignore if the input is empty)\n{videoAsrText}\n\n## Supplementary video information (this may help you understand the clip; ignore if the input is empty)\n{videoExtraInfo}\n\n# Output Format\nFollow the task objectives directly. First, output the description for each image, then combine them to output the plot of the entire video clip.",
"llmPrompt": "# Role\nYou are a professional video annotator who excels at analyzing and processing various video tasks by combining video shot information.\n\n# Task Objective\nCombine the input data to reconstruct the detailed plot of the entire video.\n\n# Constraints\n1. If there are grammatical errors or logical inconsistencies, correct them directly.\n2. In the video storyboard, if dialogue is present, the speaker may not match the spoken content. Therefore, you must accurately identify the true speaker based on the plot's progression.\n3. If there is no dialogue in the storyboard, match dialogue to it based on the video's audio and text.\n4. The revised story should appropriately retain the descriptions of characters and scenes from the storyboard.\n5. Polish the story to make it more logical.\n6. Based on the appearance of characters in the storyboard, if characters with similar appearances are the same person, you need to unify the character roles across different shots.\n\n# Input Data\n## Resource 1: Storyboard information (visual descriptions of each shot in the video)\n{videoAnalysisText}\n\n## Resource 2: Video ASR transcription information (speaker is not labeled; may contain errors and omissions; ignore this information if no ASR is provided)\n{videoAsrText}\n\n## Resource 3: Supplementary video information (ignore if the input is empty)\n{videoExtraInfo}\n\n# Output Format\nDirectly output the video plot. Do not output any other information."
}
For multiple sources, refer to the following input parameters:
{
"videoUrl": "https://goods-test1.oss-cn-hangzhou.aliyuncs.com/taishan.mp4?Expires=1733739990&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
"vlPrompt": "# Role\nYou are a video analyst who excels at understanding various video clips.\n\n# Task Description\nGiven multiple keyframes from a video clip, complete the following tasks.\n- Output the visual information for each image, including people, objects, actions, text, captions, camera language, and a one-sentence summary.\n- Combine the information from each image to generate a detailed summary of the video, reconstructing the plot of the clip.\n\n# Constraints\n- The analysis must be strictly limited to the provided video sub-clip. Do not include any speculation or background information beyond the video.\n- The summary must be strictly based on the video content. Do not add personal speculation or creative content.\n- Maintain high-fidelity reproduction of all video elements, especially text and captions, to avoid information loss or misunderstanding.\n\n# Input Data\n## ASR information for the video clip (ignore if the input is empty)\n{videoAsrText}\n\n## Supplementary video information (this may help you understand the clip; ignore if the input is empty)\n{videoExtraInfo}\n\n# Output Format\nFollow the task objectives directly. First, output the description for each image, then combine them to output the plot of the entire video clip.",
"llmPrompt": "# Role\nYou are a professional video annotator who excels at analyzing and processing various video tasks by combining video shot information.\n\n# Task Objective\nCombine the input data to reconstruct the detailed plot of the entire video.\n\n# Constraints\n1. If there are grammatical errors or logical inconsistencies, correct them directly.\n2. In the video storyboard, if dialogue is present, the speaker may not match the spoken content. Therefore, you must accurately identify the true speaker based on the plot's progression.\n3. If there is no dialogue in the storyboard, match dialogue to it based on the video's audio and text.\n4. The revised story should appropriately retain the descriptions of characters and scenes from the storyboard.\n5. Polish the story to make it more logical.\n6. Based on the appearance of characters in the storyboard, if characters with similar appearances are the same person, you need to unify the character roles across different shots.\n\n# Input Data\n## Resource 1: Storyboard information (visual descriptions of each shot in the video)\n{videoAnalysisText}\n\n## Resource 2: Video ASR transcription information (speaker is not labeled; may contain errors and omissions; ignore this information if no ASR is provided)\n{videoAsrText}\n\n## Resource 3: Supplementary video information (ignore if the input is empty)\n{videoExtraInfo}\n\n# Output Format\nDirectly output the video plot. Do not output any other information.",
"videoMaterialUrls": [
"https://goods-test1.oss-cn-hangzhou.aliyuncs.com/huangshan.mp4?Expires=1733740025&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE"
]
}
Video imitation workflow
Overall approach
-
Source materials: A sample video and a collection of source videos.
-
Objective: Replicate the style of the sample video by intelligently editing the source videos.
-
Method:
- Analyze the sample video to understand its structure and voiceover script style. Then, review the source videos to familiarize yourself with the available content.
- Use a large language model (LLM) to generate a new voiceover script. The script should be based on the structure of the sample video and the content of the source videos.
- Use the one-click video creation feature to intelligently edit the source videos.
Workflow definition
- Replace
${API_KEY}on line 65 with the large model's API key. - Replace
${ALIUID},${VIDEO_ANALYSIS_FUNCTION_NAME},${VIDEO_CUT_FUNCTION_NAME}, and${CONSTRUCT_PROMPT_FUNCTION_NAME}with your account ID and the names of the three Function Compute functions.
Type: StateMachine
Name: video_learning
SpecVersion: v1
StartAt: Parallel
States:
- Type: Parallel
Name: Parallel
Branches:
- StartAt: Source Video Understanding
States:
- Type: Task
Name: Source Video Understanding
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: >-
acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_ANALYSIS_FUNCTION_NAME}/LATEST
body:
videoUrl.$: $Input.sourceVideoUrl
vlPrompt.$: $Input.sourceVlPrompt
llmPrompt.$: $Input.sourceLlmPrompt
OutputConstructor:
returnID.$: uuid()
sourceVideoContent.$: $Output.Body.videoContent
End: true
- StartAt: Target Video Understanding
States:
- Type: Task
Name: Target Video Understanding
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
body:
videoUrl.$: $Input.targetVideoUrl
vlPrompt.$: $Input.targetVlPrompt
llmPrompt.$: $Input.targetLlmPrompt
resourceArn: >-
acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_ANALYSIS_FUNCTION_NAME}/LATEST
OutputConstructor:
returnID.$: uuid()
targetVideoContent.$: $Output.Body.videoContent
End: true
Next: Prompt Construction
- Type: Task
Name: Prompt Construction
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
body:
sourceVideoContent.$: $Input.Branch0.sourceVideoContent
targetVideoContent.$: $Input.Branch1.targetVideoContent
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${CONSTRUCT_PROMPT_FUNCTION_NAME}/LATEST
OutputConstructor:
messages.$: $Output.Body.messages
Next: Generate New Video Voiceover
- Type: Task
Name: Generate New Video Voiceover
Action: DashScope:QwenTextGeneration
TaskMode: RequestComplete
Parameters:
model: qwen-max
api_key: ${API_KEY}
enable_search: false
max_tokens: 1024
top_p: 0.8
temperature: 0.5
messages.$: $Input.messages
OutputConstructor:
speech.$: $Output.output.choices[0].message.content
Next: One-click Video Creation
- Type: Task
Name: One-click Video Creation
Action: FC:InvokeFunction
TaskMode: RequestComplete
Parameters:
invocationType: Sync
resourceArn: acs:fc:cn-shanghai:${ALIUID}:functions/${VIDEO_CUT_FUNCTION_NAME}/LATEST
body:
videoMaterialUrls.$: $Context.Execution.Input.videoMaterialUrls
speech.$: $Input.speech
OutputConstructor:
outputUrl.$: $Output.Body.outputUrl
Next: Succeed
- Type: Succeed
Name: Succeed
End: true
Create a prompt construction function
Create an event-triggered function and select Python 3.10 as the programming language.
# -*- coding: utf-8 -*-
import logging
import json
# To enable the initializer feature (https://help.aliyun.com/en/functioncompute/lifecycle-hooks-for-function-instances-1
# please implement the initializer function as below:
# def initializer(context):
# logger = logging.getLogger()
# logger.info('initializing')
def handler(event, context):
evt = json.loads(event)
logger = logging.getLogger()
prompt = '''
You are a professional video content editor.
Your task is to learn the video structure of the [Source Video]. Then, using the content of the [Target Video], write a voiceover script. This script will be used for narration after the [Target Video] is re-edited.
The structure of the [Source Video] is as follows:
{sourceVideoContent}
The content of the [Target Video] is as follows:
{targetVideoContent}
Output requirements:
Output the voiceover script for the re-edited version of the [Target Video]. The script must be about 150 words long and in a narrative style. Output only the script content.
'''.format(sourceVideoContent=evt['sourceVideoContent'], targetVideoContent=evt['targetVideoContent'])
return {"messages": [{"role":"user","content":prompt}]}
Product documentation
Billing documents
Video understanding: Film and Media Video Understanding billing
Miaobi (one-click video creation): Billing overview (Miaobi)
API documentation
Video Understanding: Film and Media Video Understanding
For information about one-click video creation, see Miaobi - One-click Video Creation.