reykit 1.0.1__py3-none-any.whl → 1.1.0__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.
@@ -1,299 +0,0 @@
1
- # !/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
-
4
- """
5
- @Time : 2024-01-11 22:00:14
6
- @Author : Rey
7
- @Contact : reyxbo@163.com
8
- @Explain : Baidu API chat methods.
9
- """
10
-
11
-
12
- from typing import TypedDict, Literal, Union, Optional
13
- from datetime import datetime, timedelta
14
- from reykit.rexception import catch_exc
15
- from reykit.rrandom import randi
16
- from reykit.rtime import now
17
-
18
- from .rbaidu_base import RAPIBaidu
19
-
20
-
21
- __all__ = (
22
- 'RAPIBaiduChat',
23
- )
24
-
25
-
26
- ChatRecord = TypedDict('ChatRecord', {'time': datetime, 'send': str, 'receive': str})
27
- HistoryMessage = TypedDict('HistoryMessage', {'role': str, 'content': str})
28
-
29
-
30
- class RAPIBaiduChat(RAPIBaidu):
31
- """
32
- Rey's `Baidu API chat` type.
33
- """
34
-
35
- # Character.
36
- characters = (
37
- '善良', '淳厚', '淳朴', '豁达', '开朗', '体贴', '活跃', '慈祥', '仁慈', '温和',
38
- '温存', '和蔼', '和气', '直爽', '耿直', '憨直', '敦厚', '正直', '爽直', '率直',
39
- '刚直', '正派', '刚正', '纯正', '廉政', '清廉', '自信', '信心', '新年', '相信',
40
- '老实', '谦恭', '谦虚', '谦逊', '自谦', '谦和', '坚强', '顽强', '建议', '刚毅',
41
- '刚强', '倔强', '强悍', '刚毅', '减震', '坚定', '坚韧', '坚决', '坚忍', '勇敢',
42
- '勇猛', '勤劳', '勤恳', '勤奋', '勤勉', '勤快', '勤俭', '辛勤', '刻苦', '节约',
43
- '狂妄', '骄横', '骄纵', '窘态', '窘迫', '困窘', '难堪', '害羞', '羞涩', '赧然',
44
- '无语', '羞赧'
45
- )
46
-
47
-
48
- def __init__(
49
- self,
50
- key: str,
51
- secret: str,
52
- character: Optional[str] = None
53
- ) -> None:
54
- """
55
- Build `Baidu API chat` attributes.
56
-
57
- Parameters
58
- ----------
59
- key : API key.
60
- secret : API secret.
61
- Character : Character of language model.
62
- """
63
-
64
- # Set attribute.
65
- super().__init__(key, secret)
66
- self.chat_records: dict[str, ChatRecord] = {}
67
- self.character=character
68
-
69
-
70
- def chat(
71
- self,
72
- text: str,
73
- character: Optional[Union[str, Literal[False]]] = None,
74
- history_key: Optional[str] = None,
75
- history_recent_seconds: float = 1800,
76
- history_max_word: int = 400
77
- ) -> bytes:
78
- """
79
- Chat with language model.
80
-
81
- Parameters
82
- ----------
83
- text : Text.
84
- Character : Character of language model.
85
- - `None`, Use `self.character`: attribute.
86
- - `str`: Use this value.
87
- - `Literal[False]`: Do not set.
88
- Character : Character of language model.
89
- history_key : Chat history records key.
90
- history_recent_seconds : Limit recent seconds of chat history.
91
- history_max_word : Limit maximum word of chat history.
92
-
93
- Returns
94
- -------
95
- Reply text.
96
- """
97
-
98
- # Get parameter.
99
- url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro'
100
- params = {'access_token': self.token}
101
- headers = {'Content-Type': 'application/json'}
102
- if history_key is None:
103
- messages = []
104
- else:
105
- messages = self.history_messages(
106
- history_key,
107
- history_recent_seconds,
108
- history_max_word
109
- )
110
- message = {'role': 'user', 'content': text}
111
- messages.append(message)
112
- json = {'messages': messages}
113
- match character:
114
- case None:
115
- character = self.character
116
- case False:
117
- character = None
118
- if character is not None:
119
- json['system'] = character
120
-
121
- # Request.
122
- try:
123
- response = self.request(
124
- url,
125
- params=params,
126
- json=json,
127
- headers=headers
128
- )
129
-
130
- ## Parameter 'system' error.
131
- except:
132
- *_, exc_instance, _ = catch_exc()
133
- error_code = exc_instance.args[1]['error_code']
134
- if error_code == 336104:
135
- result = self.chat(
136
- text,
137
- False,
138
- history_key,
139
- history_recent_seconds,
140
- history_max_word
141
- )
142
- return result
143
- else:
144
- raise exc_instance
145
-
146
- # Extract.
147
- response_json: dict = response.json()
148
- result: str = response_json['result']
149
-
150
- # Record.
151
- self.record_call(
152
- messages=messages,
153
- character=character
154
- )
155
- if history_key is not None:
156
- self.record_chat(
157
- text,
158
- result,
159
- history_key
160
- )
161
-
162
- return result
163
-
164
-
165
- def record_chat(
166
- self,
167
- send: str,
168
- receive: str,
169
- key: str
170
- ) -> None:
171
- """
172
- Record chat.
173
-
174
- Parameters
175
- ----------
176
- send : Send text.
177
- receive : Receive text.
178
- key : Chat history records key.
179
- """
180
-
181
- # Generate.
182
- record = {
183
- 'time': now(),
184
- 'send': send,
185
- 'receive': receive
186
- }
187
-
188
- # Record.
189
- reocrds = self.chat_records.get(key)
190
- if reocrds is None:
191
- self.chat_records[key] = [record]
192
- else:
193
- reocrds.append(record)
194
-
195
-
196
- def history_messages(
197
- self,
198
- key: str,
199
- recent_seconds: float,
200
- max_word: int
201
- ) -> list[HistoryMessage]:
202
- """
203
- Return history messages.
204
-
205
- Parameters
206
- ----------
207
- key : Chat history records key.
208
- recent_seconds : Limit recent seconds of chat history.
209
- max_word : Limit maximum word of chat history.
210
-
211
- Returns
212
- -------
213
- History messages.
214
- """
215
-
216
- # Get parameter.
217
- records = self.chat_records.get(key, [])
218
- now_time = now()
219
-
220
- # Generate.
221
- messages = []
222
- word_count = 0
223
- for record in records:
224
-
225
- ## Limit time.
226
- interval_time: timedelta = now_time - record['time']
227
- interval_seconds = interval_time.total_seconds()
228
- if interval_seconds > recent_seconds:
229
- break
230
-
231
- ## Limit word.
232
- word_len = len(record['send']) + len(record['receive'])
233
- character_len = len(self.character)
234
- word_count += word_len
235
- if word_count + character_len > max_word:
236
- break
237
-
238
- ## Append.
239
- message = [
240
- {'role': 'user', 'content': record['send']},
241
- {'role': 'assistant', 'content': record['receive']}
242
- ]
243
- messages.extend(message)
244
-
245
- return messages
246
-
247
-
248
- def interval_chat(
249
- self,
250
- key: str
251
- ) -> float:
252
- """
253
- Return the interval seconds from last chat.
254
- When no record, then return the interval seconds from start.
255
-
256
- Parameters
257
- ----------
258
- key : Chat history records key.
259
-
260
- Returns
261
- -------
262
- Interval seconds.
263
- """
264
-
265
- # Get parameter.
266
- records = self.chat_records.get(key)
267
- if records is None:
268
- last_time = self.start_time
269
- else:
270
- last_time: datetime = records[-1]['time']
271
- if self.call_records == []:
272
- last_time = self.start_time
273
- else:
274
- last_time: datetime = self.call_records[-1]['time']
275
-
276
- # Count.
277
- now_time = now()
278
- interval_time = now_time - last_time
279
- interval_seconds = interval_time.total_seconds()
280
-
281
- return interval_seconds
282
-
283
-
284
- def modify(
285
- self,
286
- text: str
287
- ) -> str:
288
- """
289
- Modify text.
290
- """
291
-
292
- # Get parameter.
293
- character = randi(self.characters)
294
-
295
- # Modify.
296
- text = '用%s的语气,润色以下这句话\n%s' % (character, text)
297
- text_modify = self.chat(text)
298
-
299
- return text_modify
@@ -1,183 +0,0 @@
1
- # !/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
-
4
- """
5
- @Time : 2024-01-11 22:00:14
6
- @Author : Rey
7
- @Contact : reyxbo@163.com
8
- @Explain : Baidu API image methods.
9
- """
10
-
11
-
12
- from typing import Optional
13
- from reykit.ros import RFile
14
- from reykit.rtime import wait
15
-
16
- from .rbaidu_base import RAPIBaidu
17
-
18
-
19
- __all__ = (
20
- 'RAPIBaiduImage',
21
- )
22
-
23
-
24
- class RAPIBaiduImage(RAPIBaidu):
25
- """
26
- Rey's `Baidu API image` type.
27
- """
28
-
29
-
30
- def _to_url_create_task(
31
- self,
32
- text: str
33
- ) -> str:
34
- """
35
- Create task of generate image URL from text.
36
-
37
- Parameters
38
- ----------
39
- text : Text, length cannot exceed 60.
40
-
41
- Returns
42
- -------
43
- Task ID.
44
- """
45
-
46
- # Get parameter.
47
- url = 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2'
48
- params = {'access_token': self.token}
49
- headers = {
50
- 'Accept': 'application/json',
51
- 'Content-Type': 'application/json'
52
- }
53
- json = {
54
- 'prompt': text,
55
- 'width': 1024,
56
- 'height': 1024
57
- }
58
-
59
- # Request.
60
- response = self.request(
61
- url,
62
- params=params,
63
- json=json,
64
- headers=headers
65
- )
66
-
67
- # Record.
68
- self.record_call(text=text)
69
-
70
- # Extract.
71
- response_json: dict = response.json()
72
- task_id: str = response_json['data']['task_id']
73
-
74
- return task_id
75
-
76
-
77
- def _to_url_query_task(
78
- self,
79
- task_id: str
80
- ) -> dict:
81
- """
82
- Query task of generate image URL from text.
83
-
84
- Parameters
85
- ----------
86
- task_id : Task ID.
87
-
88
- Returns
89
- -------
90
- Task information.
91
- """
92
-
93
- # Get parameter.
94
- url = 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2'
95
- params = {'access_token': self.token}
96
- headers = {
97
- 'Accept': 'application/json',
98
- 'Content-Type': 'application/json'
99
- }
100
- json = {'task_id': task_id}
101
-
102
- # Request.
103
- response = self.request(
104
- url,
105
- params=params,
106
- json=json,
107
- headers=headers
108
- )
109
-
110
- # Extract.
111
- response_json: dict = response.json()
112
- task_info: dict = response_json['data']
113
-
114
- return task_info
115
-
116
-
117
- def to_url(
118
- self,
119
- text: str,
120
- path: Optional[str] = None
121
- ) -> str:
122
- """
123
- Generate image URL from text.
124
-
125
- Parameters
126
- ----------
127
- text : Text, length cannot exceed 60.
128
- path : File save path.
129
- - `None`: Not save.
130
-
131
- Returns
132
- -------
133
- Image URL.
134
- """
135
-
136
- # Create.
137
- task_id = self._to_url_create_task(text)
138
-
139
- # Wait.
140
- store = {}
141
-
142
-
143
- ## Define.
144
- def is_task_success() -> bool:
145
- """
146
- Whether if is task successed.
147
-
148
- Returns
149
- -------
150
- Judge result.
151
- """
152
-
153
- # Query.
154
- task_info = self._to_url_query_task(task_id)
155
-
156
- # Judge.
157
- match task_info['task_status']:
158
- case 'RUNNING':
159
- return False
160
- case 'SUCCESS':
161
- store['url'] = task_info['sub_task_result_list'][0]['final_image_list'][0]['img_url']
162
- return True
163
- case _:
164
- raise AssertionError('Baidu API text to image task failed')
165
-
166
-
167
- ## Start.
168
- wait(
169
- is_task_success,
170
- _interval=0.5,
171
- _timeout=600
172
- )
173
-
174
- ## Extract.
175
- url = store['url']
176
-
177
- # Save.
178
- if path is not None:
179
- response = self.request(url)
180
- rfile = RFile(path)
181
- rfile.write(response.content)
182
-
183
- return url