dashscope 1.24.2__py3-none-any.whl → 1.24.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dashscope might be problematic. Click here for more details.

@@ -4,9 +4,8 @@ from typing import Any, Dict, Union
4
4
 
5
5
  from dashscope.api_entities.dashscope_response import (DashScopeAPIResponse,
6
6
  VideoSynthesisResponse)
7
- from dashscope.client.base_api import BaseAsyncApi
7
+ from dashscope.client.base_api import BaseAsyncApi, BaseAsyncAioApi
8
8
  from dashscope.common.constants import PROMPT
9
- from dashscope.common.error import InputRequired
10
9
  from dashscope.common.utils import _get_task_group_and_task
11
10
  from dashscope.utils.oss_utils import check_and_upload_local
12
11
 
@@ -91,7 +90,7 @@ class VideoSynthesis(BaseAsyncApi):
91
90
  **kwargs)
92
91
 
93
92
  @classmethod
94
- def async_call(cls,
93
+ def _get_input(cls,
95
94
  model: str,
96
95
  prompt: Any = None,
97
96
  img_url: str = None,
@@ -101,41 +100,14 @@ class VideoSynthesis(BaseAsyncApi):
101
100
  template: str = None,
102
101
  api_key: str = None,
103
102
  extra_input: Dict = None,
104
- workspace: str = None,
105
103
  task: str = None,
104
+ function: str = None,
106
105
  head_frame: str = None,
107
106
  tail_frame: str = None,
108
107
  first_frame_url: str = None,
109
108
  last_frame_url: str = None,
110
- **kwargs) -> VideoSynthesisResponse:
111
- """Create a video synthesis task, and return task information.
112
-
113
- Args:
114
- model (str): The model, reference ``Models``.
115
- prompt (Any): The prompt for video synthesis.
116
- extend_prompt (bool): @deprecated, use prompt_extend in parameters
117
- negative_prompt (str): The negative prompt is the opposite of the prompt meaning.
118
- template (str): LoRa input, such as gufeng, katong, etc.
119
- img_url (str): The input image url, Generate the URL of the image referenced by the video.
120
- api_key (str, optional): The api api_key. Defaults to None.
121
- workspace (str): The dashscope workspace id.
122
- extra_input (Dict): The extra input parameters.
123
- task (str): The task of api, ref doc.
124
- first_frame_url (str): The URL of the first frame image for generating the video.
125
- last_frame_url (str): The URL of the last frame image for generating the video.
126
- **kwargs:
127
- size(str, `optional`): The output video size(width*height).
128
- duration(int, optional): The duration. Duration of video generation. The default value is 5, in seconds.
129
- seed(int, optional): The seed. The random seed for video generation. The default value is 5.
109
+ **kwargs):
130
110
 
131
- Raises:
132
- InputRequired: The prompt cannot be empty.
133
-
134
- Returns:
135
- DashScopeAPIResponse: The video synthesis
136
- task id in the response.
137
- """
138
- task_group, function = _get_task_group_and_task(__name__)
139
111
  inputs = {PROMPT: prompt, 'extend_prompt': extend_prompt}
140
112
  if negative_prompt:
141
113
  inputs['negative_prompt'] = negative_prompt
@@ -192,6 +164,61 @@ class VideoSynthesis(BaseAsyncApi):
192
164
  task = VideoSynthesis.task
193
165
  if model is not None and model and 'kf2v' in model:
194
166
  task = 'image2video'
167
+
168
+ return inputs, kwargs, task
169
+
170
+ @classmethod
171
+ def async_call(cls,
172
+ model: str,
173
+ prompt: Any = None,
174
+ img_url: str = None,
175
+ # """@deprecated, use prompt_extend in parameters """
176
+ extend_prompt: bool = True,
177
+ negative_prompt: str = None,
178
+ template: str = None,
179
+ api_key: str = None,
180
+ extra_input: Dict = None,
181
+ workspace: str = None,
182
+ task: str = None,
183
+ head_frame: str = None,
184
+ tail_frame: str = None,
185
+ first_frame_url: str = None,
186
+ last_frame_url: str = None,
187
+ **kwargs) -> VideoSynthesisResponse:
188
+ """Create a video synthesis task, and return task information.
189
+
190
+ Args:
191
+ model (str): The model, reference ``Models``.
192
+ prompt (Any): The prompt for video synthesis.
193
+ extend_prompt (bool): @deprecated, use prompt_extend in parameters
194
+ negative_prompt (str): The negative prompt is the opposite of the prompt meaning.
195
+ template (str): LoRa input, such as gufeng, katong, etc.
196
+ img_url (str): The input image url, Generate the URL of the image referenced by the video.
197
+ api_key (str, optional): The api api_key. Defaults to None.
198
+ workspace (str): The dashscope workspace id.
199
+ extra_input (Dict): The extra input parameters.
200
+ task (str): The task of api, ref doc.
201
+ first_frame_url (str): The URL of the first frame image for generating the video.
202
+ last_frame_url (str): The URL of the last frame image for generating the video.
203
+ **kwargs:
204
+ size(str, `optional`): The output video size(width*height).
205
+ duration(int, optional): The duration. Duration of video generation. The default value is 5, in seconds.
206
+ seed(int, optional): The seed. The random seed for video generation. The default value is 5.
207
+
208
+ Raises:
209
+ InputRequired: The prompt cannot be empty.
210
+
211
+ Returns:
212
+ DashScopeAPIResponse: The video synthesis
213
+ task id in the response.
214
+ """
215
+ task_group, function = _get_task_group_and_task(__name__)
216
+
217
+ inputs, kwargs, task = cls._get_input(
218
+ model, prompt, img_url, extend_prompt, negative_prompt, template, api_key,
219
+ extra_input, task, function, head_frame, tail_frame,
220
+ first_frame_url, last_frame_url, **kwargs)
221
+
195
222
  response = super().async_call(
196
223
  model=model,
197
224
  task_group=task_group,
@@ -305,3 +332,225 @@ class VideoSynthesis(BaseAsyncApi):
305
332
  api_key=api_key,
306
333
  workspace=workspace,
307
334
  **kwargs)
335
+
336
+ class AioVideoSynthesis(BaseAsyncAioApi):
337
+ @classmethod
338
+ async def call(cls,
339
+ model: str,
340
+ prompt: Any = None,
341
+ img_url: str = None,
342
+ # """@deprecated, use prompt_extend in parameters """
343
+ extend_prompt: bool = True,
344
+ negative_prompt: str = None,
345
+ template: str = None,
346
+ api_key: str = None,
347
+ extra_input: Dict = None,
348
+ workspace: str = None,
349
+ task: str = None,
350
+ head_frame: str = None,
351
+ tail_frame: str = None,
352
+ first_frame_url: str = None,
353
+ last_frame_url: str = None,
354
+ **kwargs) -> VideoSynthesisResponse:
355
+ """Call video synthesis service and get result.
356
+
357
+ Args:
358
+ model (str): The model, reference ``Models``.
359
+ prompt (Any): The prompt for video synthesis.
360
+ extend_prompt (bool): @deprecated, use prompt_extend in parameters
361
+ negative_prompt (str): The negative prompt is the opposite of the prompt meaning.
362
+ template (str): LoRa input, such as gufeng, katong, etc.
363
+ img_url (str): The input image url, Generate the URL of the image referenced by the video.
364
+ api_key (str, optional): The api api_key. Defaults to None.
365
+ workspace (str): The dashscope workspace id.
366
+ extra_input (Dict): The extra input parameters.
367
+ task (str): The task of api, ref doc.
368
+ first_frame_url (str): The URL of the first frame image for generating the video.
369
+ last_frame_url (str): The URL of the last frame image for generating the video.
370
+ **kwargs:
371
+ size(str, `optional`): The output video size(width*height).
372
+ duration(int, optional): The duration. Duration of video generation. The default value is 5, in seconds.
373
+ seed(int, optional): The seed. The random seed for video generation. The default value is 5.
374
+
375
+ Raises:
376
+ InputRequired: The prompt cannot be empty.
377
+
378
+ Returns:
379
+ VideoSynthesisResponse: The video synthesis result.
380
+ """
381
+ task_group, f = _get_task_group_and_task(__name__)
382
+ inputs, kwargs, task = VideoSynthesis._get_input(
383
+ model, prompt, img_url, extend_prompt, negative_prompt, template, api_key,
384
+ extra_input, task, f, head_frame, tail_frame,
385
+ first_frame_url, last_frame_url, **kwargs)
386
+ response = await super().call(model, inputs, task_group, task, f, api_key, workspace, **kwargs)
387
+ return VideoSynthesisResponse.from_api_response(response)
388
+
389
+ @classmethod
390
+ async def async_call(cls,
391
+ model: str,
392
+ prompt: Any = None,
393
+ img_url: str = None,
394
+ # """@deprecated, use prompt_extend in parameters """
395
+ extend_prompt: bool = True,
396
+ negative_prompt: str = None,
397
+ template: str = None,
398
+ api_key: str = None,
399
+ extra_input: Dict = None,
400
+ workspace: str = None,
401
+ task: str = None,
402
+ head_frame: str = None,
403
+ tail_frame: str = None,
404
+ first_frame_url: str = None,
405
+ last_frame_url: str = None,
406
+ **kwargs) -> VideoSynthesisResponse:
407
+ """Create a video synthesis task, and return task information.
408
+
409
+ Args:
410
+ model (str): The model, reference ``Models``.
411
+ prompt (Any): The prompt for video synthesis.
412
+ extend_prompt (bool): @deprecated, use prompt_extend in parameters
413
+ negative_prompt (str): The negative prompt is the opposite of the prompt meaning.
414
+ template (str): LoRa input, such as gufeng, katong, etc.
415
+ img_url (str): The input image url, Generate the URL of the image referenced by the video.
416
+ api_key (str, optional): The api api_key. Defaults to None.
417
+ workspace (str): The dashscope workspace id.
418
+ extra_input (Dict): The extra input parameters.
419
+ task (str): The task of api, ref doc.
420
+ first_frame_url (str): The URL of the first frame image for generating the video.
421
+ last_frame_url (str): The URL of the last frame image for generating the video.
422
+ **kwargs:
423
+ size(str, `optional`): The output video size(width*height).
424
+ duration(int, optional): The duration. Duration of video generation. The default value is 5, in seconds.
425
+ seed(int, optional): The seed. The random seed for video generation. The default value is 5.
426
+
427
+ Raises:
428
+ InputRequired: The prompt cannot be empty.
429
+
430
+ Returns:
431
+ DashScopeAPIResponse: The video synthesis
432
+ task id in the response.
433
+ """
434
+ task_group, function = _get_task_group_and_task(__name__)
435
+
436
+ inputs, kwargs, task = VideoSynthesis._get_input(
437
+ model, prompt, img_url, extend_prompt, negative_prompt, template, api_key,
438
+ extra_input, task, function, head_frame, tail_frame,
439
+ first_frame_url, last_frame_url, **kwargs)
440
+
441
+ response = await super().async_call(
442
+ model=model,
443
+ task_group=task_group,
444
+ task=VideoSynthesis.task if task is None else task,
445
+ function=function,
446
+ api_key=api_key,
447
+ input=inputs,
448
+ workspace=workspace,
449
+ **kwargs)
450
+ return VideoSynthesisResponse.from_api_response(response)
451
+
452
+ @classmethod
453
+ async def fetch(cls,
454
+ task: Union[str, VideoSynthesisResponse],
455
+ api_key: str = None,
456
+ workspace: str = None,
457
+ **kwargs) -> VideoSynthesisResponse:
458
+ """Fetch video synthesis task status or result.
459
+
460
+ Args:
461
+ task (Union[str, VideoSynthesisResponse]): The task_id or
462
+ VideoSynthesisResponse return by async_call().
463
+ api_key (str, optional): The api api_key. Defaults to None.
464
+ workspace (str): The dashscope workspace id.
465
+
466
+ Returns:
467
+ VideoSynthesisResponse: The task status or result.
468
+ """
469
+ response = await super().fetch(task, api_key=api_key, workspace=workspace)
470
+ return VideoSynthesisResponse.from_api_response(response)
471
+
472
+ @classmethod
473
+ async def wait(cls,
474
+ task: Union[str, VideoSynthesisResponse],
475
+ api_key: str = None,
476
+ workspace: str = None,
477
+ **kwargs) -> VideoSynthesisResponse:
478
+ """Wait for video synthesis task to complete, and return the result.
479
+
480
+ Args:
481
+ task (Union[str, VideoSynthesisResponse]): The task_id or
482
+ VideoSynthesisResponse return by async_call().
483
+ api_key (str, optional): The api api_key. Defaults to None.
484
+ workspace (str): The dashscope workspace id.
485
+
486
+ Returns:
487
+ VideoSynthesisResponse: The task result.
488
+ """
489
+ response = await super().wait(task, api_key, workspace=workspace)
490
+ return VideoSynthesisResponse.from_api_response(response)
491
+
492
+ @classmethod
493
+ async def cancel(cls,
494
+ task: Union[str, VideoSynthesisResponse],
495
+ api_key: str = None,
496
+ workspace: str = None,
497
+ **kwargs) -> DashScopeAPIResponse:
498
+ """Cancel video synthesis task.
499
+ Only tasks whose status is PENDING can be canceled.
500
+
501
+ Args:
502
+ task (Union[str, VideoSynthesisResponse]): The task_id or
503
+ VideoSynthesisResponse return by async_call().
504
+ api_key (str, optional): The api api_key. Defaults to None.
505
+ workspace (str): The dashscope workspace id.
506
+
507
+ Returns:
508
+ DashScopeAPIResponse: The response data.
509
+ """
510
+ return await super().cancel(task, api_key, workspace=workspace)
511
+
512
+ @classmethod
513
+ async def list(cls,
514
+ start_time: str = None,
515
+ end_time: str = None,
516
+ model_name: str = None,
517
+ api_key_id: str = None,
518
+ region: str = None,
519
+ status: str = None,
520
+ page_no: int = 1,
521
+ page_size: int = 10,
522
+ api_key: str = None,
523
+ workspace: str = None,
524
+ **kwargs) -> DashScopeAPIResponse:
525
+ """List async tasks.
526
+
527
+ Args:
528
+ start_time (str, optional): The tasks start time,
529
+ for example: 20230420000000. Defaults to None.
530
+ end_time (str, optional): The tasks end time,
531
+ for example: 20230420000000. Defaults to None.
532
+ model_name (str, optional): The tasks model name. Defaults to None.
533
+ api_key_id (str, optional): The tasks api-key-id. Defaults to None.
534
+ region (str, optional): The service region,
535
+ for example: cn-beijing. Defaults to None.
536
+ status (str, optional): The status of tasks[PENDING,
537
+ RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
538
+ page_no (int, optional): The page number. Defaults to 1.
539
+ page_size (int, optional): The page size. Defaults to 10.
540
+ api_key (str, optional): The user api-key. Defaults to None.
541
+ workspace (str): The dashscope workspace id.
542
+
543
+ Returns:
544
+ DashScopeAPIResponse: The response data.
545
+ """
546
+ return await super().list(start_time=start_time,
547
+ end_time=end_time,
548
+ model_name=model_name,
549
+ api_key_id=api_key_id,
550
+ region=region,
551
+ status=status,
552
+ page_no=page_no,
553
+ page_size=page_size,
554
+ api_key=api_key,
555
+ workspace=workspace,
556
+ **kwargs)
@@ -127,4 +127,4 @@ def _build_api_request(model: str,
127
127
  request_data.add_resources(resources)
128
128
  request_data.add_parameters(**kwargs)
129
129
  request.data = request_data
130
- return request
130
+ return request
@@ -445,8 +445,8 @@ class ImageSynthesisOutput(DictMixin):
445
445
  results: List[ImageSynthesisResult]
446
446
 
447
447
  def __init__(self,
448
- task_id: str,
449
- task_status: str,
448
+ task_id: str = None,
449
+ task_status: str = None,
450
450
  results: List[ImageSynthesisResult] = [],
451
451
  **kwargs):
452
452
  res = []
@@ -1,10 +1,12 @@
1
1
  # Copyright (c) Alibaba, Inc. and its affiliates.
2
-
2
+ import datetime
3
3
  import json
4
+ import ssl
4
5
  from http import HTTPStatus
5
6
  from typing import Optional
6
7
 
7
8
  import aiohttp
9
+ import certifi
8
10
  import requests
9
11
 
10
12
  from dashscope.api_entities.base_request import AioBaseRequest
@@ -119,12 +121,18 @@ class HttpRequest(AioBaseRequest):
119
121
 
120
122
  async def _handle_aio_request(self):
121
123
  try:
124
+ connector = aiohttp.TCPConnector(
125
+ ssl=ssl.create_default_context(
126
+ cafile=certifi.where()))
122
127
  async with aiohttp.ClientSession(
128
+ connector=connector,
123
129
  timeout=aiohttp.ClientTimeout(total=self.timeout),
124
130
  headers=self.headers) as session:
125
131
  logger.debug('Starting request: %s' % self.url)
126
132
  if self.method == HTTPMethod.POST:
127
- is_form, obj = self.data.get_aiohttp_payload()
133
+ is_form, obj = False, {}
134
+ if hasattr(self, 'data') and self.data is not None:
135
+ is_form, obj = self.data.get_aiohttp_payload()
128
136
  if is_form:
129
137
  headers = {**self.headers, **obj.headers}
130
138
  response = await session.post(url=self.url,
@@ -136,8 +144,14 @@ class HttpRequest(AioBaseRequest):
136
144
  json=obj,
137
145
  headers=self.headers)
138
146
  elif self.method == HTTPMethod.GET:
147
+ # 添加条件判断
148
+ params = {}
149
+ if hasattr(self, 'data') and self.data is not None:
150
+ params = getattr(self.data, 'parameters', {})
151
+ if params:
152
+ params = self.__handle_parameters(params)
139
153
  response = await session.get(url=self.url,
140
- params=self.data.parameters,
154
+ params=params,
141
155
  headers=self.headers)
142
156
  else:
143
157
  raise UnsupportedHTTPMethod('Unsupported http method: %s' %
@@ -153,6 +167,32 @@ class HttpRequest(AioBaseRequest):
153
167
  logger.error(e)
154
168
  raise e
155
169
 
170
+ @staticmethod
171
+ def __handle_parameters(params: dict) -> dict:
172
+ def __format(value):
173
+ if isinstance(value, bool):
174
+ return str(value).lower()
175
+ elif isinstance(value, (str, int, float)):
176
+ return value
177
+ elif value is None:
178
+ return ''
179
+ elif isinstance(value, (datetime.datetime, datetime.date)):
180
+ return value.isoformat()
181
+ elif isinstance(value, (list, tuple)):
182
+ return ','.join(str(__format(x)) for x in value)
183
+ elif isinstance(value, dict):
184
+ return json.dumps(value)
185
+ else:
186
+ try:
187
+ return str(value)
188
+ except Exception as e:
189
+ raise ValueError(f"Unsupported type {type(value)} for param formatting: {e}")
190
+
191
+ formatted = {}
192
+ for k, v in params.items():
193
+ formatted[k] = __format(v)
194
+ return formatted
195
+
156
196
  async def _handle_aio_response(self, response: aiohttp.ClientResponse):
157
197
  request_id = ''
158
198
  if (response.status == HTTPStatus.OK and self.stream
@@ -211,6 +251,12 @@ class HttpRequest(AioBaseRequest):
211
251
  usage = None
212
252
  if 'output' in json_content and json_content['output'] is not None:
213
253
  output = json_content['output']
254
+ # Compatible with wan
255
+ elif 'data' in json_content and json_content['data'] is not None\
256
+ and isinstance(json_content['data'], list)\
257
+ and len(json_content['data']) > 0\
258
+ and 'task_id' in json_content['data'][0]:
259
+ output = json_content
214
260
  if 'usage' in json_content:
215
261
  usage = json_content['usage']
216
262
  if 'request_id' in json_content: