app.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import enum
  3. import os
  4. import json
  5. import shutil
  6. import slugify
  7. import time
  8. import cv2
  9. import gradio as gr
  10. import numpy as np
  11. import torch
  12. from glob import glob
  13. import platform
  14. from PIL import Image
  15. from importlib.util import find_spec
  16. from facechain.inference_fact import GenPortrait
  17. from facechain.inference_inpaint_fact import GenPortrait_inpaint
  18. from facechain.utils import snapshot_download, check_ffmpeg, project_dir, join_worker_data_dir
  19. from train_style.demo import set_img, init_tag, cut_img, train_lora, set_prompt
  20. from facechain.constants import neg_prompt as neg, pos_prompt_with_cloth, pos_prompt_with_style, \
  21. pose_examples, base_models, tts_speakers_map
  22. inference_done_count = 0
  23. character_model = 'ly261666/cv_portrait_model'
  24. BASE_MODEL_MAP = {
  25. "leosamsMoonfilm_filmGrain20": "写实模型(Realistic sd_1.5 model)",
  26. "MajicmixRealistic_v6": "\N{fire}写真模型(Photorealistic sd_1.5 model)",
  27. }
  28. class UploadTarget(enum.Enum):
  29. PERSONAL_PROFILE = 'Personal Profile'
  30. LORA_LIaBRARY = 'LoRA Library'
  31. # utils
  32. def concatenate_images(images):
  33. heights = [img.shape[0] for img in images]
  34. max_width = sum([img.shape[1] for img in images])
  35. concatenated_image = np.zeros((max(heights), max_width, 3), dtype=np.uint8)
  36. x_offset = 0
  37. for img in images:
  38. concatenated_image[0:img.shape[0], x_offset:x_offset + img.shape[1], :] = img
  39. x_offset += img.shape[1]
  40. return concatenated_image
  41. def select_function(evt: gr.SelectData):
  42. name = evt.value[1] if isinstance(evt.value, (tuple, list)) else evt.value
  43. matched = list(filter(lambda item: name == item['name'], styles))
  44. style = matched[0]
  45. return gr.Text.update(value=style['name'], visible=True)
  46. def select_function_multi(evt: gr.SelectData):
  47. tag = evt.value[1]
  48. impath = evt.value[0]
  49. return gr.Text.update(value=impath), gr.Text.update(value=tag)
  50. def get_selected_image(state_image_list, evt: gr.SelectData):
  51. return state_image_list[evt.index]
  52. def upload_file(files, current_files):
  53. file_paths = [file_d['name'] for file_d in current_files] + [file.name for file in files]
  54. return file_paths
  55. def update_prompt(style_model, style_choice, uuid):
  56. if not uuid:
  57. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  58. raise gr.Error("请登陆后使用! (Please login first)")
  59. else:
  60. uuid = 'qw'
  61. if style_choice == 0:
  62. matched = list(filter(lambda item: style_model == item['name'], styles))
  63. style = matched[0]
  64. pos_prompt = generate_pos_prompt(style['name'], style['add_prompt_style'])
  65. multiplier_style = style['multiplier_style']
  66. multiplier_human = style['multiplier_human']
  67. else:
  68. f = open(f'{project_dir}/workspace/{uuid}/style_lora/{style_model}/add_prompt_style.txt', 'r')
  69. add_prompt_style = f.read()
  70. f.close()
  71. pos_prompt = pos_prompt_with_style.format(add_prompt_style)
  72. multiplier_style = 0.8
  73. return gr.Textbox.update(value=pos_prompt), \
  74. gr.Slider.update(value=multiplier_style)
  75. def update_pose_model(pose_image, pose_model):
  76. if pose_image is None:
  77. return gr.Radio.update(value=pose_models[0]['name']), gr.Image.update(visible=False)
  78. else:
  79. if pose_model == 0:
  80. pose_model = 1
  81. pose_res_img = preprocess_pose(pose_image)
  82. return gr.Radio.update(value=pose_models[pose_model]['name']), gr.Image.update(value=pose_res_img, visible=True)
  83. def generate_pos_prompt(style_model, prompt_cloth):
  84. if style_model is not None:
  85. matched = list(filter(lambda style: style_model == style['name'], styles))
  86. if len(matched) == 0:
  87. raise ValueError(f'styles not found: {style_model}')
  88. matched = matched[0]
  89. if matched['model_id'] is None:
  90. pos_prompt = pos_prompt_with_cloth.format(prompt_cloth)
  91. else:
  92. pos_prompt = pos_prompt_with_style.format(matched['add_prompt_style'])
  93. else:
  94. pos_prompt = pos_prompt_with_cloth.format(prompt_cloth)
  95. return pos_prompt
  96. def launch_pipeline(uuid,
  97. style_choice,
  98. pos_prompt,
  99. neg_prompt=None,
  100. user_images=None,
  101. num_images=1,
  102. style_model=None,
  103. lora_choice=None,
  104. multiplier_style=0.35,
  105. pose_image=None,
  106. use_face_swap=0
  107. ):
  108. if not uuid:
  109. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  110. raise gr.Error("请登陆后使用! (Please login first)")
  111. else:
  112. uuid = 'qw'
  113. # Check style model
  114. if style_choice == None:
  115. raise gr.Error('请选择风格模型(Please select the style model)!')
  116. if style_model == None and lora_choice == 'preset':
  117. raise gr.Error('请选择风格模型(Please select the style model)!')
  118. before_queue_size = 0
  119. before_done_count = inference_done_count
  120. if style_choice == 0:
  121. matched = list(filter(lambda item: style_model == item['name'], styles))
  122. if len(matched) == 0:
  123. raise ValueError(f'styles not found: {style_model}')
  124. matched = matched[0]
  125. style_model = matched['name']
  126. if lora_choice == 'preset':
  127. if style_choice == 1:
  128. style_model_path = os.path.join(f'{project_dir}/workspace/{uuid}/style_lora', style_model, 'lora_weights.safetensors')
  129. base_model_index = 0
  130. elif matched['model_id'] is None:
  131. style_model_path = None
  132. base_model_index = 0
  133. else:
  134. model_dir = snapshot_download(matched['model_id'], revision=matched['revision'])
  135. style_model_path = os.path.join(model_dir, matched['bin_file'])
  136. base_model_index = matched['base_model_index']
  137. else:
  138. print(f'uuid: {uuid}')
  139. temp_lora_dir = join_worker_data_dir(uuid, 'temp_lora')
  140. file_name = lora_choice
  141. print(lora_choice.split('.')[-1], os.path.join(temp_lora_dir, file_name))
  142. if lora_choice.split('.')[-1] != 'safetensors' or not os.path.exists(os.path.join(temp_lora_dir, file_name)):
  143. raise ValueError(f'Invalid lora file: {lora_file.name}')
  144. style_model_path = os.path.join(temp_lora_dir, file_name)
  145. base_model_index = 1
  146. num_images = min(6, num_images)
  147. print('base model index: ', base_model_index)
  148. outputs = gen_portrait(use_face_swap, num_images, base_model_index, style_model_path, pos_prompt, neg_prompt, user_images[0]['name'], pose_image, multiplier_style)
  149. outputs_RGB = []
  150. for out_tmp in outputs:
  151. outputs_RGB.append(cv2.cvtColor(out_tmp, cv2.COLOR_BGR2RGB))
  152. if len(outputs) > 0:
  153. yield ["生成完毕(Generation done)!", outputs_RGB]
  154. else:
  155. yield ["生成失败, 请重试(Generation failed, please retry)!", outputs_RGB]
  156. def launch_pipeline_inpaint(uuid,
  157. user_images,
  158. num_faces=1,
  159. selected_face=1,
  160. template_image=None,
  161. use_face_swap=0):
  162. if not uuid:
  163. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  164. raise gr.Error("请登陆后使用! (Please login first)")
  165. else:
  166. uuid = 'qw'
  167. # if isinstance(user_image, str):
  168. # if len(user_image) == 0:
  169. # raise gr.Error('请选择一张用户图像(Please select 1 user image)')
  170. if isinstance(template_image, str):
  171. if len(template_image) == 0:
  172. raise gr.Error('请选择一张模板(Please select 1 template)')
  173. multiplier_style = 0.05
  174. strength = 0.6
  175. output_img_size = 512
  176. pos_prompt = 'raw photo, masterpiece, simple background, solo, medium shot, high detail face, photorealistic, best quality, wearing T-shirt'
  177. neg_prompt = 'nsfw, paintings, sketches, (worst quality:2), (low quality:2) ' \
  178. 'lowers, normal quality, ((monochrome)), ((grayscale)), logo, word, character'
  179. outputs = gen_portrait_inpaint(use_face_swap, template_image,
  180. strength,
  181. output_img_size,
  182. num_faces,
  183. selected_face,
  184. pos_prompt,
  185. neg_prompt,
  186. user_images[0]['name'])
  187. outputs_RGB = []
  188. for out_tmp in outputs:
  189. outputs_RGB.append(cv2.cvtColor(out_tmp, cv2.COLOR_BGR2RGB))
  190. if len(outputs) > 0:
  191. yield ["生成完毕(Generation done)!", outputs_RGB]
  192. else:
  193. yield ["生成失败,请重试(Generation failed, please retry)!", outputs_RGB]
  194. def update_lora_choice(uuid):
  195. if not uuid:
  196. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  197. raise gr.Error("请登陆后使用! (Please login first)")
  198. else:
  199. uuid = 'qw'
  200. print("uuid: ", uuid)
  201. temp_lora_dir = join_worker_data_dir(uuid, 'temp_lora')
  202. if not os.path.exists(temp_lora_dir):
  203. os.makedirs(temp_lora_dir)
  204. lora_list = sorted(os.listdir(temp_lora_dir))
  205. lora_list = ["preset"] + lora_list
  206. return gr.Dropdown.update(choices=lora_list, value="preset")
  207. def upload_lora_file(uuid, lora_file):
  208. if not uuid:
  209. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  210. raise gr.Error("请登陆后使用! (Please login first)")
  211. else:
  212. uuid = 'qw'
  213. print("uuid: ", uuid)
  214. temp_lora_dir = join_worker_data_dir(uuid, 'temp_lora')
  215. if not os.path.exists(temp_lora_dir):
  216. os.makedirs(temp_lora_dir)
  217. shutil.copy(lora_file.name, temp_lora_dir)
  218. filename = os.path.basename(lora_file.name)
  219. newfilepath = os.path.join(temp_lora_dir, filename)
  220. print("newfilepath: ", newfilepath)
  221. lora_list = sorted(os.listdir(temp_lora_dir))
  222. lora_list = ["preset"] + lora_list
  223. return gr.Dropdown.update(choices=lora_list, value=filename)
  224. def clear_lora_file(uuid, lora_file):
  225. if not uuid:
  226. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  227. raise gr.Error("请登陆后使用! (Please login first)")
  228. else:
  229. uuid = 'qw'
  230. return gr.Dropdown.update(value="preset")
  231. def change_lora_choice(lora_choice):
  232. if lora_choice == 'preset':
  233. return gr.Gallery.update(value=[(item["img"], item["name"]) for item in styles], visible=True), \
  234. gr.Text.update(value=style_list[0])
  235. else:
  236. return gr.Gallery.update(visible=False), gr.Text.update(visible=False)
  237. def change_style_choice(uuid, style_choice):
  238. if not uuid:
  239. if os.getenv("MODELSCOPE_ENVIRONMENT") == 'studio':
  240. raise gr.Error("请登陆后使用! (Please login first)")
  241. else:
  242. uuid = 'qw'
  243. out_path = f'{project_dir}/workspace/{uuid}/style_lora'
  244. if os.path.exists(out_path):
  245. choices = os.listdir(out_path)
  246. else:
  247. choices = []
  248. if style_choice == 0:
  249. return gr.Gallery.update(visible=True), gr.Radio.update(choices=choices, visible=False)
  250. else:
  251. return gr.Gallery.update(visible=False), gr.Radio.update(choices=choices, visible=True)
  252. def select_trained_style(trained_styles):
  253. return gr.Text.update(value=trained_styles)
  254. def get_tag(imgs):
  255. results = []
  256. for i in range(len(imgs)):
  257. file, old_prompt = imgs[i]
  258. img_path = file['name']
  259. img = Image.open(img_path)
  260. result = tag_model.tag(img, threshold=0.7)
  261. results.append([img_path, result])
  262. imgs[i][1] = result
  263. return gr.Gallery.update(value=results, visible=True)
  264. def modify_tag(gallery, impath, tag):
  265. results = []
  266. for item in gallery:
  267. if item[0]['data'] == impath:
  268. results.append([item[0]['name'], tag])
  269. else:
  270. results.append([item[0]['name'], item[1]])
  271. return gr.Gallery.update(value=results)
  272. def inference_input():
  273. with gr.Blocks() as demo:
  274. uuid = gr.Text(label="modelscope_uuid", visible=False)
  275. with gr.Row():
  276. with gr.Column():
  277. with gr.Box():
  278. style_choice = gr.Radio(label="风格模型来源(Whether enhancing face similarity)", choices=["预设风格(Preset styles)", "用户训练风格(User-trained styles)"], type="index", value=None)
  279. style_model = gr.Text(label='请选择一种风格(Select a style from the pics below):', interactive=False)
  280. trained_styles = gr.Radio(label='用户训练风格列表(User-trained style list)', choices=[], value=None, type="value", visible=False)
  281. if find_spec('webui'):
  282. gallery = gr.Gallery(value=[(item["img"], item["name"]) for item in styles],
  283. label="风格(Style)",
  284. allow_preview=False,
  285. elem_id="gallery",
  286. show_share_button=False,
  287. visible=True).style(columns=6, rows=2)
  288. else:
  289. gallery = gr.Gallery(value=[(item["img"], item["name"]) for item in styles],
  290. label="风格(Style)",
  291. allow_preview=False,
  292. elem_id="gallery",
  293. show_share_button=False,
  294. visible=True).style(columns=6, object_fit='contain', height=600)
  295. with gr.Box():
  296. gr.Markdown('请上传一张用户人像图片(Please upload a user image):')
  297. user_images = gr.Gallery(label="输入用户图片(User image)", show_label=True)
  298. with gr.Row(elem_id="container_row"):
  299. upload_button = gr.UploadButton("选择图片上传(Upload photos)", file_types=["image"],
  300. file_count="multiple")
  301. clear_button = gr.Button("清空图片(Clear photos)")
  302. clear_button.click(fn=lambda: [], inputs=None, outputs=user_images)
  303. upload_button.upload(upload_file, inputs=[upload_button, user_images], outputs=user_images,
  304. queue=False)
  305. with gr.Accordion("高级选项(Advanced Options)", open=False):
  306. # upload one lora file and show the name or path of the file
  307. with gr.Accordion("上传LoRA文件(Upload LoRA file)", open=False):
  308. with gr.Row():
  309. lora_choice = gr.Dropdown(choices=["preset"], type="value", value="preset", label="LoRA文件(LoRA file)", visible=True)
  310. update_button = gr.Button('刷新风格LoRA列表并切换为预设风格(Refresh style LoRAs and switch to preset styles)')
  311. lora_file = gr.File(
  312. value=None,
  313. label="上传LoRA文件(Upload LoRA file)",
  314. type="file",
  315. file_types=[".safetensors"],
  316. file_count="single",
  317. visible=True,
  318. )
  319. pos_prompt = gr.Textbox(label="提示语(Prompt)", lines=3,
  320. value=generate_pos_prompt(None, styles[0]['add_prompt_style']),
  321. interactive=True)
  322. neg_prompt = gr.Textbox(label="负向提示语(Negative Prompt)", lines=3,
  323. value="",
  324. interactive=True)
  325. if neg_prompt.value == '' :
  326. neg_prompt.value = neg
  327. multiplier_style = gr.Slider(minimum=0, maximum=1, value=0.25,
  328. step=0.05, label='风格权重(Multiplier style)')
  329. with gr.Accordion("姿态控制(Pose control)", open=True):
  330. with gr.Row():
  331. pose_image = gr.Image(source='upload', type='filepath', label='姿态图片(Pose image)', height=250)
  332. pose_res_image = gr.Image(source='upload', interactive=False, label='姿态结果(Pose result)', visible=False, height=250)
  333. gr.Examples(pose_examples['man'], inputs=[pose_image], label='男性姿态示例')
  334. gr.Examples(pose_examples['woman'], inputs=[pose_image], label='女性姿态示例')
  335. with gr.Box():
  336. num_images = gr.Number(
  337. label='生成图片数量(Number of photos)', value=1, precision=1, minimum=1, maximum=6)
  338. use_face_swap = gr.Radio(label="是否使用人脸相似度增强(Whether enhancing face similarity)", choices=["否(No)", "是(Yes)"], type="index", value="是(Yes)")
  339. gr.Markdown('''
  340. 注意:
  341. - 最多支持生成6张图片!(You may generate a maximum of 6 photos at one time!)
  342. - 可上传在定义LoRA文件使用, 否则默认使用风格模型的LoRA。(You may upload custome LoRA file, otherwise the LoRA file of the style model will be used by deault.)
  343. - 使用自定义LoRA文件需手动输入prompt, 否则可能无法正常触发LoRA文件风格。(You shall provide prompt when using custom LoRA, otherwise desired LoRA style may not be triggered.)
  344. ''')
  345. with gr.Row(elem_id="container_row"):
  346. display_button = gr.Button('开始生成(Start!)', variant='primary')
  347. with gr.Box():
  348. infer_progress = gr.Textbox(label="生成进度(Progress)", value="当前无生成任务(No task)", interactive=False)
  349. with gr.Box():
  350. gr.Markdown('生成结果(Result)')
  351. output_images = gr.Gallery(label='Output', show_label=False).style(columns=3, rows=2, height=600,
  352. object_fit="contain")
  353. style_choice.change(fn=change_style_choice, inputs=[uuid, style_choice], outputs=[gallery, trained_styles], queue=False)
  354. gallery.select(select_function, None, style_model, queue=False)
  355. trained_styles.change(select_trained_style, inputs=[trained_styles], outputs=[style_model], queue=False)
  356. lora_choice.change(fn=change_lora_choice, inputs=[lora_choice], outputs=[gallery, style_model], queue=False)
  357. lora_file.upload(fn=upload_lora_file, inputs=[uuid, lora_file], outputs=[lora_choice], queue=False)
  358. lora_file.clear(fn=clear_lora_file, inputs=[uuid, lora_file], outputs=[lora_choice], queue=False)
  359. style_model.change(update_prompt, [style_model, style_choice, uuid], [pos_prompt, multiplier_style], queue=False)
  360. display_button.click(fn=launch_pipeline,
  361. inputs=[uuid, style_choice, pos_prompt, neg_prompt, user_images, num_images, style_model, lora_choice, multiplier_style,
  362. pose_image, use_face_swap],
  363. outputs=[infer_progress, output_images])
  364. update_button.click(fn=update_lora_choice, inputs=[uuid], outputs=[lora_choice], queue=False)
  365. return demo
  366. def inference_inpaint():
  367. preset_template = glob(os.path.join(f'{project_dir}/inpaint_template/*.jpg'))
  368. with gr.Blocks() as demo:
  369. uuid = gr.Text(label="modelscope_uuid", visible=False)
  370. # Initialize the GUI
  371. with gr.Row():
  372. with gr.Column():
  373. with gr.Box():
  374. gr.Markdown('请选择或上传模板图片(Please select or upload a template image):')
  375. template_image_list = [[i] for idx, i in enumerate(preset_template)]
  376. print(template_image_list)
  377. template_image = gr.Image(source='upload', type='filepath', label='模板图片(Template image)')
  378. gr.Examples(template_image_list, inputs=[template_image], label='模板示例(Template examples)')
  379. with gr.Box():
  380. gr.Markdown('请上传用户人像图片(Please upload a user image):')
  381. user_images = gr.Gallery(label="输入用户图片(User image)", show_label=True)
  382. with gr.Row(elem_id="container_row"):
  383. upload_button = gr.UploadButton("选择图片上传(Upload photos)", file_types=["image"],
  384. file_count="multiple")
  385. clear_button = gr.Button("清空图片(Clear photos)")
  386. clear_button.click(fn=lambda: [], inputs=None, outputs=user_images)
  387. upload_button.upload(upload_file, inputs=[upload_button, user_images], outputs=user_images,
  388. queue=False)
  389. num_faces = gr.Number(minimum=1, value=1, precision=1, label='照片中的人脸数目(Number of Faces)')
  390. selected_face = gr.Number(minimum=1, value=1, precision=1, label='选择重绘的人脸编号,按从左至右的顺序(Index of Face for inpainting, counting from left to right)')
  391. use_face_swap = gr.Radio(label="是否使用人脸相似度增强(Whether enhancing face similarity)", choices=["否(No)", "是(Yes)"], type="index", value="是(Yes)")
  392. with gr.Row(elem_id="container_row"):
  393. display_button = gr.Button('开始生成(Start Generation)', variant='primary')
  394. with gr.Box():
  395. infer_progress = gr.Textbox(
  396. label="生成(Generation Progress)",
  397. value="No task currently",
  398. interactive=False
  399. )
  400. with gr.Box():
  401. gr.Markdown('生成结果(Generated Results)')
  402. output_images = gr.Gallery(
  403. label='输出(Output)',
  404. show_label=False
  405. ).style(columns=3, rows=2, height=600, object_fit="contain")
  406. display_button.click(
  407. fn=launch_pipeline_inpaint,
  408. inputs=[uuid, user_images, num_faces, selected_face, template_image, use_face_swap],
  409. outputs=[infer_progress, output_images]
  410. )
  411. return demo
  412. def train_input():
  413. with gr.Blocks() as demo:
  414. uuid = gr.Text(label="modelscope_uuid", visible=False)
  415. output_model_name = gr.Text(label='风格lora模型名称(Style lora name)', visible=True)
  416. gallery = gr.Gallery(type='image', label='图片列表(Photos)', height=250, columns=8, visible=True)
  417. with gr.Row(elem_id="container_row"):
  418. upload_button = gr.UploadButton("选择图片上传(Upload photos)", file_types=["image"], file_count="multiple")
  419. train_folder = gr.Text(label='训练文件夹(Train folder)', visible=False)
  420. with gr.Row(elem_id="container_row"):
  421. tag_btn = gr.Button(value='开始打标签(Tag prompt)')
  422. rank = gr.Number(label='rank', direction='row', value=32, step=1)
  423. num_train_epochs = gr.Number(label='num_train_epochs', direction='row', value=200, step=1)
  424. with gr.Accordion("手动修改标签(Manually modify tags)", open=False):
  425. with gr.Row(elem_id="container_row"):
  426. current_pth = gr.Text(label='当前图片(Current image)', value=None, visible=False)
  427. current_tag = gr.Text(label='当前标签(Current tags)', value=None, visible=True)
  428. mod_btn = gr.Button(value='提交修改(Submit modifications)')
  429. prompt_input = gr.Text(label='风格触发词(Trigger word)', visible=True)
  430. with gr.Row(elem_id="container_row"):
  431. btn = gr.Button(value='开始训练(Start train)', interactive=False)
  432. output_lora = gr.Files(label='输出模型(Output model)', type='file', visible=True)
  433. output_prompt = gr.Text(label='风格提示词(Style prompt)', visible=False)
  434. # 完成待训练图片上传
  435. upload_button.upload(fn=set_img, inputs=[upload_button, uuid, output_model_name], outputs=[train_folder, gallery, btn])
  436. # 完成公用提示词输入
  437. prompt_input.input(fn=set_prompt, outputs=[btn])
  438. # 开始给图片打标签(prompt)
  439. tag_btn.click(fn=get_tag, inputs=[gallery], outputs=[gallery])
  440. # 获取图片标签
  441. gallery.select(select_function_multi, None, [current_pth, current_tag], queue=False)
  442. # 手动修改标签
  443. mod_btn.click(fn=modify_tag, inputs=[gallery, current_pth, current_tag], outputs=[gallery], queue=False)
  444. # 开始训练
  445. btn.click(fn=train_lora, inputs=[uuid, output_model_name, prompt_input, train_folder, gallery, rank, num_train_epochs], outputs=[output_lora, output_prompt])
  446. return demo
  447. styles = []
  448. style_list = []
  449. base_models_reverse = [base_models[1], base_models[0]]
  450. for base_model in base_models_reverse:
  451. folder_path = f"{os.path.dirname(os.path.abspath(__file__))}/styles/{base_model['name']}"
  452. files = os.listdir(folder_path)
  453. files.sort()
  454. for file in files:
  455. file_path = os.path.join(folder_path, file)
  456. with open(file_path, "r", encoding='utf-8') as f:
  457. data = json.load(f)
  458. if data['img'][:2] == './':
  459. data['img'] = f"{project_dir}/{data['img'][2:]}"
  460. if base_model['name'] == 'leosamsMoonfilm_filmGrain20':
  461. data['base_model_index'] = 0
  462. else:
  463. data['base_model_index'] = 1
  464. style_list.append(data['name'])
  465. styles.append(data)
  466. for style in styles:
  467. print(style['name'])
  468. if style['model_id'] is not None:
  469. model_dir = snapshot_download(style['model_id'], revision=style['revision'])
  470. gen_portrait = GenPortrait()
  471. gen_portrait_inpaint = GenPortrait_inpaint()
  472. tag_model = init_tag()
  473. with open(
  474. os.path.join(os.path.dirname(__file__), 'main.css'), "r",
  475. encoding="utf-8") as f:
  476. MAIN_CSS_CODE = f.read()
  477. with gr.Blocks(css=MAIN_CSS_CODE, theme=gr.themes.Soft()) as demo:
  478. if find_spec('webui'):
  479. # if running as a webui extension, don't display banner self-advertisement
  480. gr.Markdown("# <center> \N{fire} FaceChain-FACT Portrait Generation (\N{whale} [Github star it here](https://github.com/modelscope/facechain/tree/main) \N{whale})</center>")
  481. else:
  482. gr.Markdown("# <center> \N{fire} FaceChain-FACT Portrait Generation ([Github star it here](https://github.com/modelscope/facechain/tree/main) \N{whale}, [API](https://help.aliyun.com/zh/dashscope/developer-reference/facechain-quick-start) \N{whale})</center>")
  483. gr.Markdown("##### <center> 本项目仅供学习交流,请勿将模型及其制作内容用于非法活动或违反他人隐私的场景。(This project is intended solely for the purpose of technological discussion, and should not be used for illegal activities and violating privacy of individuals.)</center>")
  484. with gr.Tabs():
  485. with gr.TabItem('\N{party popper}免训练无限风格形象写真(Infinite Style Portrait)'):
  486. inference_input()
  487. with gr.TabItem('\N{party popper}免训练固定模板形象写真(Fixed Templates Portrait)'):
  488. inference_inpaint()
  489. with gr.TabItem('\N{party popper}自定义风格模型训练(Style Model Training)'):
  490. train_input()
  491. if __name__ == "__main__":
  492. demo.queue(status_update_rate=1).launch(share=False)