Beracles commited on
Commit
08cd4f3
·
1 Parent(s): c964edf
.gitignore CHANGED
@@ -1,3 +1,4 @@
 
1
  # Byte-compiled / optimized / DLL files
2
  __pycache__/
3
  *.py[cod]
 
1
+ .vscode
2
  # Byte-compiled / optimized / DLL files
3
  __pycache__/
4
  *.py[cod]
.vscode/launch.json CHANGED
@@ -1,21 +1,19 @@
1
  {
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
  "version": "0.2.0",
6
  "configurations": [
7
-
8
  {
9
- "name": "Python: FastAPI",
10
- "type": "python",
11
  "request": "launch",
12
  "module": "uvicorn",
13
  "args": [
14
- "main:app",
15
  "--reload"
16
  ],
17
- "jinja": true,
18
- "justMyCode": true
19
- }
20
  ]
21
  }
 
1
  {
2
+ // 使用 IntelliSense 了解相关属性。
3
+ // 悬停以查看现有属性的描述。
4
+ // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
5
  "version": "0.2.0",
6
  "configurations": [
 
7
  {
8
+ "name": "Python 调试程序: FastAPI",
9
+ "type": "debugpy",
10
  "request": "launch",
11
  "module": "uvicorn",
12
  "args": [
13
+ "src.main:app",
14
  "--reload"
15
  ],
16
+ "jinja": true
17
+ },
 
18
  ]
19
  }
Dockerfile CHANGED
@@ -8,4 +8,4 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
8
 
9
  COPY . .
10
 
11
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "4"]
 
8
 
9
  COPY . .
10
 
11
+ CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "4"]
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Pgai
3
  emoji: 📊
4
  colorFrom: red
5
  colorTo: pink
 
1
  ---
2
+ title: FastAPI
3
  emoji: 📊
4
  colorFrom: red
5
  colorTo: pink
faiss_index/index.faiss ADDED
Binary file (26.2 kB). View file
 
faiss_index/index.pkl ADDED
Binary file (23.4 kB). View file
 
games/angrybirds/add_config.py DELETED
@@ -1,63 +0,0 @@
1
- import copy
2
-
3
- from games.angrybirds.config_const import x_bird
4
- from games.angrybirds.config_const import x_pig
5
- from games.angrybirds.config_const import x_house
6
- from games.angrybirds.config_const import x_obstacle
7
- from games.angrybirds.config_const import x_pig_size
8
- from games.angrybirds.config_const import x_bird_size
9
-
10
- from games.angrybirds.config_const import x_change_position
11
- from games.angrybirds.config_const import x_change_skin
12
- from games.angrybirds.config_const import x_add
13
- from games.angrybirds.config_const import x_delete
14
- from games.angrybirds.config_const import x_list
15
- from games.angrybirds.config_const import x_increase
16
- from games.angrybirds.config_const import x_decrease
17
-
18
- from games.angrybirds.config_const import x_quantity
19
- from games.angrybirds.config_const import x_color
20
- from games.angrybirds.config_const import x_type
21
- from games.angrybirds.config_const import x_size
22
- from games.angrybirds.config_const import x_args
23
-
24
- # from games.angrybirds.config import config
25
-
26
- def change_attribute(d, attr, value):
27
- d['result'][2][attr] = value
28
-
29
- def add_config(game_train):
30
- ###########################################
31
- # additional 'add houses'
32
- ###########################################
33
- example = 'build houses'
34
- assert example in game_train
35
- ###########################################
36
-
37
- x = 'protect the pigs by build houses for them'
38
- game_train[x] = game_train[example]
39
- print(len(game_train))
40
-
41
- x = "build a house"
42
- game_train[x] = copy.deepcopy(game_train[example])
43
- assert game_train[x]['result'][2][x_quantity] == 'some'
44
- change_attribute(game_train[x], x_quantity, 1)
45
- print(len(game_train))
46
-
47
- x = "build houses, so I can protect my pigs"
48
- game_train[x] = game_train[example]
49
- print(len(game_train))
50
-
51
- ###########################################
52
- # additional 'delete birds'
53
- ###########################################
54
- for bird in [
55
- 'big', 'magnet', 'superheavy',
56
- 'catapult', 'flash', 'antigravity',
57
- ]:
58
- example = f'delete {bird} birds'
59
- assert example in game_train
60
- ###########################################
61
- x = f"I don't like {bird} birds. Delete them"
62
- game_train[x] = game_train[example]
63
- print(len(game_train))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/angrybirds.py DELETED
@@ -1,172 +0,0 @@
1
- import json
2
- from pathlib import Path
3
- from collections import Counter
4
-
5
- import openai
6
- from games.game import game
7
- # from games.game_openai import api_key
8
- from games.angrybirds.config import config
9
-
10
- debug = 2
11
-
12
- class angrybird (game):
13
- ai_version = '3.8.0.2023-09-18-a' # # use inheritance
14
- data_version = ai_version
15
-
16
- def __init__(self):
17
- # openai.api_key = api_key
18
- self.ROOT = Path(__file__).parent.parent.parent
19
- self.PATH = self.__class__.__name__
20
- self.embeddings = {}
21
- self.query_count = 0
22
-
23
- def init_train():
24
- PATH = Path(__file__).parent
25
- with open(PATH/"game_train.json", 'r') as f:
26
- unnormalized = json.load(f)
27
-
28
- self.train = {}
29
- for cmd in unnormalized.keys():
30
- key = cmd.strip().lower()
31
- self.train[key] = unnormalized[cmd]
32
- print(f"{len(self.train)=}")
33
-
34
- # self.train = self.init_train(config)
35
- init_train()
36
-
37
-
38
- def special_case(self, command: str):
39
- if command.strip().lower() in ['bird', 'birds']:
40
- print('special case')
41
- return 'list birds'
42
- elif command.strip().lower() in ['pig', 'pigs', 'enemy', 'enemies']:
43
- print('special case')
44
- return 'list pigs'
45
- else:
46
- return command
47
-
48
-
49
- def _get_full_prompt(self, prompt):
50
- assistant = {
51
- "role": "system",
52
- "content": "You are a helpful assistant.",
53
- }
54
- full_prompt = [
55
- assistant,
56
- {'role': 'user', 'content': prompt}
57
- ]
58
- return full_prompt
59
-
60
-
61
- def _query_chatgpt(self, full_prompt:str, n:int=15):
62
- completion = openai.ChatCompletion.create(
63
- # model='gpt-4',
64
- model='gpt-3.5-turbo',
65
- messages=full_prompt, # self._get_full_prompt(prompt),
66
- n=n,
67
- )
68
- choices = [choice.message.content for choice in completion.choices]
69
- return choices
70
-
71
-
72
- def query_chatgpt_nlp_response(
73
- self,
74
- command: str,
75
- n: int,
76
- ):
77
-
78
- prompt1 = f"""
79
- {config.game_desc}
80
- """
81
- full_prompt = self._get_full_prompt()
82
- # print(prompt)
83
- choices = self._query_chatgpt(self._get_full_prompt(prompt1), n=1)
84
-
85
-
86
- prompt2 = f"""
87
- As a game developer, when I say,
88
-
89
- {command}
90
-
91
- give me a concise response.
92
- """
93
- # print(prompt)
94
- choices = self._query_chatgpt(self._get_full_prompt(prompt1), n=1)
95
-
96
- return choices
97
-
98
-
99
- def query_chatgpt_yes_no(
100
- self,
101
- command: str,
102
- follow_up_question: str,
103
- ):
104
-
105
- prompt = f"""
106
- When the user says:
107
-
108
- '{command}'
109
-
110
- {follow_up_question}
111
-
112
- Please answer yes or no.
113
- Please do not explain.
114
- """
115
-
116
- tmp = """
117
- Please answer yes or no.
118
- Please do not explain.
119
- """
120
-
121
- if debug >= 2:
122
- print('-'*10)
123
- print(prompt)
124
- print('-'*10)
125
- choices = self._query_chatgpt(self._get_full_prompt(prompt))
126
- # res = completion.choices[0].message.content
127
-
128
- # yes_no
129
- for i in range(len(choices)):
130
- choices[i] = choices[i].lower()[0]
131
-
132
- res, freq = Counter(choices).most_common()[0]
133
- if debug >= 2:
134
- print(f"{freq/len(choices):.4f} {freq}/{len(choices)}\t{res}")
135
- print(Counter(choices).most_common())
136
- return res
137
-
138
-
139
- def query_chatgpt_number(
140
- self,
141
- command: str,
142
- follow_up_question: str,
143
- ):
144
-
145
- prompt = f"""
146
- When the user says:
147
-
148
- '{command}'
149
-
150
- {follow_up_question}
151
-
152
- Just provide the number in numerical form.
153
- Please do not explain.
154
- """
155
-
156
- tmp = """
157
- Please answer yes or no.
158
- Please do not explain.
159
- """
160
-
161
- if debug >= 2:
162
- print('-'*10)
163
- print(prompt)
164
- print('-'*10)
165
- choices = self._query_chatgpt(self._get_full_prompt(prompt))
166
- # res = completion.choices[0].message.content
167
-
168
- res, freq = Counter(choices).most_common()[0]
169
- if debug >= 2:
170
- print(f"{freq/len(choices):.4f} {freq}/{len(choices)}\t{res}")
171
- print(Counter(choices).most_common())
172
- return res
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/config.py DELETED
@@ -1,646 +0,0 @@
1
- import json
2
-
3
- from games.angrybirds.add_config import add_config
4
- from games.angrybirds.config_const import *
5
-
6
- class config:
7
- game_train = {}
8
- agent = 'game developer'
9
- game_desc = """
10
- Imaging we are developing the game of the Angry Birds,
11
- and the game is described as the following:
12
-
13
- In Angry Birds, players take control of a group of birds who are seeking
14
- revenge on a group of green pigs that have stolen their eggs.
15
- The gameplay involves using a slingshot to launch the birds at various
16
- structures where the pigs are hiding. The objective is to
17
- eliminate all the pigs on each level and score as many points as possible.
18
-
19
- A game developer is building the game,
20
- and I need you to help me figure out what is going on.
21
- """
22
-
23
- def init_game_train(self):
24
- ###########################################
25
- # add/remove <5> (<antigravity>) birds/pigs
26
- ###########################################
27
- for obj, obj_single, obj_plural in [
28
- (x_bird, 'bird', 'birds'),
29
- (x_pig, 'pig', 'pigs'),
30
- (x_pig, 'enemy', 'enemies'),
31
- ]:
32
- for verb1, verb2 in [
33
- ('add', x_add),
34
- ('delete', x_delete),
35
- ('reduce', x_delete),
36
- ]:
37
- adjs = ['elderly', 'sport',] if obj == x_pig else [
38
- 'big', 'magnet', 'superheavy',
39
- 'catapult', 'flash', 'antigravity',
40
- ]
41
- for certain in adjs + ['']: # empty means no adj
42
- for x1, x2, x3 in [
43
- ('one', obj_single, 1),
44
- ('a' if (certain == '') or (certain[0] not in 'aeiou') else 'an', obj_single, 1),
45
- ('two', obj_plural, 2),
46
- (2, obj_plural, 2),
47
- ('three', obj_plural, 3),
48
- (3, obj_plural, 3),
49
- ('four', obj_plural, 4),
50
- (4, obj_plural, 4),
51
- ('five', obj_plural, 5),
52
- (5, obj_plural, 5),
53
- ('six', obj_plural, 6),
54
- (6, obj_plural, 6),
55
- ('seven', obj_plural, 7),
56
- (7, obj_plural, 7),
57
- ('eight', obj_plural, 8),
58
- (8, obj_plural, 8),
59
- ('nine', obj_plural, 9),
60
- (9, obj_plural, 9),
61
- ('ten', obj_plural, 10),
62
- (10, obj_plural, 10),
63
- ('more', obj_plural, 'some'),
64
- ('some', obj_plural, 'some'),
65
- ('', obj_plural, 'all' if verb2 in [x_delete] else 'some'),
66
- ('all', obj_plural, 'all'),
67
- ]:
68
- tmp = f"{verb1} {x1} {certain} {x2}"
69
- key = ' '.join(tmp.split())
70
- xxx = {
71
- key: {
72
- 'train': '',
73
- 'result': [
74
- obj,
75
- verb2,
76
- {x_quantity: x3, x_type: certain},
77
- ],
78
- 'desc': [
79
- '[unified] add/delete one or more (special) birds/pigs',
80
- ]
81
- },
82
- }
83
- if certain == '':
84
- del xxx[key]['result'][2][x_type]
85
- # if x3 == 1:
86
- # xxx[f"add {x1} {x2}"]['result'][2] = {}
87
- self.game_train |= xxx
88
-
89
- ###########################################
90
- # add pigs
91
- ###########################################
92
- for objs in ['pigs', 'enemies']:
93
- xxx = {
94
- f"make {objs} everywehre": {
95
- 'train': '',
96
- 'result': [
97
- x_pig,
98
- x_add,
99
- {x_quantity: 'everywhere'},
100
- ],
101
- 'desc': [
102
- '[unified] add/delete one or more (special) birds/pigs',
103
- ]
104
- },
105
- f"Our {objs} are losing. Add more {objs}": {
106
- 'train': '',
107
- 'result': [
108
- x_pig,
109
- x_add,
110
- {x_quantity: 'some'},
111
- ],
112
- 'desc': [
113
- '[unified] add/delete one or more (special) birds/pigs',
114
- ]
115
- },
116
- }
117
- self.game_train |= xxx
118
-
119
- ###########################################
120
- # add houses
121
- ###########################################
122
- xxx = {
123
- "build houses": {
124
- 'train': '',
125
- 'result': [
126
- x_house,
127
- x_add,
128
- {x_quantity: 'some'},
129
- ],
130
- 'desc': [
131
- 'add one or more houses',
132
- ]
133
- },
134
- }
135
- self.game_train |= xxx
136
-
137
- ###########################################
138
- # add solid houses
139
- ###########################################
140
- xxx = {
141
- "The obstacles are too weak. Let's build some solid houses": {
142
- 'train': '',
143
- 'result': [
144
- x_house,
145
- x_add,
146
- {x_type: 'solid', x_quantity: 'some'},
147
- ],
148
- 'desc': [
149
- 'add one or more houses',
150
- ]
151
- },
152
- }
153
- self.game_train |= xxx
154
-
155
- ###########################################
156
- # change HP for pigs
157
- ###########################################
158
- for obj_single, objs in [
159
- ('pig', 'pigs'),
160
- ('enemy', 'enemies'),
161
- ]:
162
- xxx = {
163
- f"The {objs} are too weak. Increase the health points for them": {
164
- 'train': '',
165
- 'result': [
166
- 'pig',
167
- 'increase health points',
168
- {},
169
- ],
170
- 'desc': [
171
- 'change HP',
172
- ]
173
- },
174
- f"The {objs} are too weak. Increase the HP for them": {
175
- 'train': '',
176
- 'result': [
177
- 'pig',
178
- 'increase health points',
179
- {},
180
- ],
181
- 'desc': [
182
- 'change HP',
183
- ]
184
- },
185
- f"The {objs} are too weak. Increase the hit points for them": {
186
- 'train': '',
187
- 'result': [
188
- 'pig',
189
- 'increase health points',
190
- {},
191
- ],
192
- 'desc': [
193
- 'change HP',
194
- ]
195
- },
196
- f"The {objs} are too weak. Increase the blood level for them": {
197
- 'train': '',
198
- 'result': [
199
- 'pig',
200
- 'increase health points',
201
- {},
202
- ],
203
- 'desc': [
204
- 'change HP',
205
- ]
206
- },
207
- f"The {objs} are too weak. Increase the blood levels for them": {
208
- 'train': '',
209
- 'result': [
210
- 'pig',
211
- 'increase health points',
212
- {},
213
- ],
214
- 'desc': [
215
- 'change HP',
216
- ]
217
- },
218
- f"make the {obj_single} weaker": {
219
- 'train': '',
220
- 'result': [
221
- x_pig,
222
- 'decrease health points',
223
- {x_quantity: 1},
224
- ],
225
- 'desc': [
226
- 'change HP',
227
- ]
228
- },
229
- }
230
- self.game_train |= xxx
231
-
232
- ###########################################
233
- # Change background
234
- ###########################################
235
- xxx = {
236
- "Change background music": {
237
- 'train': '',
238
- 'result': [
239
- 'change background',
240
- {x_args: 'music'},
241
- ],
242
- 'desc': [
243
- 'change background',
244
- ]
245
- },
246
- "Change background sound": {
247
- 'train': '',
248
- 'result': [
249
- 'change background',
250
- {x_args: 'music'},
251
- ],
252
- 'desc': [
253
- 'change background',
254
- ]
255
- },
256
- "Change background volumn": {
257
- 'train': '',
258
- 'result': [
259
- 'change background',
260
- {x_args: 'volumn'},
261
- ],
262
- 'desc': [
263
- 'change background',
264
- ]
265
- },
266
- "Change volumn": {
267
- 'train': '',
268
- 'result': [
269
- 'change background',
270
- {x_args: 'volumn'},
271
- ],
272
- 'desc': [
273
- 'change background',
274
- ]
275
- },
276
- "Change background": {
277
- 'train': '',
278
- 'result': [
279
- 'change background',
280
- {x_args: 'picture'},
281
- ],
282
- 'desc': [
283
- 'change background',
284
- ]
285
- },
286
- "Change background picture": {
287
- 'train': '',
288
- 'result': [
289
- 'change background',
290
- {x_args: 'picture'},
291
- ],
292
- 'desc': [
293
- 'change background',
294
- ]
295
- },
296
- "Change background photo": {
297
- 'exclude': '',
298
- 'result': [
299
- 'change background',
300
- {x_args: 'picture'},
301
- ],
302
- 'desc': [
303
- 'change background',
304
- ]
305
- },
306
- "Change background color": {
307
- 'train': '',
308
- 'result': [
309
- 'change background',
310
- {x_args: 'picture'},
311
- ],
312
- 'desc': [
313
- 'change background',
314
- ]
315
- },
316
- "Change background text": {
317
- 'train': '',
318
- 'result': [
319
- 'change background',
320
- {x_args: 'picture'},
321
- ],
322
- 'desc': [
323
- 'change background',
324
- ]
325
- },
326
- }
327
- self.game_train |= xxx
328
-
329
- ###########################################
330
- # change position (birds, pigs, etc)
331
- ###########################################
332
- for obj, obj_plural in [
333
- (x_bird, 'birds'),
334
- (x_pig, 'pigs'),
335
- (x_pig, 'enemies'),
336
- (x_house, 'houses'),
337
- (x_obstacle, 'obstacles'),
338
- ]:
339
- xxx = {
340
- f'change the position of {obj_plural}': {
341
- 'train': '',
342
- 'prompt': [
343
- ],
344
- 'result': [
345
- obj,
346
- x_change_position,
347
- {},
348
- ],
349
- 'desc': [
350
- f'change positions',
351
- ]
352
- },
353
- f'move {obj_plural}': {
354
- 'train': '',
355
- 'prompt': [
356
- ],
357
- 'result': [
358
- obj,
359
- x_change_position,
360
- {},
361
- ],
362
- 'desc': [
363
- f'change positions',
364
- ]
365
- },
366
- }
367
- self.game_train |= xxx
368
-
369
- ###########################################
370
- # change size (birds/pigs)
371
- ###########################################
372
- xxx = {
373
- "Make the bird bigger": {
374
- 'train': '',
375
- 'result': [
376
- x_bird_size,
377
- x_increase,
378
- {},
379
- ],
380
- 'desc': [
381
- 'change size',
382
- ]
383
- },
384
- "Make the bird bigger, so it can run over the enemies": {
385
- 'train': '',
386
- 'focus': '',
387
- 'result': [
388
- x_bird_size,
389
- x_increase,
390
- {},
391
- ],
392
- 'desc': [
393
- 'change size',
394
- ]
395
- },
396
- "Make the pig bigger": {
397
- 'train': '',
398
- 'result': [
399
- x_pig_size,
400
- x_increase,
401
- {},
402
- ],
403
- 'desc': [
404
- 'change size',
405
- ]
406
- },
407
- "Make the enemy bigger": {
408
- 'train': '',
409
- 'result': [
410
- x_pig_size,
411
- x_increase,
412
- {},
413
- ],
414
- 'desc': [
415
- 'change size',
416
- ]
417
- },
418
- "Make the bird smaller": {
419
- 'train': '',
420
- 'result': [
421
- x_bird_size,
422
- x_decrease,
423
- {},
424
- ],
425
- 'desc': [
426
- 'change size',
427
- ]
428
- },
429
- "Make the pig smaller": {
430
- 'train': '',
431
- 'result': [
432
- x_pig_size,
433
- x_decrease,
434
- {},
435
- ],
436
- 'desc': [
437
- 'change size',
438
- ]
439
- },
440
- "Make the enemy smaller": {
441
- 'train': '',
442
- 'result': [
443
- x_pig_size,
444
- x_decrease,
445
- {},
446
- ],
447
- 'desc': [
448
- 'change size',
449
- ]
450
- },
451
- }
452
- self.game_train |= xxx
453
-
454
- ###########################################
455
- # Change skin for birds
456
- ###########################################
457
- xxx = {
458
- "Change bird's picture": {
459
- 'train': '',
460
- 'result': [
461
- x_change_skin,
462
- {x_args: 'birds'},
463
- ],
464
- 'desc': [
465
- 'change skin',
466
- 'change skin for birds',
467
- ]
468
- },
469
- "Change bird's skin": {
470
- 'train': '',
471
- 'result': [
472
- x_change_skin,
473
- {x_args: 'birds'},
474
- ],
475
- 'desc': [
476
- 'change skin',
477
- 'change skin for birds',
478
- ]
479
- },
480
- "bird picture": {
481
- 'train': '',
482
- 'result': [
483
- x_change_skin,
484
- {x_args: 'birds'},
485
- ],
486
- 'desc': [
487
- 'change skin',
488
- 'change skin for bird',
489
- ]
490
- },
491
- "pig picture": {
492
- 'train': '',
493
- 'result': [
494
- x_change_skin,
495
- {x_args: 'pigs'},
496
- ],
497
- 'desc': [
498
- 'change skin',
499
- 'change skin for pigs',
500
- ]
501
- },
502
- "enemy picture": {
503
- 'train': '',
504
- 'result': [
505
- x_change_skin,
506
- {x_args: 'pigs'},
507
- ],
508
- 'desc': [
509
- 'change skin',
510
- 'change skin for pigs',
511
- ]
512
- },
513
- "Change pig's picture": {
514
- 'train': '',
515
- 'result': [
516
- x_change_skin,
517
- {x_args: 'pigs'},
518
- ],
519
- 'desc': [
520
- 'change skin',
521
- 'change skin for pigs',
522
- ]
523
- },
524
- "Change enemy's picture": {
525
- 'train': '',
526
- 'result': [
527
- x_change_skin,
528
- {x_args: 'pigs'},
529
- ],
530
- 'desc': [
531
- 'change skin',
532
- 'change skin for pigs',
533
- ]
534
- },
535
- "Change pig's skin": {
536
- 'train': '',
537
- 'result': [
538
- x_change_skin,
539
- {x_args: 'pigs'},
540
- ],
541
- 'desc': [
542
- 'change skin',
543
- 'change skin for pigs',
544
- ]
545
- },
546
- "Change enemy's skin": {
547
- 'train': '',
548
- 'result': [
549
- x_change_skin,
550
- {x_args: 'pigs'},
551
- ],
552
- 'desc': [
553
- 'change skin',
554
- 'change skin for pigs',
555
- ]
556
- },
557
- }
558
- self.game_train |= xxx
559
-
560
- ###########################################
561
- # list birds/pigs
562
- ###########################################
563
- for obj, obj_single, obj_plural in [
564
- (x_bird, 'bird', 'birds'),
565
- (x_pig, 'pig', 'pigs'),
566
- (x_pig, 'enemy', 'enemies'),
567
- ]:
568
- xxx = {
569
- f"List {obj_plural}": {
570
- 'train': '',
571
- 'result': [
572
- obj,
573
- x_list,
574
- {},
575
- ],
576
- 'desc': [
577
- f'list birds or pigs',
578
- ]
579
- },
580
- f"Show {obj_single} list": {
581
- 'train': '',
582
- 'result': [
583
- obj,
584
- x_list,
585
- {},
586
- ],
587
- 'desc': [
588
- f'list birds or pigs',
589
- ]
590
- },
591
- f"{obj_single} list": {
592
- 'train': '',
593
- 'result': [
594
- obj,
595
- x_list,
596
- {},
597
- ],
598
- 'desc': [
599
- f'list birds or pigs',
600
- ]
601
- },
602
- f"What kind of {obj_plural} do you have?": {
603
- 'train': '',
604
- 'result': [
605
- obj,
606
- x_list,
607
- {},
608
- ],
609
- 'desc': [
610
- f'list birds or pigs',
611
- ]
612
- },
613
- f"Are there new kinds of {obj_plural}?": {
614
- 'train': '',
615
- 'result': [
616
- obj,
617
- x_list,
618
- {x_type: 'new'},
619
- ],
620
- 'desc': [
621
- f'list birds or pigs',
622
- ]
623
- },
624
- # slight strange semantics
625
- f"Change {obj_plural}": {
626
- 'train': '',
627
- 'result': [
628
- obj,
629
- x_list,
630
- {}
631
- ],
632
- 'desc': [
633
- f'list birds or pigs',
634
- ]
635
- },
636
- }
637
- self.game_train |= xxx
638
-
639
- print('before add_config')
640
- print(len(self.game_train))
641
- add_config(self.game_train)
642
- print('after add_config')
643
- print(len(self.game_train))
644
-
645
- print('final')
646
- print(len(self.game_train))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/config_const.py DELETED
@@ -1,27 +0,0 @@
1
- # constant
2
-
3
- # object verb
4
- x_change_position = 'change position'
5
- x_change_skin = 'change skin'
6
-
7
- # object
8
- x_bird = 'bird'
9
- x_pig = 'pig'
10
- x_house = 'house'
11
- x_obstacle = 'obstacle'
12
- x_pig_size = 'pig size'
13
- x_bird_size = 'bird size'
14
-
15
- # verb
16
- x_add = 'add'
17
- x_delete = 'delete'
18
- x_list = 'list'
19
- x_increase = 'increase'
20
- x_decrease = 'decrease'
21
-
22
- # attributes
23
- x_quantity = 'quantity'
24
- x_color = 'color'
25
- x_type = 'type'
26
- x_size = 'size'
27
- x_args = 'args'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/game_train.json DELETED
The diff for this file is too large to render. See raw diff
 
games/angrybirds/test_all_angrybirds.py DELETED
@@ -1,305 +0,0 @@
1
- import pytest
2
-
3
- from games.angrybirds.angrybirds import angrybird
4
-
5
- status_OK = 'OK'
6
- status_Failure = 'Failure'
7
- bird = angrybird()
8
- bird.init_emb()
9
-
10
- def ai_test(inp,outp):
11
- result = bird.query_emb(inp)
12
- # result = bird.query_entry_point(inp)
13
- assert result[0] == status_OK
14
- # assert result[1][:2] == outp[:2], f"{inp}, {result}"
15
- assert result[1] == outp, f"{inp}, {result}"
16
-
17
- def test_a00_test():
18
- assert 1 + 1 == 2
19
-
20
- def test_a01_add_bird():
21
- input = 'add a bird'
22
- output = ['bird', 'add', {'quantity': 1}]
23
- ai_test(input, output)
24
-
25
- def test_a02_i_want_add_birds():
26
- input = 'I want add birds'
27
- output = ['bird', 'add', {'quantity': 'some'}]
28
- ai_test(input, output)
29
-
30
- def test_a03_reduce_bird_quantity():
31
- input = 'Reduce a bird'
32
- output = ['bird', 'delete', {'quantity': 1}]
33
- ai_test(input, output)
34
-
35
- def test_a04_bird():
36
- input = 'bird list'
37
- output = ['bird', 'list', {}]
38
- ai_test(input, output)
39
-
40
- def test_a05_show_birds():
41
- input = 'show birds'
42
- output = ['bird', 'list', {}]
43
- ai_test(input, output)
44
-
45
- def test_a06_big_bird():
46
- input = 'Big birds'
47
- output = ['bird', 'add', {'type': 'big', 'quantity':'some'}]
48
- ai_test(input, output)
49
-
50
- def test_a07_add_magnet_bird():
51
- input = 'Add a Magnet Bird'
52
- output = ['bird', 'add', {'type': 'magnet', 'quantity':1}]
53
- ai_test(input, output)
54
-
55
- def test_a08_superheavy():
56
- input = 'remove all superheavy birds'
57
- output = ['bird', 'delete', {'type': 'superheavy', 'quantity':'all'}]
58
- ai_test(input, output)
59
-
60
- def test_a09_catapult_bird():
61
- input = 'add a Catapult bird'
62
- output = ['bird', 'add', {'type': 'catapult','quantity':1}]
63
- ai_test(input, output)
64
-
65
- def test_a10_flash_bird():
66
- input = 'add 5 Flash Birds'
67
- output = ['bird', 'add', {'type': 'flash', 'quantity':5}]
68
- ai_test(input, output)
69
-
70
- def test_a11_antigravity_bird():
71
- input = 'Anti-gravity bird'
72
- output = ['bird', 'add', {'type': 'antigravity', 'quantity':1}]
73
- ai_test(input, output)
74
-
75
- def test_a12_change_bird_picture():
76
- input = "I want to change bird's picture"
77
- output = ['change skin', {'args': 'birds'}]
78
- ai_test(input, output)
79
-
80
- def test_a13_bird_photo():
81
- input = 'bird photo'
82
- output = ['change skin', {'args': 'birds'}]
83
- ai_test(input, output)
84
-
85
- def test_a14_change_birds():
86
- input = 'I want to change birds'
87
- # output = ['change position', {'args': 'birds'}]
88
- # strange semantics
89
- output = ['bird', 'list', {}]
90
- ai_test(input, output)
91
-
92
- def test_a15_add_a_pig():
93
- input = 'add a pig'
94
- output = ['pig', 'add', {'quantity': 1}]
95
- ai_test(input, output)
96
-
97
- def test_a15_add_a_enemy():
98
- input = 'add a enemy'
99
- output = ['pig', 'add', {'quantity': 1}]
100
- ai_test(input, output)
101
-
102
- def test_a16_add_a_pig():
103
- input = 'Add a pig'
104
- output = ['pig', 'add', {'quantity': 1}]
105
- ai_test(input, output)
106
-
107
- def test_a16_add_a_enemy():
108
- input = 'Add a enemy'
109
- output = ['pig', 'add', {'quantity': 1}]
110
- ai_test(input, output)
111
-
112
- def test_a17_reduce_a_pig():
113
- input = 'reduce a pig'
114
- output = ['pig', 'delete', {'quantity': 1}]
115
- ai_test(input, output)
116
-
117
- def test_a17_reduce_a_enemy():
118
- input = 'reduce a enemy'
119
- output = ['pig', 'delete', {'quantity': 1}]
120
- ai_test(input, output)
121
-
122
- def test_a18_list_pigs():
123
- input = 'list pigs'
124
- output = ['pig', 'list', {}]
125
- ai_test(input, output)
126
-
127
- def test_a18_list_enemies():
128
- input = 'list enemies'
129
- output = ['pig', 'list', {}]
130
- ai_test(input, output)
131
-
132
- def test_a19_elderly_pig():
133
- input = 'add an Elderly pig'
134
- output = ['pig', 'add', {'type': 'elderly', 'quantity': 1}]
135
- ai_test(input, output)
136
-
137
- def test_a19_elderly_enemy():
138
- input = 'add an Elderly enemy'
139
- output = ['pig', 'add', {'type': 'elderly', 'quantity': 1}]
140
- ai_test(input, output)
141
-
142
- def test_a20_sport_pig():
143
- input = 'add a sport pig'
144
- output = ['pig', 'add', {'type': 'sport', 'quantity': 1}]
145
- ai_test(input, output)
146
-
147
- def test_a20_sport_enemy():
148
- input = 'add a sport enemy'
149
- output = ['pig', 'add', {'type': 'sport', 'quantity': 1}]
150
- ai_test(input, output)
151
-
152
- def test_a21_pig_picture():
153
- input = 'pig picture'
154
- output = ['change skin', {'args': 'pigs'}]
155
- ai_test(input, output)
156
-
157
- def test_a21_enemy_picture():
158
- input = 'enemy picture'
159
- output = ['change skin', {'args': 'pigs'}]
160
- ai_test(input, output)
161
-
162
- def test_a22_make_the_pig_weaker():
163
- input = 'make the pig weaker'
164
- output = ['pig', 'decrease health points', {'quantity': 1}]
165
- ai_test(input, output)
166
-
167
- def test_a22_make_the_enemy_weaker():
168
- input = 'make the enemy weaker'
169
- output = ['pig', 'decrease health points', {'quantity': 1}]
170
- ai_test(input, output)
171
-
172
- def test_a23_make_the_pig_bigger():
173
- input = 'make the pig bigger'
174
- output = ['pig size', 'increase', {}]
175
- ai_test(input, output)
176
-
177
- def test_a23_make_the_enemy_bigger():
178
- input = 'make the enemy bigger'
179
- output = ['pig size', 'increase', {}]
180
- ai_test(input, output)
181
-
182
- def test_a24_change_pig_position():
183
- input = "change pig's position"
184
- output = ['pig', 'change position', {}]
185
- ai_test(input, output)
186
-
187
- def test_a24_change_enemy_position():
188
- input = "change enemy's position"
189
- output = ['pig', 'change position', {}]
190
- ai_test(input, output)
191
-
192
- def test_a25_move_the_pig():
193
- input = 'move the pig'
194
- output = ['pig', 'change position', {}]
195
- ai_test(input, output)
196
-
197
- def test_a25_move_the_enemy():
198
- input = 'move the enemy'
199
- output = ['pig', 'change position', {}]
200
- ai_test(input, output)
201
-
202
- def test_a26_change_obstacles():
203
- input = 'I want to change the obstacles'
204
- output = ['obstacle', 'change position', {}]
205
- ai_test(input, output)
206
-
207
- def test_a27_():
208
- input = 'background picture'
209
- output = ['change background', {'args': 'picture'}]
210
- ai_test(input, output)
211
-
212
- def test_a28_change_music():
213
- input = 'change music'
214
- output = ['change background', {'args': 'music'}]
215
- ai_test(input, output)
216
-
217
- def test_a29_change_volumn():
218
- input = 'change volumn'
219
- output = ['change background', {'args': 'volumn'}]
220
- ai_test(input, output)
221
-
222
- def test_a30_delete_3_pigs():
223
- input = 'reduce 3 pigs'
224
- output = ['pig', 'delete', {'quantity': 3}]
225
- ai_test(input, output)
226
-
227
- def test_a30_delete_3_enemies():
228
- input = 'reduce 3 enemies'
229
- output = ['pig', 'delete', {'quantity': 3}]
230
- ai_test(input, output)
231
-
232
- def test_a31_delete_5_birds():
233
- input = 'remove five birds'
234
- output = ['bird', 'delete', {'quantity': 5}]
235
- ai_test(input, output)
236
-
237
- def test_a32_bird():
238
- input = 'bird'
239
- output = ['bird', 'list', {}]
240
- ai_test(input, output)
241
-
242
- def test_a33_birds():
243
- input = ' birds'
244
- output = ['bird', 'list', {}]
245
- ai_test(input, output)
246
-
247
- def test_a34_enemy():
248
- input = 'enemy'
249
- output = ['pig', 'list', {}]
250
- ai_test(input, output)
251
-
252
- def test_a34_pig():
253
- input = ' pig '
254
- output = ['pig', 'list', {}]
255
- ai_test(input, output)
256
-
257
- def test_a34_enemy():
258
- input = ' enemy '
259
- output = ['pig', 'list', {}]
260
- ai_test(input, output)
261
-
262
- def test_a35_pigs():
263
- input = ' piGs \t'
264
- output = ['pig', 'list', {}]
265
- ai_test(input, output)
266
-
267
- def test_a35_enemies():
268
- input = ' enemIEs \t'
269
- output = ['pig', 'list', {}]
270
- ai_test(input, output)
271
-
272
- def test_a35_more_birds():
273
- input = 'The game is too difficult. add more birds'
274
- output = ['bird', 'add', {'quantity':'some'}]
275
- ai_test(input, output)
276
-
277
- def test_a36_move_pigs():
278
- input = 'move pigs'
279
- output = ['pig', 'change position', {}]
280
- ai_test(input, output)
281
-
282
- def test_a36_move_enemies():
283
- input = 'move enemies'
284
- output = ['pig', 'change position', {}]
285
- ai_test(input, output)
286
-
287
- def test_a37_move_the_pigs():
288
- input = 'move the pigs'
289
- output = ['pig', 'change position', {}]
290
- ai_test(input, output)
291
-
292
- def test_a37_move_the_enemies():
293
- input = 'move the enemies'
294
- output = ['pig', 'change position', {}]
295
- ai_test(input, output)
296
-
297
- def test_a38_move_this_pig():
298
- input = 'move this pig'
299
- output = ['pig', 'change position', {}]
300
- ai_test(input, output)
301
-
302
- def test_a38_move_this_enemy():
303
- input = 'move this enemy'
304
- output = ['pig', 'change position', {}]
305
- ai_test(input, output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/test_delete_birds.py DELETED
@@ -1,103 +0,0 @@
1
- import pytest
2
-
3
- from games.angrybirds.angrybirds import angrybird
4
-
5
- status_OK = 'OK'
6
- status_Failure = 'Failure'
7
- bird = angrybird()
8
- bird.init_emb()
9
-
10
- def test_00_test():
11
- assert 1 + 1 == 2
12
-
13
- def ai_test(inp,outp):
14
- result = bird.query_emb(inp)
15
- assert result[0] == status_OK
16
- # assert result[1][:2] == outp[:2], f"{inp}, {result}"
17
- assert result[1] == outp, f"{inp}, {result}"
18
-
19
- def test_delete_one_bird():
20
- for bird_name in [
21
- 'big',
22
- 'flash',
23
- ]:
24
- inp = f'remove a {bird_name} bird'
25
- outp = ['bird', 'remove', {'type': bird_name}]
26
- ai_test(inp, outp)
27
-
28
- def test_delete_some_birds():
29
- for bird_name in [
30
- 'big',
31
- 'flash',
32
- ]:
33
- for bird_number, bird_number_numeric in {
34
- 'two': 2,
35
- '2': 2,
36
- 'three': 3,
37
- '3': 3,
38
- }:
39
- inp = f'remove {bird_number} {bird_name} bird'
40
- outp = ['bird', 'remove', {'quantity': bird_number_numeric, 'type': bird_name}]
41
- ai_test(inp, outp)
42
-
43
- def test_delete_ranked_bird():
44
- for bird_rank in [
45
- 'first',
46
- 'second',
47
- 'third',
48
- ]:
49
- inp = f'remove the {bird_rank} bird'
50
- outp = ['bird', 'remove', {'rank': bird_rank, 'quantity': 1}]
51
- ai_test(inp, outp)
52
-
53
- def test_delete_ranked_type_bird():
54
- for bird_rank in [
55
- 'first',
56
- 'second',
57
- 'third',
58
- ]:
59
- for bird_name in [
60
- 'big',
61
- 'flash',
62
- ]:
63
- inp = f'remove the {bird_rank} {bird_name} bird'
64
- outp = ['bird', 'remove', {'type': bird_name, 'rank': bird_rank, 'quantity': 1}]
65
- ai_test(inp, outp)
66
-
67
- def test_delete_ranked_birds():
68
- for bird_rank in [
69
- 'first',
70
- 'last',
71
- ]:
72
- for bird_number, bird_number_numeric in {
73
- 'two': 2,
74
- '2': 2,
75
- 'three': 3,
76
- '3': 3,
77
- }:
78
- inp = f'remove the {bird_rank} {bird_number} birds'
79
- outp = ['bird', 'remove', {'rank': bird_rank, 'quantity': bird_number_numeric}]
80
- ai_test(inp, outp)
81
-
82
- def test_delete_ranked_type_birds():
83
- for bird_rank in [
84
- 'first',
85
- 'last',
86
- ]:
87
- for bird_number, bird_number_numeric in {
88
- 'two': 2,
89
- '2': 2,
90
- 'three': 3,
91
- '3': 3,
92
- }:
93
- for bird_name in [
94
- 'big',
95
- 'flash',
96
- ]:
97
- inp = f'remove the {bird_rank} {bird_number} {bird_name} birds'
98
- outp = ['bird', 'remove', {
99
- 'rank': bird_rank,
100
- 'quantity': bird_number_numeric,
101
- 'type': bird_name,
102
- }]
103
- ai_test(inp, outp)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/angrybirds/test_parameter.py DELETED
@@ -1,26 +0,0 @@
1
- import pytest
2
-
3
- from games.angrybirds.angrybirds import angrybird
4
-
5
- status_OK = 'OK'
6
- status_Failure = 'Failure'
7
- bird = angrybird()
8
- bird.init_emb()
9
-
10
- def test_00_test():
11
- assert 1 + 1 == 2
12
-
13
- def ai_test(inp,outp):
14
- result = bird.query_emb(inp)
15
- assert result[0] == status_OK
16
- # assert result[1][:2] == outp[:2], f"{inp}, {result}"
17
- assert result[1] == outp, f"{inp}, {result}"
18
-
19
- def test_delete_one_bird():
20
- for bird_name in [
21
- 'big',
22
- 'flash',
23
- ]:
24
- inp = f'remove a {bird_name} bird'
25
- outp = ['bird', 'remove', {'type': bird_name}]
26
- ai_test(inp, outp)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/game.py DELETED
@@ -1,129 +0,0 @@
1
- import json
2
- from datetime import datetime
3
- from zoneinfo import ZoneInfo
4
- import glob
5
-
6
- from openai.embeddings_utils import get_embedding as openai_get_embedding
7
- from openai.embeddings_utils import cosine_similarity as openai_cosine_similarity
8
-
9
- debug = 2
10
-
11
- class game:
12
- status_failure = 'Failure'
13
- status_OK = 'OK'
14
-
15
- ai_version = ''
16
- data_version = ''
17
-
18
- def __init__(self):
19
- pass
20
-
21
- def query_entry_point(self, command: str):
22
- status, res, desc, results = \
23
- self.query_emb(command)
24
-
25
- t = datetime.now()
26
- t = t.astimezone(ZoneInfo('Asia/Shanghai'))
27
- # t = t.replace(microsecond=0)
28
-
29
- res1 = {
30
- 'status': status,
31
- 'result': res,
32
- 'desc': desc,
33
- 'command': command,
34
- # 'score': f'{top_sim:.4f}',
35
- 'timestamp': f"{t}",
36
- 'ai-version': self.ai_version,
37
- }
38
-
39
- res2 = []
40
- for i, e in enumerate(results[:]):
41
- tmp = [i, f"{e[1]:.8f}", e[0]]
42
- res2.append(tmp)
43
-
44
- self.query_count += 1
45
- print()
46
- print('-'*20)
47
- print(f'[{self.PATH}] query count: {self.query_count}')
48
- print(f'input: {command}')
49
- print(json.dumps(res1, indent=2))
50
- print(json.dumps(res2, indent=2))
51
- print('%'*20)
52
- print(f'[{self.PATH}] query count: {self.query_count}')
53
- print(f'input: {command}')
54
- print(res1['status'])
55
- print(f'top: {results[0][0]}')
56
- print('-'*20)
57
- print()
58
- return res1, res2
59
-
60
-
61
- def list_functionality(self):
62
- s = []
63
- for cmd in self.train:
64
- desc = self.train[cmd]['desc'][0]
65
- if desc not in s:
66
- s.append(desc)
67
- res = {
68
- 'version': self.data_version,
69
- 'data': [f'({i+1}) {e}' for i, e in enumerate(sorted(s))],
70
- }
71
- return res
72
-
73
-
74
- def show_json_old(self):
75
- s = {}
76
- for cmd in self.train:
77
- s[cmd] = {}
78
- s[cmd]['result'] = self.train[cmd]['result']
79
- res = {
80
- 'version': self.data_version,
81
- 'data': s,
82
- }
83
- return res
84
-
85
-
86
- def show_json(self):
87
- s = {}
88
- for cmd in self.train:
89
- desc = self.train[cmd]['desc'][0]
90
- result = self.train[cmd]['result']
91
- if desc not in s:
92
- s[desc] = [result,]
93
- else:
94
- if result not in s[desc]:
95
- s[desc].append(result)
96
- res = {
97
- 'version': self.data_version,
98
- 'data': s,
99
- }
100
- return res
101
-
102
-
103
- def show_json_x(self):
104
- s = {}
105
- for cmd in self.train:
106
- key = json.dumps(self.train[cmd]['result'])
107
- desc = set(self.train[cmd]['desc'])
108
- if key not in s.keys():
109
- s[key] = desc
110
- else:
111
- s[key] |= desc
112
- res = {
113
- 'version': self.data_version,
114
- 'data': s,
115
- }
116
-
117
- res2 = {}
118
- i = 0
119
- for key in res['data'].keys():
120
- res2 |= {i: [json.loads(key), list(res['data'][key])]}
121
- i += 1
122
-
123
- res = {
124
- 'version': self.data_version,
125
- 'data': res2,
126
- }
127
-
128
- return res
129
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/game_angrybird.py DELETED
@@ -1,23 +0,0 @@
1
- import os
2
- import json
3
- import requests
4
-
5
- from games.angrybirds.angrybirds import angrybird
6
-
7
-
8
- game = angrybird()
9
-
10
-
11
- def process(command: str):
12
- url = f'https://{os.getenv("hfs_space")}.hf.space/games/angrybird'
13
- # url = 'http://127.0.0.1:8080/nlp'
14
- myobj = {
15
- 'command': command,
16
- }
17
- headers = {'Authorization': f'Bearer {os.getenv("hfs_token")}'}
18
-
19
- x = requests.post(url, json=myobj, headers=headers)
20
- print(x.text)
21
-
22
- # res1, _ = game.query_entry_point(command)
23
- return json.loads(x.text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/game_snake.py DELETED
@@ -1,23 +0,0 @@
1
- import os
2
- import json
3
- import requests
4
-
5
- from games.snake.snake import snake
6
-
7
-
8
- game = snake()
9
-
10
-
11
- def process(command: str):
12
- url = f'https://{os.getenv("hfs_space")}.hf.space/games/snake'
13
- # url = 'http://127.0.0.1:8080/nlp'
14
- myobj = {
15
- 'command': command,
16
- }
17
- headers = {'Authorization': f'Bearer {os.getenv("hfs_token")}'}
18
-
19
- x = requests.post(url, json=myobj, headers=headers)
20
- print(x.text)
21
-
22
- # res1, _ = game.query_entry_point(command)
23
- return json.loads(x.text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/game_util.py DELETED
@@ -1,16 +0,0 @@
1
- from fastapi import HTTPException, status
2
-
3
- import games.game_snake as game_snake
4
- import games.game_angrybird as game_angrybird
5
-
6
-
7
- GAME_ANGRY_BIRD = 'angrybird'
8
- GAME_SNAKE = 'snake'
9
-
10
-
11
- def nlp(game: str, token: str, command: str):
12
- if game == GAME_ANGRY_BIRD:
13
- return game_angrybird.process(token, command)
14
- if game == GAME_SNAKE:
15
- return game_snake.process(token, command)
16
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
games/snake/game_train.json DELETED
The diff for this file is too large to render. See raw diff
 
games/snake/game_train2.json DELETED
The diff for this file is too large to render. See raw diff
 
games/snake/snake.py DELETED
@@ -1,37 +0,0 @@
1
- import json
2
- from pathlib import Path
3
-
4
- import openai
5
- from games.game import game
6
- # from games.game_openai import api_key
7
-
8
- debug = 2
9
-
10
- class snake (game):
11
- ai_version = '1.4.0.2023-12-29-a' # fastapi
12
- data_version = ai_version
13
-
14
- def __init__(self):
15
- # openai.api_key = api_key
16
- self.ROOT = Path(__file__).parent.parent.parent
17
- self.PATH = self.__class__.__name__
18
- self.embeddings = {}
19
- self.query_count = 0
20
-
21
- def init_train():
22
- PATH = Path(__file__).parent
23
- with open(PATH/"game_train.json", 'r') as f:
24
- unnormalized = json.load(f)
25
-
26
- self.train = {}
27
- for cmd in unnormalized.keys():
28
- key = cmd.strip().lower()
29
- self.train[key] = unnormalized[cmd]
30
- print(f"{len(self.train)=}")
31
-
32
- # self.train = self.init_train(config)
33
- init_train()
34
-
35
-
36
- def special_case(self, command: str):
37
- return command
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py DELETED
@@ -1,14 +0,0 @@
1
- from fastapi import FastAPI, Body
2
-
3
- import games.game_util as game_util
4
-
5
- app = FastAPI()
6
-
7
-
8
- @app.get("/")
9
- async def root():
10
- return {"message": "PGAI API"}
11
-
12
- @app.post("/nlp")
13
- def test(game: str=Body(), token: str=Body(), command: str=Body()):
14
- return game_util.nlp(game, token, command)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,10 +1,13 @@
1
  fastapi
2
- uvicorn[standard]
3
- openai==0.27.8
4
- matplotlib==3.7.2
5
- matplotlib-inline==0.1.6
6
- plotly==5.15.0
7
- pandas==2.0.3
8
- pandas-stubs==2.1.1.230928
9
- scipy==1.11.4
10
- scikit-learn==1.3.0
 
 
 
 
1
  fastapi
2
+ huggingface-hub
3
+ langchain
4
+ langchain-community
5
+ langchain-huggingface
6
+ langchain_openai
7
+ transformers
8
+ sentence-transformers
9
+ faiss-cpu
10
+ dashscope
11
+ pdfminer.six
12
+ pdfplumber
13
+ # git+https://github.com/east-and-west-magic/pgsoft.git@tag-2024-01-11-a
src/fileservice.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from pgsoft.pgdate.date_utils import beijing
3
+ from pgsoft.pghash.md5 import md5
4
+ import pgsoft.pgfile as pgfile
5
+ from time import sleep
6
+ import json
7
+ import os
8
+
9
+ router = APIRouter(prefix="/file", tags=["File Service"])
10
+ dataset_id = "pgsoft/game"
11
+ tempdir = "game"
12
+ pgai_code = os.environ.get("pgai_code")
13
+ db_token = os.environ.get("db_token")
14
+ if db_token:
15
+ print(db_token[:5])
16
+
17
+
18
+ @router.get("/download")
19
+ def download_file(game: str, token: str, gamecode: str):
20
+ if token != pgai_code:
21
+ print(f"[{beijing()}][download file] failed")
22
+ return {"status": "Failure", "detail": "Invalid token"}
23
+ game = game.strip().lower()
24
+ filename = gamecode.strip() + ".json"
25
+ remotepath = "/".join([game, filename[:2], filename])
26
+ res = pgfile.download(
27
+ dataset_id,
28
+ remotepath=remotepath,
29
+ repo_type="dataset",
30
+ localdir=tempdir,
31
+ token=db_token,
32
+ )
33
+ if not res:
34
+ print(f"[{beijing()}][download file] failed")
35
+ return {"status": "Failure", "detail": "File not found or server error"}
36
+ with open(res, "r") as f:
37
+ outp = json.load(f)
38
+ print(f"[{beijing()}][download file] OK")
39
+ return {"status": "OK", "result": outp}
40
+
41
+
42
+ @router.post("/upload")
43
+ def upload_file(game: str, token: str, content: str):
44
+ if token != pgai_code:
45
+ print(f"[{beijing()}][upload file] failed")
46
+ return {"status": "Failure", "detail": "Invalid token"}
47
+ game = game.strip().lower()
48
+ try:
49
+ content_dict = json.loads(content)
50
+ except json.JSONDecodeError as e:
51
+ print(f"[{beijing()}][upload file] failed, {type(e)}: {e}")
52
+ return {"status": "Failure", "detail": "Invalid JSON"}
53
+
54
+ if not isinstance(content_dict, dict):
55
+ print(f"[{beijing()}][upload file] failed, not a dict")
56
+ return {"status": "Failure", "detail": "not a dict"}
57
+
58
+ needed_keys = ["game-file", "device-id"]
59
+ for key in needed_keys:
60
+ if key not in content_dict:
61
+ print(f'[{beijing()}][upload file] failed, missed "{key}"')
62
+ return {"status": "Failure", "detail": f'missed "{key}"'}
63
+
64
+ if not isinstance(content_dict["device-id"], str):
65
+ print(f'[{beijing()}][upload file] failed, "device-id" is not a str')
66
+ return {"status": "Failure", "detail": '"device-id" is not a str'}
67
+ if not isinstance(content_dict["game-file"], dict):
68
+ print(f'[{beijing()}][upload file] failed, "game-file" is not a dict')
69
+ return {"status": "Failure", "detail": '"game-file" is not a dict'}
70
+
71
+ obj = {
72
+ "upload-time": beijing().__str__(),
73
+ "game-file": content_dict["game-file"],
74
+ }
75
+ maxtry = 5
76
+ for retry in range(maxtry):
77
+ md5code = md5(obj)
78
+ remotepath = "/".join([game, md5code[:2], md5code + ".json"])
79
+ if not pgfile.api.file_exists(
80
+ repo_id=dataset_id,
81
+ filename=remotepath,
82
+ repo_type="dataset",
83
+ token=db_token,
84
+ ):
85
+ break
86
+ sleep(0.1)
87
+ obj["upload-time"] = beijing().__str__()
88
+ maxtry -= 1
89
+ if not maxtry and pgfile.api.file_exists(
90
+ repo_id=dataset_id,
91
+ filename=remotepath,
92
+ repo_type="dataset",
93
+ token=db_token,
94
+ ):
95
+ print(f"[{beijing()}][upload file] failed, timeout, please retry")
96
+ return {"status": "Failure", "detail": "timeout, please retry"}
97
+ filedir = os.path.join(tempdir, game, md5code[:2])
98
+ if not os.path.exists(filedir):
99
+ os.makedirs(filedir)
100
+ filepath = os.path.join(filedir, md5code + ".json")
101
+ content_indented = json.dumps(content_dict, indent=4)
102
+ with open(filepath, "w") as f:
103
+ f.write(content_indented)
104
+ res = pgfile.upload(
105
+ filepath,
106
+ remotepath,
107
+ dataset_id,
108
+ "dataset",
109
+ db_token,
110
+ f"Updated at {beijing()}",
111
+ )
112
+ if not res:
113
+ print(f"[{beijing()}][upload file] failed")
114
+ return {"status": "Failure", "detail": "server error"}
115
+ print(f"[{beijing()}][upload file] OK")
116
+ return {"status": "OK", "result": md5code}
117
+
118
+
119
+ @router.get("/list")
120
+ def list_files(game: str, token: str):
121
+ if token != pgai_code:
122
+ print(f"[{beijing()}][list files] failed")
123
+ return {"status": "Failure", "detail": "Invalid token"}
124
+ game = game.strip().lower()
125
+ games = pgfile.list_files(
126
+ repo_id=dataset_id,
127
+ repo_type="dataset",
128
+ token=db_token,
129
+ )
130
+ if games is None:
131
+ print(f"[{beijing()}][list files] failed")
132
+ return {"status": "Failure", "detail": "server error"}
133
+ games = {
134
+ item.split(".")[0][-32:]: item
135
+ for item in games
136
+ if item.endswith(".json") and item.startswith(game)
137
+ }
138
+ print(f"[{beijing()}][list files] OK")
139
+ return {"status": "OK", "result": games}
src/main.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from . import fileservice
3
+ from . import talk_to_your_manual
4
+
5
+ app = FastAPI()
6
+ # app.include_router(fileservice.router)
7
+ app.include_router(talk_to_your_manual.router)
8
+
9
+
10
+ @app.get("/")
11
+ def root():
12
+ return {"message": "Server for Prove of Concept"}
src/talk_to_your_manual/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from . import use_aliyun
3
+ from . import use_huggingface
4
+
5
+
6
+ router = APIRouter(
7
+ prefix="/talk-to-your-manual",
8
+ tags=["Talk To Your Manual"],
9
+ )
10
+ router.include_router(use_aliyun.router)
11
+ # router.include_router(use_huggingface.router)
src/talk_to_your_manual/use_aliyun.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dashscope import Application
2
+ from fastapi import APIRouter
3
+ from fastapi.responses import JSONResponse
4
+ import os
5
+
6
+ router = APIRouter()
7
+ API_KEY = os.environ.get("API_KEY")
8
+ APP_ID = os.environ.get("APP_ID")
9
+
10
+
11
+ @router.get("/aliyun")
12
+ async def call_aliyun(prompt: str):
13
+ response = Application.call(
14
+ api_key=API_KEY,
15
+ app_id=APP_ID,
16
+ prompt=prompt,
17
+ )
18
+ return JSONResponse(
19
+ status_code=response.status_code,
20
+ content={
21
+ "request_id": response.request_id,
22
+ "message": response.message,
23
+ "output": response.output,
24
+ "usage": response.usage,
25
+ },
26
+ )
src/talk_to_your_manual/use_huggingface.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import BloomForCausalLM, BloomTokenizerFast
2
+ from langchain.chains import RetrievalQA
3
+ from langchain_community.vectorstores import FAISS
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain_community.document_loaders import PDFPlumberLoader
6
+ from langchain_huggingface import HuggingFaceEndpointEmbeddings
7
+ from langchain_huggingface import HuggingFacePipeline
8
+ from transformers import pipeline
9
+ from fastapi import APIRouter, status
10
+ from fastapi.responses import JSONResponse
11
+ import os
12
+
13
+ router = APIRouter()
14
+
15
+ # 查询文本
16
+ query = "游戏的主要玩法是什么?"
17
+ max_new_tokens = 100
18
+
19
+ # 加载模型和tokenizer
20
+ db_token = os.environ.get("db_token")
21
+ model = BloomForCausalLM.from_pretrained(
22
+ "bigscience/bloom-560m",
23
+ token=db_token,
24
+ )
25
+ tokenizer = BloomTokenizerFast.from_pretrained(
26
+ "bigscience/bloom-560m",
27
+ token=db_token,
28
+ )
29
+
30
+ # 加载文档内容
31
+ loader = PDFPlumberLoader("建造大楼游戏说明.pdf")
32
+ documents = loader.load()
33
+ splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
34
+ documents = splitter.split_documents(documents)
35
+ # 使用 Sentence-BERT 模型将文档转化为向量
36
+ embeddings = HuggingFaceEndpointEmbeddings(
37
+ repo_id="sentence-transformers/all-MiniLM-L6-v2",
38
+ huggingfacehub_api_token=db_token,
39
+ )
40
+ # 使用 FAISS 创建索引
41
+ faiss_index = FAISS.from_documents(documents, embeddings)
42
+ # 保存索引
43
+ faiss_index.save_local("faiss_index")
44
+ # 从 FAISS 索引中检索相关文档
45
+ retriever = faiss_index.as_retriever()
46
+
47
+ # 创建 Hugging Face Pipeline 以使用 BLOOM 模型
48
+ hf_pipeline = pipeline(
49
+ "text-generation",
50
+ model=model,
51
+ tokenizer=tokenizer,
52
+ max_new_tokens=max_new_tokens,
53
+ )
54
+
55
+ # 使用 LangChain 的 HuggingFacePipeline 类
56
+ llm = HuggingFacePipeline(pipeline=hf_pipeline)
57
+
58
+ # 创建问答链
59
+ qa_chain = RetrievalQA.from_chain_type(
60
+ llm=llm,
61
+ retriever=retriever,
62
+ return_source_documents=True,
63
+ )
64
+
65
+
66
+ @router.get("/huggingface")
67
+ async def call_huggingface(prompt: str):
68
+ try:
69
+ response = qa_chain.invoke({"query": prompt})
70
+ text: str = response["result"]
71
+ text = text.split("\nHelpful Answer: ")[1]
72
+ text = text.split("\n\n")[0]
73
+ return JSONResponse(
74
+ status_code=status.HTTP_200_OK,
75
+ content={
76
+ "result": text,
77
+ },
78
+ )
79
+ except Exception as e:
80
+ return JSONResponse(
81
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
82
+ content={
83
+ "error": str(e),
84
+ },
85
+ )