-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.py
610 lines (501 loc) · 22.8 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
import re
import base64
import os
import requests
import json
import time
import configparser
import random
import threading
import renpy
running_state = False
background_list = []
if_already = False
character_list = []
game_directory = renpy.config.basedir
# game_directory = r"D:\renpy-8.1.1-sdk.7z\PROJECT"#测试用,一般不要开,要开换成自己的地址
game_directory = os.path.join(game_directory, "game")
images_directory = os.path.join(game_directory, "images")
audio_directory = os.path.join(game_directory, "audio")
config = configparser.ConfigParser()
config.read(rf"{game_directory}\config.ini", encoding='utf-8')
def gpt(system, prompt):
config = configparser.ConfigParser()
config.read(rf"{game_directory}\config.ini", encoding='utf-8')
key = config.get('CHATGPT', 'GPT_KEY')
url = config.get('CHATGPT', 'BASE_URL')
model = config.get('CHATGPT', 'model')
payload = json.dumps({
"model": model,
"messages": [
{
"role": "system",
"content": system
},
{
"role": "user",
"content": prompt
}
]
})
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {key}',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
content = json.loads(response.text)['choices'][0]['message']['content']
return content
def separate_content(text):
title_pattern = re.compile(r"标题:(.+)")
outline_pattern = re.compile(r"大纲:(.+?)背景:", re.DOTALL)
background_pattern = re.compile(r"背景:(.+?)人物:", re.DOTALL)
characters_pattern = re.compile(r"人物:(.+)", re.DOTALL)
title = title_pattern.search(text).group(1).strip()
outline = outline_pattern.search(text).group(1).strip()
background = background_pattern.search(text).group(1).strip()
characters = characters_pattern.search(text).group(1).strip()
information = (title, outline, background, characters)
return information
# ----------------------------------------------------------------------
online_draw_key = config.get('AI绘画', '绘画key')
url = "https://cn.tensorart.net/v1/jobs"
headers = {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": f"Bearer {online_draw_key}"
}
def online_generate(prompt, mode):
print("云端启动绘画")
# TMND:611399039965066695
# 天空:611437926598989702
requests_id = ''.join([str(random.randint(0, 9)) for _ in range(10)])
if mode == 'background':
width = 960
height = 540
prompt2 = "(no_human)" + prompt
if config.get('AI绘画', '人物绘画模型ID(本地模式不填)'):
model = config.get('AI绘画', '人物绘画模型ID(本地模式不填)')
else:
model = "611399039965066695"
else:
width = 512
height = 768
prompt2 = "(upper_body),solo" + prompt
if config.get('AI绘画', '背景绘画模型ID(本地模式不填)'):
model = config.get('AI绘画', '背景绘画模型ID(本地模式不填)')
else:
model = "611437926598989702"
data = {
"request_id": str(requests_id),
"stages": [
{
"type": "INPUT_INITIALIZE",
"inputInitialize": {
"seed": -1,
"count": 1
}
},
{
"type": "DIFFUSION",
"diffusion": {
"width": width,
"height": height,
"prompts": [{"text": prompt2}],
"steps": 25,
"sdVae": "animevae.pt",
"sd_model": model,
"clip_skip": 2,
"cfg_scale": 7
}
},
{
"type": "IMAGE_TO_UPSCALER",
"image_to_upscaler": {
"hr_upscaler": "R-ESRGAN 4x+ Anime6B",
"hr_scale": 2,
"hr_second_pass_steps": 10,
"denoising_strength": 0.3
}
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
id = json.loads(response.text)['job']['id']
return id
else:
print(f"请求失败,状态码:{response.status_code},请检查是否正确填写了key")
def get_result(job_id, image_name):
while True:
time.sleep(1)
response = requests.get(f"{url}/{job_id}", headers=headers)
get_job_response_data = json.loads(response.text)
if 'job' in get_job_response_data:
job_dict = get_job_response_data['job']
job_status = job_dict.get('status')
if job_status == 'SUCCESS':
url2 = job_dict["successInfo"]["images"][0]["url"]
response = requests.get(url2)
with open(fr'{images_directory}\{image_name}.png', 'wb') as f:
f.write(response.content)
break
elif job_status == 'FAILED':
print(job_dict)
break
def generate_image_pro(prompt, image_name, mode):
id = online_generate(prompt, mode)
get_result(id, image_name)
def generate_audio_pro(content, speaker, output_name):
if speaker == 1:
speaker = "罗刹【中】"
elif speaker == 2:
speaker = "花火【中】"
elif speaker == 3:
speaker = "流萤【中】"
elif speaker == 4:
speaker = "藿藿【中】"
elif speaker == 5:
speaker = "三月七【中】"
else:
speaker = "符玄【中】"
data = {
"access_token": config.get('SOVITS', '语音key'),
"type": "tts",
"brand": "bert-vits2",
"name": "sr",
"prarm": {
"speaker": speaker,
"text": content,
"sdp_ratio": 0.2,
"noise_scale": 0.6,
"noise_scale_w": 0.9,
"length_scale": 1.0,
"language": "ZH",
"cut_by_sent": True,
"interval_between_sent": 0.2,
"interval_between_para": 1.0,
"style_text": None,
"style_weight": 0.7
}
}
headers = {
'Content-Type': 'application/json',
}
url = 'https://infer.acgnai.top/infer/gen'
response = requests.post(url, data=json.dumps(data), headers=headers)
if response.status_code == 200:
response_data = json.loads(response.text)
mp3_url = response_data["audio"]
with requests.get(mp3_url, stream=True) as r:
# 检查请求是否成功
r.raise_for_status()
# 以流的方式写入文件
with open(fr'{audio_directory}\{output_name}.wav', 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print(f'音频已下载: {output_name}.wav')
else:
print('Failed:', response.status_code, response.text)
def generate_music(prompt, filename):
def run(prompt):
url = config.get("音乐", "base_url")
url1 = f"https://{url}/suno/submit/music"
key = config.get("音乐", "key")
sad = "Pure music, light music, game,galgame,piano,sad"
common = "Pure music, light music, relaxed,cafe,game,galgame,piano"
payload = {
"prompt": "a",
"tags": sad if prompt == "sad" else common,
"mv": "chirp-v3-5",
"title": "BGM",
"make_instrumental": True
}
headers = {
'Authorization': f'Bearer {key}',
'Accept': 'application/json',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
response = requests.post(url1, headers=headers, json=payload)
id = json.loads(response.text)["data"]
return id
def download_music(id, filename):
url = config.get("音乐", "base_url")
url2 = f"https://{url}/suno/fetch/{id}"
key = config.get("音乐", "key")
payload = {}
headers = {
'Authorization': f'Bearer {key}',
'Accept': 'application/json',
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
'Content-Type': 'application/json'
}
while True:
response = requests.request("GET", url2, headers=headers, data=payload)
json.loads(response.text)
response_data = json.loads(response.text)
if response_data['data']["status"] == 'SUCCESS':
audio_urls = [item["audio_url"] for item in response_data["data"]["data"]]
with requests.get(audio_urls[0], stream=True) as r:
with open(fr"{game_directory}/music/{filename}.mp3", 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print(f"文件 {filename} 已下载。")
with requests.get(audio_urls[0], stream=True) as r:
with open(fr"{game_directory}/music/{filename}2.mp3", 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print(f"文件 {filename}2 已下载。")
break
download_music(run(prompt), filename)
# ----------------------------------------------------------------------
def generate_image(prompt, image_name, mode):
global images_directory
url = "http://127.0.0.1:7860"
if mode == 'background':
width = 960
height = 540
prompt2 = "(no_human)"
model = "tmndMix_tmndMixVPruned.safetensors [d9f11471a8]"
else:
width = 512
height = 768
prompt2 = "(upper_body),solo"
model = "天空之境.safetensors [c1d961233a]"
payload = {
"prompt": f"masterpiece,wallpaper,simple background,{prompt},{prompt2}",
"negative_prompt": "Easynagative,bad,worse,nsfw",
"steps": 30,
"sampler_name": "DPM++ 2M SDE",
"width": width,
"height": height,
"restore_faces": False,
"enable_hr": True,
"hr_upscaler": "R-ESRGAN 4x+ Anime6B",
"hr_scale": 2,
"hr_second_pass_steps": 15,
"denoising_strength": 0.3
}
try:
response = requests.post(url=f'{url}/sdapi/v1/txt2img', json=payload)
if response.status_code == 200:
r = response.json()
for i, img_data in enumerate(r['images']):
if ',' in img_data:
base64_data = img_data.split(",", 1)[1]
else:
base64_data = img_data
image_data = base64.b64decode(base64_data)
final_image_name = f'{image_name}.png'
with open(fr'{images_directory}\{final_image_name}', 'wb') as f:
f.write(image_data)
print(f'图片已保存为 {final_image_name}')
else:
print("Failed to generate image:", response.text)
except:
print("绘图失败!")
def generate_audio(response, name, output_name):
global audio_directory
config = configparser.ConfigParser()
config.read(rf"{game_directory}\config.ini", encoding='utf-8')
json_data = {
"gpt_model_path": config.get('SOVITS', 'gpt_model_path'),
"sovits_model_path": config.get('SOVITS', 'sovits_model_path')
}
if name == 1:
url = config.get('SOVITS', 'sovits_url1').format(response=response)
elif name == 2:
url = config.get('SOVITS', 'sovits_url2').format(response=response)
elif name == 3:
url = config.get('SOVITS', 'sovits_url3').format(response=response)
elif name == 4:
url = config.get('SOVITS', 'sovits_url4').format(response=response)
elif name == 5:
url = config.get('SOVITS', 'sovits_url5').format(response=response)
else:
url = config.get('SOVITS', 'sovits_url6').format(response=response)
requests.post('http://127.0.0.1:9880/set_model', json=json_data)
try:
response = requests.get(url)
with open(rf'{audio_directory}\{output_name}.wav', 'wb') as file:
file.write(response.content)
except Exception as e:
print("语音错误", e)
def add_dialogue_to_json(character, text, background_image, audio):
global game_directory
try:
with open(rf"{game_directory}\dialogues.json", "r", encoding="utf-8") as file:
dialogues = json.load(file)
dialogues["conversations"].append({
"character": character,
"text": text,
"background_image": background_image,
"audio": audio
})
with open(rf"{game_directory}\dialogues.json", "w", encoding="utf-8") as file:
json.dump(dialogues, file, indent=4, ensure_ascii=False)
print("新的对话已成功添加到dialogues.json文件中")
except FileNotFoundError:
print("错误:找不到文件 dialogues.json")
except Exception as e:
print(f"发生错误:{e}")
def rembg(pic):
global images_directory
url = "http://localhost:7000/api/remove"
file_path = rf"{images_directory}/{pic}.png"
with open(file_path, 'rb') as file:
response = requests.post(url, files={'file': file})
with open(file_path, 'wb') as output_file:
output_file.write(response.content)
def choose_story():
with open(rf"{game_directory}\story.txt", 'r', encoding='utf-8') as file:
book = file.read()
choices = gpt("你是galgame剧情家,精通各种galgame写作",
f"根据galgame剧情,以男主角的视角,设计男主角接下来的三个分支选项。内容:{book},返回格式:1.xxx\n2.xxx\n3.xxx,要求每个选项尽量简短。不要使用markdown语法。")
cleaned_text = '\n'.join([line.split('. ', 1)[1] if '. ' in line else line for line in choices.strip().split('\n')])
with open(rf"{game_directory}\choice.txt", 'w', encoding='utf-8') as file:
file.write(cleaned_text)
return cleaned_text
def main():
global book, game_directory, if_already, character_list
config = configparser.ConfigParser()
config.read(rf"{game_directory}\config.ini", encoding='utf-8')
if config.getboolean('音乐', '音乐生成'):
thread1 = threading.Thread(target=generate_music, args=("common", "happy bgm"))
thread2 = threading.Thread(target=generate_music, args=("sad", "sad bgm"))
thread1.start()
thread2.start()
with open(rf'{game_directory}\dialogues.json', 'w') as file:
file.write("""{\n"conversations": [\n]\n}""")
with open(rf"{game_directory}\characters.txt", 'w') as file:
file.write('')
theme = config.get('剧情', '剧本的主题')
title, outline, background, characters = separate_content(
gpt("现在你是一名gal game剧情设计师,精通写各种各样的gal game剧情,不要使用markdown格式",
f"现在请你写一份gal game的标题,大纲,背景,人物,我给出的主题和要求是{theme},你的输出格式为:标题:xx\n大纲:xx\n背景:xx\n人物:xx(每个人物占一行,人物不多于5人),每个人物的格式是人物名:介绍,无需序号。男主角也要名字").replace(
":", ":"))
book = gpt("现在你是一名galgame剧情作家,精通写各种各样的galgame剧情,请不要使用markdown格式",
f"现在根据以下内容开始写第一章:gal game标题:{title},gal game大纲:{outline},gal game背景:{background},galgame角色:{characters}。你的输出格式应该为对话模式,例xxx:xx表达,你的叙事节奏要非常非常慢,可以加一点新的内容进去。需要切换地点时,在句尾写[地点名],[地点名]不可单独一行,不用切换则不写,开头第一句是旁白而且必须要包含地点[],地点理论上不应该超过3处。不需要标题。输出例子:旁白:xxx[地点A]\n角色A:xxx\n角色B:xxx\n角色:xxx[地点B]\n旁白:xxx,角色名字要完整。剧情对话不要加双引号")
lines = book.split('\n') # 去掉文本最后一行
book = '\n'.join(lines[:-1])
booklines = book.splitlines()
print(book)
with open(rf"{game_directory}\story.txt", 'w', encoding='utf-8') as file:
file.write(f"{book}\n")
with open(rf"{game_directory}\character_info.txt", 'w', encoding='utf-8') as file:
file.write(characters)
characterslines = characters.splitlines()
characterslines = [item for item in characterslines if ":" in item]
print(characterslines)
for i in range(len(characterslines)):
prompt = gpt(
"根据人物设定给出相应的人物形象,应该由简短的英文单词或短句组成,输出格式样例:a girl,pink hair,black shoes,long hair,young,lovely。请注意,人名与实际内容无关无需翻译出来,只输出英文单词,不要输出多余的内容",
f"人物形象{characterslines[i]}")
name = characterslines[i].split(":", 1)[0]
name = re.sub(r'[^\u4e00-\u9fa5]', '', name) # 标准化名字
if config.getboolean('AI绘画', '云端模式'):
generate_image_pro(prompt, name, "character")
else:
generate_image(prompt, name, "character")
rembg(name)
character_list.append(name)
with open(rf"{game_directory}\characters.txt", "a", encoding='utf-8') as file:
file.write(f"{name}\n")
for i in booklines:
if i.strip() != "":
background = re.findall(r'(?<=\[).*?(?=\])', i)
if background and background[0] not in background_list:
prompt = gpt(
"把下面的内容翻译成英文并且变成短词,比如red,apple,big这样。请注意,地名与实际内容无关无需翻译出来,例如星之学院应该翻译成academy而不是star academy。你应该只返回英文单词,下面是你要翻译的内容:",
background[0])
print(prompt)
if config.getboolean('AI绘画', '云端模式'):
generate_image_pro(prompt, background[0], "background")
else:
generate_image(prompt, background[0], "background")
background_image = background[0]
background_list.append(background_image)
else:
background_image = ""
i = i.replace(":", ":")
i = "旁白:" + i if ":" not in i else i
character, text = i.split(":", 1)
text1 = re.sub(r'\[.*?\]', '', text)
text2 = re.sub(r'\([^)]*\)', '', text1.replace("(", "(").replace(")", ")"))
try:
index = character_list.index(character)
audio_num = index + 1
except ValueError:
print(f"{character} 不在列表中")
audio_num = 6
if character != "旁白":
if config.getboolean('SOVITS', '云端模式'):
generate_audio_pro(text2, audio_num, text1)
else:
generate_audio(text2, audio_num, text1)
character = "" if character == "旁白" else character
if text != "":
add_dialogue_to_json(character, text2, background_image, text1)
choose_story()
if_already = True
def story_continue(choice):
global book, running_state, game_directory, character_list
running_state = True
with open(rf"{game_directory}\story.txt", 'r', encoding='utf-8') as file:
book = file.read()
with open(rf"{game_directory}\character_info.txt", 'r', encoding='utf-8') as file:
character_info = file.read()
add_book = gpt(
"现在你是一名galgame剧情设计师,精通写各种各样的galgame剧情。只输出文本,不要输出任何多余的。不要使用markdown格式,如果需要切换场景在对话的后面加上[地点],输出例子:旁白:xxx[地点A]\n角色A:xxx\n角色B:xxx\n角色:xxx[地点B]\n旁白:xxx,角色名字要完整。",
f"请你根据以下内容继续续写galgame剧情。只返回剧情。人物设定:{character_info},内容:{book},我选则的分支是{choice}")
booklines = add_book.splitlines()
book = book + "\n" + add_book
with open(rf'{game_directory}\story.txt', 'w', encoding='utf-8') as file:
file.write(f"{book}\n")
for i in booklines:
if i.strip() != "":
background = re.findall(r'(?<=\[).*?(?=\])', i)
if background and background[0] not in background_list:
prompt = gpt(
"把下面的内容翻译成英文并且变成短词,比如red,apple,big这样。请注意,地名与实际内容无关无需翻译出来,例如星之学院应该翻译成academy而不是star academy。你应该只返回英文单词,下面是你要翻译的内容:",
background[0])
print(prompt)
cloud_mode = config.getboolean('AI绘画', '云端模式')
if cloud_mode:
generate_image_pro(prompt, background[0], "background")
else:
generate_image(prompt, background[0], "background")
background_image = background[0]
background_list.append(background_image)
else:
background_image = ""
i = i.replace(":", ":")
i = "旁白:" + i if ":" not in i else i
character, text = i.split(":", 1)
text1 = re.sub(r'\[.*?\]', '', text) # 去除地点
text2 = re.sub(r'\([^)]*\)', '', text1.replace("(", "(").replace(")", ")")) # 去除小括号
try:
with open(rf"{game_directory}\characters.txt", 'r', encoding='utf-8') as file:
line_number = 0
for line in file:
line_number += 1
if character in line:
audio_num = line_number
except ValueError:
print(f"{character} 不在列表中")
audio_num = 6
if character != "旁白" and character != "new":
if config.getboolean('SOVITS', '云端模式'):
generate_audio_pro(text2, audio_num, text1)
else:
generate_audio(text2, audio_num, text1)
character = "" if character == "旁白" else character
if text != "":
add_dialogue_to_json(character, text2, background_image, text1)
choose_story()
running_state = False
if __name__ == "__main__":
main()