dashscope 1.22.1__py3-none-any.whl → 1.22.2__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.
- dashscope/aigc/multimodal_conversation.py +6 -4
- dashscope/api_entities/dashscope_response.py +11 -2
- dashscope/api_entities/websocket_request.py +0 -2
- dashscope/audio/asr/transcribe.py +270 -0
- dashscope/deployment.py +163 -0
- dashscope/embeddings/multimodal_embedding.py +4 -3
- dashscope/file.py +94 -0
- dashscope/finetune.py +175 -0
- dashscope/version.py +1 -1
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/METADATA +4 -3
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/RECORD +15 -14
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/entry_points.txt +1 -0
- dashscope/aigc/chat_completion.py +0 -271
- dashscope/api_entities/chat_completion_types.py +0 -349
- dashscope/utils/temporary_storage.py +0 -160
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/LICENSE +0 -0
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/WHEEL +0 -0
- {dashscope-1.22.1.dist-info → dashscope-1.22.2.dist-info}/top_level.txt +0 -0
|
@@ -1,349 +0,0 @@
|
|
|
1
|
-
# adapter from openai sdk
|
|
2
|
-
from dataclasses import dataclass
|
|
3
|
-
from typing import Dict, List, Literal, Optional
|
|
4
|
-
|
|
5
|
-
from dashscope.common.base_type import BaseObjectMixin
|
|
6
|
-
"""
|
|
7
|
-
{
|
|
8
|
-
"choices": [
|
|
9
|
-
{
|
|
10
|
-
"message": {
|
|
11
|
-
"role": "assistant",
|
|
12
|
-
"content": "很抱歉,由于您提供的信息不完整,我无法直接比较两篇文章的内容。但是,一般而言,大型语言模型的训练通常确实涉及两个主要阶段:\n\n1. **预训练阶段 (Pre-Training Phase)**:在这个阶段,模型在大规模无标注文本数据集(如互联网上的网页、书籍、新闻等)上进行训练。目的是让模型学习语言的通用模式和结构。常见的预训练技术包括自回归(Autoregressive)模型如GPT系列,以及transformer架构下的编码器-解码器模型如BERT系列。\n\n2. **微调阶段 (Fine-Tuning Phase)**:预训练模型在特定任务的数据集上进行进一步训练,以适应下游任务,如问答、文本分类、机器翻译等。这个阶段允许模型根据具体任务的需求调整权重,从而提高性能。\n\n如果您能提供更详细的信息或两篇文章的具体内容,我可以给出更准确的比较分析。"
|
|
13
|
-
},
|
|
14
|
-
"finish_reason": "stop",
|
|
15
|
-
"index": 0,
|
|
16
|
-
"logprobs": null
|
|
17
|
-
}
|
|
18
|
-
],
|
|
19
|
-
"object": "chat.completion",
|
|
20
|
-
"usage": {
|
|
21
|
-
"prompt_tokens": 66,
|
|
22
|
-
"completion_tokens": 195,
|
|
23
|
-
"total_tokens": 261
|
|
24
|
-
},
|
|
25
|
-
"created": 1716539630,
|
|
26
|
-
"system_fingerprint": null,
|
|
27
|
-
"model": "qwen-long",
|
|
28
|
-
"id": "chatcmpl-a737071790e091c6be016ea27a891392",
|
|
29
|
-
"status_code": 200
|
|
30
|
-
}
|
|
31
|
-
"""
|
|
32
|
-
|
|
33
|
-
@dataclass(init=False)
|
|
34
|
-
class CompletionUsage(BaseObjectMixin):
|
|
35
|
-
completion_tokens: int
|
|
36
|
-
"""Number of tokens in the generated completion."""
|
|
37
|
-
|
|
38
|
-
prompt_tokens: int
|
|
39
|
-
"""Number of tokens in the prompt."""
|
|
40
|
-
|
|
41
|
-
total_tokens: int
|
|
42
|
-
"""Total number of tokens used in the request (prompt + completion)."""
|
|
43
|
-
def __init__(self, **kwargs):
|
|
44
|
-
super().__init__(**kwargs)
|
|
45
|
-
|
|
46
|
-
@dataclass(init=False)
|
|
47
|
-
class TopLogprob(BaseObjectMixin):
|
|
48
|
-
token: str
|
|
49
|
-
"""The token."""
|
|
50
|
-
|
|
51
|
-
bytes: Optional[List[int]] = None
|
|
52
|
-
"""A list of integers representing the UTF-8 bytes representation of the token.
|
|
53
|
-
|
|
54
|
-
Useful in instances where characters are represented by multiple tokens and
|
|
55
|
-
their byte representations must be combined to generate the correct text
|
|
56
|
-
representation. Can be `null` if there is no bytes representation for the token.
|
|
57
|
-
"""
|
|
58
|
-
|
|
59
|
-
logprob: float
|
|
60
|
-
"""The log probability of this token, if it is within the top 20 most likely
|
|
61
|
-
tokens.
|
|
62
|
-
|
|
63
|
-
Otherwise, the value `-9999.0` is used to signify that the token is very
|
|
64
|
-
unlikely.
|
|
65
|
-
"""
|
|
66
|
-
def __init__(self, **kwargs):
|
|
67
|
-
super().__init__(**kwargs)
|
|
68
|
-
|
|
69
|
-
@dataclass(init=False)
|
|
70
|
-
class ChatCompletionTokenLogprob(BaseObjectMixin):
|
|
71
|
-
token: str
|
|
72
|
-
"""The token."""
|
|
73
|
-
|
|
74
|
-
bytes: Optional[List[int]] = None
|
|
75
|
-
"""A list of integers representing the UTF-8 bytes representation of the token.
|
|
76
|
-
|
|
77
|
-
Useful in instances where characters are represented by multiple tokens and
|
|
78
|
-
their byte representations must be combined to generate the correct text
|
|
79
|
-
representation. Can be `null` if there is no bytes representation for the token.
|
|
80
|
-
"""
|
|
81
|
-
|
|
82
|
-
logprob: float
|
|
83
|
-
"""The log probability of this token, if it is within the top 20 most likely
|
|
84
|
-
tokens.
|
|
85
|
-
|
|
86
|
-
Otherwise, the value `-9999.0` is used to signify that the token is very
|
|
87
|
-
unlikely.
|
|
88
|
-
"""
|
|
89
|
-
|
|
90
|
-
top_logprobs: List[TopLogprob]
|
|
91
|
-
"""List of the most likely tokens and their log probability, at this token
|
|
92
|
-
position.
|
|
93
|
-
|
|
94
|
-
In rare cases, there may be fewer than the number of requested `top_logprobs`
|
|
95
|
-
returned.
|
|
96
|
-
"""
|
|
97
|
-
def __init__(self, **kwargs):
|
|
98
|
-
if 'top_logprobs' in kwargs and kwargs['top_logprobs'] is not None and kwargs['top_logprobs']:
|
|
99
|
-
top_logprobs = []
|
|
100
|
-
for logprob in kwargs['top_logprobs']:
|
|
101
|
-
top_logprobs.append(ChatCompletionTokenLogprob(**logprob))
|
|
102
|
-
self.top_logprobs = top_logprobs
|
|
103
|
-
else:
|
|
104
|
-
self.top_logprobs = None
|
|
105
|
-
|
|
106
|
-
super().__init__(**kwargs)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
@dataclass(init=False)
|
|
110
|
-
class ChoiceLogprobs(BaseObjectMixin):
|
|
111
|
-
content: Optional[List[ChatCompletionTokenLogprob]] = None
|
|
112
|
-
"""A list of message content tokens with log probability information."""
|
|
113
|
-
def __init__(self, **kwargs):
|
|
114
|
-
if 'content' in kwargs and kwargs['content'] is not None and kwargs['content']:
|
|
115
|
-
logprobs = []
|
|
116
|
-
for logprob in kwargs['content']:
|
|
117
|
-
logprobs.append(ChatCompletionTokenLogprob(**logprob))
|
|
118
|
-
self.content = logprobs
|
|
119
|
-
else:
|
|
120
|
-
self.content = None
|
|
121
|
-
|
|
122
|
-
super().__init__(**kwargs)
|
|
123
|
-
|
|
124
|
-
@dataclass(init=False)
|
|
125
|
-
class FunctionCall(BaseObjectMixin):
|
|
126
|
-
arguments: str
|
|
127
|
-
"""
|
|
128
|
-
The arguments to call the function with, as generated by the model in JSON
|
|
129
|
-
format. Note that the model does not always generate valid JSON, and may
|
|
130
|
-
hallucinate parameters not defined by your function schema. Validate the
|
|
131
|
-
arguments in your code before calling your function.
|
|
132
|
-
"""
|
|
133
|
-
|
|
134
|
-
name: str
|
|
135
|
-
"""The name of the function to call."""
|
|
136
|
-
def __init__(self, **kwargs):
|
|
137
|
-
super().__init__(**kwargs)
|
|
138
|
-
|
|
139
|
-
@dataclass(init=False)
|
|
140
|
-
class Function(BaseObjectMixin):
|
|
141
|
-
arguments: str
|
|
142
|
-
"""
|
|
143
|
-
The arguments to call the function with, as generated by the model in JSON
|
|
144
|
-
format. Note that the model does not always generate valid JSON, and may
|
|
145
|
-
hallucinate parameters not defined by your function schema. Validate the
|
|
146
|
-
arguments in your code before calling your function.
|
|
147
|
-
"""
|
|
148
|
-
|
|
149
|
-
name: str
|
|
150
|
-
"""The name of the function to call."""
|
|
151
|
-
def __init__(self, **kwargs):
|
|
152
|
-
super().__init__(**kwargs)
|
|
153
|
-
|
|
154
|
-
@dataclass(init=False)
|
|
155
|
-
class ChatCompletionMessageToolCall(BaseObjectMixin):
|
|
156
|
-
id: str
|
|
157
|
-
"""The ID of the tool call."""
|
|
158
|
-
|
|
159
|
-
function: Function
|
|
160
|
-
"""The function that the model called."""
|
|
161
|
-
|
|
162
|
-
type: Literal["function"]
|
|
163
|
-
"""The type of the tool. Currently, only `function` is supported."""
|
|
164
|
-
def __init__(self, **kwargs):
|
|
165
|
-
if 'function' in kwargs and kwargs['function'] is not None and kwargs['function']:
|
|
166
|
-
self.function = Function(**kwargs.pop('function', {}))
|
|
167
|
-
else:
|
|
168
|
-
function = None
|
|
169
|
-
|
|
170
|
-
super().__init__(**kwargs)
|
|
171
|
-
|
|
172
|
-
@dataclass(init=False)
|
|
173
|
-
class ChatCompletionMessage(BaseObjectMixin):
|
|
174
|
-
content: Optional[str] = None
|
|
175
|
-
"""The contents of the message."""
|
|
176
|
-
|
|
177
|
-
role: Literal["assistant"]
|
|
178
|
-
"""The role of the author of this message."""
|
|
179
|
-
|
|
180
|
-
function_call: Optional[FunctionCall] = None
|
|
181
|
-
"""Deprecated and replaced by `tool_calls`.
|
|
182
|
-
|
|
183
|
-
The name and arguments of a function that should be called, as generated by the
|
|
184
|
-
model.
|
|
185
|
-
"""
|
|
186
|
-
|
|
187
|
-
tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None
|
|
188
|
-
|
|
189
|
-
"""The tool calls generated by the model, such as function calls."""
|
|
190
|
-
def __init__(self, **kwargs):
|
|
191
|
-
if 'function_call' in kwargs and kwargs['function_call'] is not None and kwargs['function_call']:
|
|
192
|
-
self.function_call = FunctionCall(**kwargs.pop('function_call', {}))
|
|
193
|
-
|
|
194
|
-
if 'tool_calls' in kwargs and kwargs['tool_calls'] is not None and kwargs['tool_calls']:
|
|
195
|
-
tool_calls = []
|
|
196
|
-
for tool_call in kwargs['tool_calls']:
|
|
197
|
-
tool_calls.append(ChatCompletionMessageToolCall(**tool_call))
|
|
198
|
-
self.tool_calls = tool_calls
|
|
199
|
-
|
|
200
|
-
super().__init__(**kwargs)
|
|
201
|
-
|
|
202
|
-
@dataclass(init=False)
|
|
203
|
-
class Choice(BaseObjectMixin):
|
|
204
|
-
finish_reason: Literal["stop", "length", "tool_calls", "content_filter", "function_call"]
|
|
205
|
-
"""The reason the model stopped generating tokens.
|
|
206
|
-
|
|
207
|
-
This will be `stop` if the model hit a natural stop point or a provided stop
|
|
208
|
-
sequence, `length` if the maximum number of tokens specified in the request was
|
|
209
|
-
reached, `content_filter` if content was omitted due to a flag from our content
|
|
210
|
-
filters, `tool_calls` if the model called a tool, or `function_call`
|
|
211
|
-
(deprecated) if the model called a function.
|
|
212
|
-
"""
|
|
213
|
-
|
|
214
|
-
index: int
|
|
215
|
-
"""The index of the choice in the list of choices."""
|
|
216
|
-
|
|
217
|
-
logprobs: Optional[ChoiceLogprobs] = None
|
|
218
|
-
"""Log probability information for the choice."""
|
|
219
|
-
|
|
220
|
-
message: ChatCompletionMessage
|
|
221
|
-
"""A chat completion message generated by the model."""
|
|
222
|
-
|
|
223
|
-
def __init__(self, **kwargs):
|
|
224
|
-
if 'message' in kwargs and kwargs['message'] is not None and kwargs['message']:
|
|
225
|
-
self.message = ChatCompletionMessage(**kwargs.pop('message', {}))
|
|
226
|
-
else:
|
|
227
|
-
self.message = None
|
|
228
|
-
|
|
229
|
-
if 'logprobs' in kwargs and kwargs['logprobs'] is not None and kwargs['logprobs']:
|
|
230
|
-
self.logprobs = ChoiceLogprobs(**kwargs.pop('logprobs', {}))
|
|
231
|
-
|
|
232
|
-
super().__init__(**kwargs)
|
|
233
|
-
|
|
234
|
-
@dataclass(init=False)
|
|
235
|
-
class ChatCompletion(BaseObjectMixin):
|
|
236
|
-
status_code: int
|
|
237
|
-
"""The call response status_code, 200 indicate create success.
|
|
238
|
-
"""
|
|
239
|
-
code: str
|
|
240
|
-
"""The request failed, this is the error code.
|
|
241
|
-
"""
|
|
242
|
-
message: str
|
|
243
|
-
"""The request failed, this is the error message.
|
|
244
|
-
"""
|
|
245
|
-
id: str
|
|
246
|
-
"""A unique identifier for the chat completion.
|
|
247
|
-
"""
|
|
248
|
-
choices: List[Choice]
|
|
249
|
-
"""A list of chat completion choices.
|
|
250
|
-
|
|
251
|
-
Can be more than one if `n` is greater than 1.
|
|
252
|
-
"""
|
|
253
|
-
|
|
254
|
-
created: int
|
|
255
|
-
"""The Unix timestamp (in seconds) of when the chat completion was created."""
|
|
256
|
-
|
|
257
|
-
model: str
|
|
258
|
-
"""The model used for the chat completion."""
|
|
259
|
-
|
|
260
|
-
object: Literal["chat.completion"]
|
|
261
|
-
"""The object type, which is always `chat.completion`."""
|
|
262
|
-
|
|
263
|
-
system_fingerprint: Optional[str] = None
|
|
264
|
-
"""This fingerprint represents the backend configuration that the model runs with.
|
|
265
|
-
|
|
266
|
-
Can be used in conjunction with the `seed` request parameter to understand when
|
|
267
|
-
backend changes have been made that might impact determinism.
|
|
268
|
-
"""
|
|
269
|
-
|
|
270
|
-
usage: Optional[CompletionUsage] = None
|
|
271
|
-
"""Usage statistics for the completion request."""
|
|
272
|
-
|
|
273
|
-
def __init__(self, **kwargs):
|
|
274
|
-
if 'usage' in kwargs and kwargs['usage'] is not None and kwargs['usage']:
|
|
275
|
-
self.usage = CompletionUsage(**kwargs.pop('usage', {}))
|
|
276
|
-
else:
|
|
277
|
-
self.usage = None
|
|
278
|
-
|
|
279
|
-
if 'choices' in kwargs and kwargs['choices'] is not None and kwargs['choices']:
|
|
280
|
-
choices = []
|
|
281
|
-
for choice in kwargs.pop('choices', []):
|
|
282
|
-
choices.append(Choice(**choice))
|
|
283
|
-
self.choices = choices
|
|
284
|
-
else:
|
|
285
|
-
self.choices = None
|
|
286
|
-
super().__init__(**kwargs)
|
|
287
|
-
|
|
288
|
-
@dataclass(init=False)
|
|
289
|
-
class ChatCompletionChunk(BaseObjectMixin):
|
|
290
|
-
status_code: int
|
|
291
|
-
"""The call response status_code, 200 indicate create success.
|
|
292
|
-
"""
|
|
293
|
-
code: str
|
|
294
|
-
"""The request failed, this is the error code.
|
|
295
|
-
"""
|
|
296
|
-
message: str
|
|
297
|
-
"""The request failed, this is the error message.
|
|
298
|
-
"""
|
|
299
|
-
id: str
|
|
300
|
-
"""A unique identifier for the chat completion. Each chunk has the same ID."""
|
|
301
|
-
|
|
302
|
-
choices: List[Choice]
|
|
303
|
-
"""A list of chat completion choices.
|
|
304
|
-
|
|
305
|
-
Can contain more than one elements if `n` is greater than 1. Can also be empty
|
|
306
|
-
for the last chunk if you set `stream_options: {"include_usage": true}`.
|
|
307
|
-
"""
|
|
308
|
-
|
|
309
|
-
created: int
|
|
310
|
-
"""The Unix timestamp (in seconds) of when the chat completion was created.
|
|
311
|
-
|
|
312
|
-
Each chunk has the same timestamp.
|
|
313
|
-
"""
|
|
314
|
-
|
|
315
|
-
model: str
|
|
316
|
-
"""The model to generate the completion."""
|
|
317
|
-
|
|
318
|
-
object: Literal["chat.completion.chunk"]
|
|
319
|
-
"""The object type, which is always `chat.completion.chunk`."""
|
|
320
|
-
|
|
321
|
-
system_fingerprint: Optional[str] = None
|
|
322
|
-
"""
|
|
323
|
-
This fingerprint represents the backend configuration that the model runs with.
|
|
324
|
-
Can be used in conjunction with the `seed` request parameter to understand when
|
|
325
|
-
backend changes have been made that might impact determinism.
|
|
326
|
-
"""
|
|
327
|
-
|
|
328
|
-
usage: Optional[CompletionUsage] = None
|
|
329
|
-
"""
|
|
330
|
-
An optional field that will only be present when you set
|
|
331
|
-
`stream_options: {"include_usage": true}` in your request. When present, it
|
|
332
|
-
contains a null value except for the last chunk which contains the token usage
|
|
333
|
-
statistics for the entire request.
|
|
334
|
-
"""
|
|
335
|
-
def __init__(self, **kwargs):
|
|
336
|
-
if 'usage' in kwargs and kwargs['usage'] is not None and kwargs['usage']:
|
|
337
|
-
self.usage = CompletionUsage(**kwargs.pop('usage', {}))
|
|
338
|
-
else:
|
|
339
|
-
self.usage = None
|
|
340
|
-
|
|
341
|
-
if 'choices' in kwargs and kwargs['choices'] is not None and kwargs['choices']:
|
|
342
|
-
choices = []
|
|
343
|
-
for choice in kwargs.pop('choices', []):
|
|
344
|
-
choices.append(Choice(**choice))
|
|
345
|
-
self.choices = choices
|
|
346
|
-
else:
|
|
347
|
-
self.choices = None
|
|
348
|
-
super().__init__(**kwargs)
|
|
349
|
-
|
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
from dataclasses import dataclass
|
|
2
|
-
import mimetypes
|
|
3
|
-
import os
|
|
4
|
-
from datetime import datetime
|
|
5
|
-
from http import HTTPStatus
|
|
6
|
-
from time import mktime
|
|
7
|
-
from typing import List
|
|
8
|
-
from urllib.parse import unquote_plus, urlparse
|
|
9
|
-
from wsgiref.handlers import format_date_time
|
|
10
|
-
import time
|
|
11
|
-
import threading
|
|
12
|
-
|
|
13
|
-
import requests
|
|
14
|
-
|
|
15
|
-
from dashscope.api_entities.dashscope_response import DashScopeAPIResponse
|
|
16
|
-
from dashscope.client.base_api import GetMixin
|
|
17
|
-
from dashscope.common.constants import (FILE_PATH_SCHEMA,
|
|
18
|
-
REQUEST_CONTENT_AUDIO,
|
|
19
|
-
REQUEST_CONTENT_IMAGE,
|
|
20
|
-
REQUEST_CONTENT_TEXT)
|
|
21
|
-
from dashscope.common.error import InvalidInput, UploadFileException
|
|
22
|
-
from dashscope.common.logging import logger
|
|
23
|
-
from dashscope.common.utils import get_user_agent
|
|
24
|
-
|
|
25
|
-
@dataclass
|
|
26
|
-
class UploadToken:
|
|
27
|
-
token: str = None
|
|
28
|
-
expire_time: int = None
|
|
29
|
-
|
|
30
|
-
class UploadTokenMeta(type):
|
|
31
|
-
def __init__(cls):
|
|
32
|
-
cls._tokens = {} # key model, value: token and expire_time
|
|
33
|
-
cls._lock = threading.Lock() # lock set
|
|
34
|
-
|
|
35
|
-
@property
|
|
36
|
-
def token(cls, model):
|
|
37
|
-
current_time = time.perf_counter()
|
|
38
|
-
upload_token: UploadToken = cls._tokens[model] if model in cls._tokens else None
|
|
39
|
-
if upload_token is not None and current_time < upload_token.expire_time:
|
|
40
|
-
return upload_token.token
|
|
41
|
-
else:
|
|
42
|
-
return None
|
|
43
|
-
|
|
44
|
-
@token.setter
|
|
45
|
-
def token(cls, model: str, upload_token: UploadToken):
|
|
46
|
-
cls._lock.acquire()
|
|
47
|
-
cls._tokens[model] = upload_token
|
|
48
|
-
cls._lock.release()
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
class OssUtils(GetMixin, metaclass=UploadTokenMeta):
|
|
52
|
-
SUB_PATH = 'uploads'
|
|
53
|
-
|
|
54
|
-
@classmethod
|
|
55
|
-
def _decode_response_error(cls, response: requests.Response):
|
|
56
|
-
if 'application/json' in response.headers.get('content-type', ''):
|
|
57
|
-
message = response.json()
|
|
58
|
-
else:
|
|
59
|
-
message = response.content.decode('utf-8')
|
|
60
|
-
return message
|
|
61
|
-
|
|
62
|
-
@classmethod
|
|
63
|
-
def upload(cls,
|
|
64
|
-
model: str,
|
|
65
|
-
file_path: str,
|
|
66
|
-
api_key: str = None,
|
|
67
|
-
**kwargs) -> DashScopeAPIResponse:
|
|
68
|
-
"""Upload file for model fine-tune or other tasks.
|
|
69
|
-
|
|
70
|
-
Args:
|
|
71
|
-
file_path (str): The local file name to upload.
|
|
72
|
-
purpose (str): The purpose of the file[fine-tune|inference]
|
|
73
|
-
description (str, optional): The file description message.
|
|
74
|
-
api_key (str, optional): The api key. Defaults to None.
|
|
75
|
-
|
|
76
|
-
Returns:
|
|
77
|
-
DashScopeAPIResponse: The upload information
|
|
78
|
-
"""
|
|
79
|
-
upload_token = cls.token(model)
|
|
80
|
-
if upload_token is None:
|
|
81
|
-
upload_info = cls.get_upload_certificate(model=model, api_key=api_key)
|
|
82
|
-
if upload_info.status_code != HTTPStatus.OK:
|
|
83
|
-
raise UploadFileException(
|
|
84
|
-
'Get upload certificate failed, code: %s, message: %s' %
|
|
85
|
-
(upload_info.code, upload_info.message))
|
|
86
|
-
upload_info = upload_info.output
|
|
87
|
-
cls.token = xx
|
|
88
|
-
|
|
89
|
-
upload_info = upload_info.output
|
|
90
|
-
headers = {}
|
|
91
|
-
headers = {'user-agent': get_user_agent()}
|
|
92
|
-
headers['Accept'] = 'application/json'
|
|
93
|
-
headers['Date'] = format_date_time(mktime(datetime.now().timetuple()))
|
|
94
|
-
form_data = {}
|
|
95
|
-
form_data['OSSAccessKeyId'] = upload_info['oss_access_key_id']
|
|
96
|
-
form_data['Signature'] = upload_info['signature']
|
|
97
|
-
form_data['policy'] = upload_info['policy']
|
|
98
|
-
form_data['key'] = upload_info['upload_dir'] + \
|
|
99
|
-
'/' + os.path.basename(file_path)
|
|
100
|
-
form_data['x-oss-object-acl'] = upload_info['x_oss_object_acl']
|
|
101
|
-
form_data['x-oss-forbid-overwrite'] = upload_info[
|
|
102
|
-
'x_oss_forbid_overwrite']
|
|
103
|
-
form_data['success_action_status'] = '200'
|
|
104
|
-
form_data['x-oss-content-type'] = mimetypes.guess_type(file_path)[0]
|
|
105
|
-
url = upload_info['upload_host']
|
|
106
|
-
files = {'file': open(file_path, 'rb')}
|
|
107
|
-
with requests.Session() as session:
|
|
108
|
-
response = session.post(url,
|
|
109
|
-
files=files,
|
|
110
|
-
data=form_data,
|
|
111
|
-
headers=headers,
|
|
112
|
-
timeout=3600)
|
|
113
|
-
if response.status_code == HTTPStatus.OK:
|
|
114
|
-
return 'oss://' + form_data['key']
|
|
115
|
-
else:
|
|
116
|
-
msg = (
|
|
117
|
-
'Uploading file: %s to oss failed, error: %s' %
|
|
118
|
-
(file_path, cls._decode_response_error(response=response)))
|
|
119
|
-
logger.error(msg)
|
|
120
|
-
raise UploadFileException(msg)
|
|
121
|
-
|
|
122
|
-
@classmethod
|
|
123
|
-
def get_upload_certificate(cls,
|
|
124
|
-
model: str,
|
|
125
|
-
api_key: str = None,
|
|
126
|
-
**kwargs) -> DashScopeAPIResponse:
|
|
127
|
-
"""Get a oss upload certificate.
|
|
128
|
-
|
|
129
|
-
Args:
|
|
130
|
-
api_key (str, optional): The api key. Defaults to None.
|
|
131
|
-
|
|
132
|
-
Returns:
|
|
133
|
-
DashScopeAPIResponse: The job info
|
|
134
|
-
"""
|
|
135
|
-
params = {'action': 'getPolicy'}
|
|
136
|
-
params['model'] = model
|
|
137
|
-
return super().get(None, api_key, params=params, **kwargs)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
def upload_file(model: str, upload_path: str, api_key: str):
|
|
141
|
-
if upload_path.startswith(FILE_PATH_SCHEMA):
|
|
142
|
-
parse_result = urlparse(upload_path)
|
|
143
|
-
if parse_result.netloc:
|
|
144
|
-
file_path = parse_result.netloc + unquote_plus(parse_result.path)
|
|
145
|
-
else:
|
|
146
|
-
file_path = unquote_plus(parse_result.path)
|
|
147
|
-
if os.path.exists(file_path):
|
|
148
|
-
file_url = OssUtils.upload(model=model,
|
|
149
|
-
file_path=file_path,
|
|
150
|
-
api_key=api_key)
|
|
151
|
-
if file_url is None:
|
|
152
|
-
raise UploadFileException('Uploading file: %s failed' %
|
|
153
|
-
upload_path)
|
|
154
|
-
return file_url
|
|
155
|
-
else:
|
|
156
|
-
raise InvalidInput('The file: %s is not exists!' % file_path)
|
|
157
|
-
return None
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|