NeuroDonu commited on
Commit
a23feab
·
verified ·
1 Parent(s): f9176de

update - patch core/content analyzer

Browse files
Files changed (1) hide show
  1. updater.py +210 -142
updater.py CHANGED
@@ -1,143 +1,211 @@
1
- import os
2
- import subprocess
3
- import locale
4
- import winreg
5
- import argparse
6
- import inspect
7
- import ast
8
-
9
- abs_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10
- git = os.path.join(abs_path, "s", "git", "cmd", "git.exe")
11
- master_path = os.path.join(abs_path, "p")
12
- python = os.path.join(abs_path, "s", "python", "python.exe")
13
- parser = argparse.ArgumentParser()
14
-
15
- parser.add_argument('-wf', '--webcam-false', action='store_true')
16
- parser.add_argument('-wt', '--webcam-true', action='store_true')
17
- parser.add_argument('-mb', '--master-branch', action='store_true')
18
- parser.add_argument('-nb', '--next-branch', action='store_true')
19
- parser.add_argument('-nu', '--no-update', action='store_true')
20
-
21
- args = parser.parse_args()
22
-
23
- def run_git_command(args):
24
- subprocess.run([git] + args, check=True)
25
-
26
- def uncensore(branch):
27
- functions_to_modify = {
28
- "analyse_frame": False,
29
- "analyse_stream": False,
30
- "forward": 0.0,
31
- "prepare_frame": "frame",
32
- "analyse_video": False,
33
- "analyse_image": False
34
- }
35
- file_path = os.path.join(master_path, branch, 'facefusion', 'content_analyser.py')
36
-
37
- if not os.path.exists(file_path):
38
- print(f"Файл {file_path} не найден.")
39
- return
40
-
41
- with open(file_path, 'r', encoding='utf-8') as file:
42
- source_code = file.read()
43
-
44
- tree = ast.parse(source_code)
45
-
46
- class ModifyFunctions(ast.NodeTransformer):
47
- def visit_FunctionDef(self, node):
48
- if node.name in functions_to_modify:
49
- return_value = functions_to_modify[node.name]
50
- if isinstance(return_value, bool):
51
- node.body = [ast.Return(value=ast.Constant(value=return_value))]
52
- elif isinstance(return_value, float):
53
- node.body = [ast.Return(value=ast.Constant(value=return_value))]
54
- elif isinstance(return_value, str) and return_value == "frame":
55
- node.body = [ast.Return(value=ast.Name(id='vision_frame', ctx=ast.Load()))]
56
-
57
- return node
58
-
59
- modified_tree = ModifyFunctions().visit(tree)
60
- modified_code = ast.unparse(modified_tree)
61
-
62
- with open(file_path, 'w', encoding='utf-8') as file:
63
- file.write(modified_code)
64
-
65
- def prepare_environment(branch):
66
- branch_path = os.path.join(master_path, branch)
67
- os.chdir(branch_path)
68
- if not args.no_update:
69
- run_git_command(['reset', '--hard'])
70
- run_git_command(['checkout', branch])
71
- run_git_command(['pull', 'origin', branch, '--rebase'])
72
- uncensore(branch)
73
-
74
- def ask_webcam_mode(language):
75
- webcam_choice = input(get_localized_text(language, "enable_webcam")).strip().lower()
76
- if webcam_choice in ["y", "д"]:
77
- return True
78
- elif webcam_choice in ["n", "н"]:
79
- return False
80
- return None
81
-
82
- def start_ff(branch, webcam_mode=False):
83
- path_to_branch = os.path.join(master_path, branch)
84
- second_file = os.path.join(path_to_branch, "facefusion.py")
85
- args = ["run", "--open-browser", "--ui-layouts", "webcam"] if webcam_mode else ["run", "--open-browser"]
86
- cmd = f'"{python}" "{second_file}" {" ".join(args)}'
87
- subprocess.run(cmd, shell=True, check=True)
88
-
89
- def get_localized_text(language, key):
90
- texts = {
91
- "en": {
92
- "choose_action": "Choose an action:",
93
- "update_master": "1. Update to the master branch and start it",
94
- "update_next": "2. Update to the next branch and start it",
95
- "enter_choice": "Enter the number of the action: ",
96
- "invalid_choice": "Invalid choice, please try again.",
97
- "enable_webcam": "Enable webcam mode? (Y/N): ",
98
- },
99
- "ru": {
100
- "choose_action": "Выберите действие:",
101
- "update_master": "1. Обновить до обычной ветки и запустить ее (master)",
102
- "update_next": "2. Обновить до бета ветки и запустить ее (next)",
103
- "enter_choice": "Введите номер действия: ",
104
- "invalid_choice": "Неверный выбор, попробуйте снова.",
105
- "enable_webcam": "Включить режим вебкамеры? (Y/N): ",
106
- }
107
- }
108
- return texts[language].get(key, "")
109
-
110
- def get_system_language():
111
- try:
112
- key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Control Panel\International")
113
- language = winreg.QueryValueEx(key, "LocaleName")[0]
114
- winreg.CloseKey(key)
115
- return "ru" if language.split('-')[0].lower() == "ru" else "en"
116
- except WindowsError:
117
- return "ru" if locale.getlocale()[0].split('_')[0].lower() == "ru" else "en"
118
-
119
- def facefusion():
120
- language = get_system_language()
121
- if args.master_branch or args.next_branch:
122
- branch = "master" if args.master_branch else "next"
123
- prepare_environment(branch)
124
- webcam_mode = True if args.webcam_true else False if args.webcam_false else ask_webcam_mode(language)
125
- start_ff(branch, webcam_mode)
126
- return
127
-
128
- while True:
129
- print(get_localized_text(language, "choose_action"))
130
- print(get_localized_text(language, "update_master"))
131
- print(get_localized_text(language, "update_next"))
132
- choice = input(get_localized_text(language, "enter_choice")).strip()
133
- if choice in ['1', '2']:
134
- branch = "master" if choice == '1' else "next"
135
- prepare_environment(branch)
136
- webcam_mode = ask_webcam_mode(language)
137
- start_ff(branch, webcam_mode)
138
- break
139
- else:
140
- print(get_localized_text(language, "invalid_choice"))
141
-
142
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  facefusion()
 
1
+ import os
2
+ import subprocess
3
+ import locale
4
+ import winreg
5
+ import argparse
6
+ import inspect
7
+ import ast
8
+
9
+ abs_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10
+ git = os.path.join(abs_path, "s", "git", "cmd", "git.exe")
11
+ master_path = os.path.join(abs_path, "p")
12
+ python = os.path.join(abs_path, "s", "python", "python.exe")
13
+ parser = argparse.ArgumentParser()
14
+
15
+ parser.add_argument('-wf', '--webcam-false', action='store_true')
16
+ parser.add_argument('-wt', '--webcam-true', action='store_true')
17
+ parser.add_argument('-mb', '--master-branch', action='store_true')
18
+ parser.add_argument('-nb', '--next-branch', action='store_true')
19
+ parser.add_argument('-nu', '--no-update', action='store_true')
20
+
21
+ args = parser.parse_args()
22
+
23
+ def run_git_command(args):
24
+ subprocess.run([git] + args, check=True)
25
+
26
+ def uncensore(branch):
27
+ file_path = os.path.join(master_path, branch, 'facefusion', 'content_analyser.py')
28
+
29
+ if not os.path.exists(file_path):
30
+ print(f"Файл {file_path} не найден.")
31
+ return
32
+
33
+ print(f"Радикально снимаем цензуру с {file_path}...")
34
+
35
+ with open(file_path, 'r', encoding='utf-8') as file:
36
+ source_code = file.read()
37
+
38
+ tree = ast.parse(source_code)
39
+
40
+ class ModifyFunctions(ast.NodeTransformer):
41
+ def visit_FunctionDef(self, node):
42
+ if node.name in ['analyse_frame', 'analyse_stream', 'analyse_video', 'analyse_image',
43
+ 'detect_nsfw', 'detect_with_nsfw_1', 'detect_with_nsfw_2', 'detect_with_nsfw_3']:
44
+ node.body = [ast.Return(value=ast.Constant(value=False))]
45
+
46
+ elif node.name == 'pre_check':
47
+ node.body = [ast.Return(value=ast.Constant(value=True))]
48
+
49
+ elif node.name == 'get_inference_pool':
50
+ node.body = [ast.Return(value=ast.Dict(keys=[], values=[]))]
51
+
52
+ elif node.name == 'collect_model_downloads':
53
+ node.body = [ast.Return(value=ast.Tuple(elts=[ast.Dict(keys=[], values=[]), ast.Dict(keys=[], values=[])], ctx=ast.Load()))]
54
+
55
+ elif node.name == 'create_static_model_set':
56
+ node.body = [ast.Return(value=ast.Dict(keys=[], values=[]))]
57
+
58
+ elif node.name == 'resolve_execution_providers':
59
+ node.body = [ast.Return(value=ast.List(elts=[], ctx=ast.Load()))]
60
+
61
+ elif node.name == 'forward_nsfw':
62
+ node.body = [ast.Return(value=ast.List(elts=[], ctx=ast.Load()))]
63
+
64
+ elif node.name == 'prepare_detect_frame':
65
+ node.body = [ast.Return(value=ast.Name(id='temp_vision_frame', ctx=ast.Load()))]
66
+
67
+ elif node.name == 'clear_inference_pool':
68
+ node.body = [ast.Pass()]
69
+
70
+ else:
71
+ if hasattr(node, 'returns') and node.returns:
72
+ if isinstance(node.returns, ast.Name) and node.returns.id == 'bool':
73
+ node.body = [ast.Return(value=ast.Constant(value=False))]
74
+ elif isinstance(node.returns, ast.Constant) and node.returns.value == bool:
75
+ node.body = [ast.Return(value=ast.Constant(value=False))]
76
+ else:
77
+ node.body = [ast.Return(value=ast.Constant(value=None))]
78
+ else:
79
+ node.body = [ast.Return(value=ast.Constant(value=None))]
80
+
81
+ return node
82
+
83
+ modified_tree = ModifyFunctions().visit(tree)
84
+ modified_code = ast.unparse(modified_tree)
85
+
86
+ with open(file_path, 'w', encoding='utf-8') as file:
87
+ file.write(modified_code)
88
+
89
+ print("Цензура радикально снята! Все модели отключены, никаких загрузок не будет!")
90
+
91
+ def patch_core(branch):
92
+ core_path = os.path.join(master_path, branch, 'facefusion', 'core.py')
93
+
94
+ if not os.path.exists(core_path):
95
+ print(f"Файл {core_path} не найден.")
96
+ return
97
+
98
+ print(f"Патчим проверку хеша в {core_path}...")
99
+
100
+ with open(core_path, 'r', encoding='utf-8') as file:
101
+ content = file.read()
102
+
103
+ content = content.replace(
104
+ "content_analyser_content = inspect.getsource(content_analyser).encode()\n\tis_valid = hash_helper.create_hash(content_analyser_content) == 'b159fd9d'",
105
+ "content_analyser_content = inspect.getsource(content_analyser).encode()\n\tis_valid = True"
106
+ )
107
+
108
+ with open(core_path, 'w', encoding='utf-8') as file:
109
+ file.write(content)
110
+
111
+ print("Проверка хеша успешно обойдена!")
112
+
113
+ def prepare_environment(branch):
114
+ branch_path = os.path.join(master_path, branch)
115
+ os.chdir(branch_path)
116
+ if not args.no_update:
117
+ run_git_command(['reset', '--hard'])
118
+ run_git_command(['checkout', branch])
119
+ run_git_command(['pull', 'origin', branch, '--rebase'])
120
+ uncensore(branch)
121
+ patch_core(branch)
122
+
123
+ def ask_webcam_mode(language):
124
+ """Спрашивает у пользователя режим вебкамеры и возвращает определенный результат"""
125
+ webcam_choice = input(get_localized_text(language, "enable_webcam")).strip().lower()
126
+ if webcam_choice in ["y", "д"]:
127
+ return True
128
+ elif webcam_choice in ["n", "н"]:
129
+ return False
130
+ else:
131
+ print("Неверный ввод, вебкамера отключена по умолчанию.")
132
+ return False
133
+
134
+ def start_ff(branch, webcam_mode=False):
135
+ path_to_branch = os.path.join(master_path, branch)
136
+ second_file = os.path.join(path_to_branch, "facefusion.py")
137
+ args = ["run", "--open-browser", "--ui-layouts", "webcam"] if webcam_mode else ["run", "--open-browser"]
138
+ cmd = f'"{python}" "{second_file}" {" ".join(args)}'
139
+ subprocess.run(cmd, shell=True, check=True)
140
+
141
+ def get_localized_text(language, key):
142
+ texts = {
143
+ "en": {
144
+ "choose_action": "Choose an action:",
145
+ "update_master": "1. Update to the master branch and start it",
146
+ "update_next": "2. Update to the next branch and start it",
147
+ "enter_choice": "Enter the number of the action: ",
148
+ "invalid_choice": "Invalid choice, please try again.",
149
+ "enable_webcam": "Enable webcam mode? (Y/N): ",
150
+ },
151
+ "ru": {
152
+ "choose_action": "Выберите действие:",
153
+ "update_master": "1. Обновить до обычной ветки и запустить ее (master)",
154
+ "update_next": "2. Обновить до бета ветки и запустить ее (next)",
155
+ "enter_choice": "Введите номер действия: ",
156
+ "invalid_choice": "Неверный выбор, попробуйте снова.",
157
+ "enable_webcam": "Включить режим вебкамеры? (Y/N): ",
158
+ }
159
+ }
160
+ return texts[language].get(key, "")
161
+
162
+ def get_system_language():
163
+ """Определяет системный язык с корректной обработкой None значений"""
164
+ try:
165
+ key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Control Panel\International")
166
+ language = winreg.QueryValueEx(key, "LocaleName")[0]
167
+ winreg.CloseKey(key)
168
+ if language:
169
+ return "ru" if language.split('-')[0].lower() == "ru" else "en"
170
+ except (WindowsError, AttributeError):
171
+ pass
172
+
173
+ try:
174
+ locale_info = locale.getlocale()[0]
175
+ if locale_info:
176
+ return "ru" if locale_info.split('_')[0].lower() == "ru" else "en"
177
+ except (AttributeError, IndexError):
178
+ pass
179
+
180
+ return "ru"
181
+
182
+ def facefusion():
183
+ language = get_system_language()
184
+ if args.master_branch or args.next_branch:
185
+ branch = "master" if args.master_branch else "next"
186
+ prepare_environment(branch)
187
+ if args.webcam_true:
188
+ webcam_mode = True
189
+ elif args.webcam_false:
190
+ webcam_mode = False
191
+ else:
192
+ webcam_mode = ask_webcam_mode(language)
193
+ start_ff(branch, webcam_mode)
194
+ return
195
+
196
+ while True:
197
+ print(get_localized_text(language, "choose_action"))
198
+ print(get_localized_text(language, "update_master"))
199
+ print(get_localized_text(language, "update_next"))
200
+ choice = input(get_localized_text(language, "enter_choice")).strip()
201
+ if choice in ['1', '2']:
202
+ branch = "master" if choice == '1' else "next"
203
+ prepare_environment(branch)
204
+ webcam_mode = ask_webcam_mode(language)
205
+ start_ff(branch, webcam_mode)
206
+ break
207
+ else:
208
+ print(get_localized_text(language, "invalid_choice"))
209
+
210
+ if __name__ == "__main__":
211
  facefusion()