Cnass commited on
Commit
b3827db
·
verified ·
1 Parent(s): 3feac44

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -66
app.py CHANGED
@@ -11,7 +11,6 @@ from flask import Flask, request, jsonify
11
  from decompiler import magic, renpycompat
12
 
13
  sys.setrecursionlimit(50000)
14
-
15
  app = Flask(__name__)
16
 
17
  # --- 1. YARDIMCI VE ZIRHLI ÇEVİRİ FONKSİYONLARI ---
@@ -23,44 +22,20 @@ def unescape_wp_string(s):
23
  s = s.replace('\\\\', '\\')
24
  return s.replace('\r', '')
25
 
26
- def prepare_translations(raw_translations):
27
- """Çevirileri AST motorunun anlayacağı saf ve hızlı formata (O(1) Dictionary) dönüştürür."""
28
- processed = {}
29
- for k, v in raw_translations.items():
30
- clean_k = unescape_wp_string(k)
31
- clean_v = unescape_wp_string(v)
32
-
33
- # Varsa başındaki ve sonundaki tırnakları temizle
34
- if len(clean_k) >= 2 and clean_k[0] in ('"', "'") and clean_k[-1] == clean_k[0]:
35
- clean_k = clean_k[1:-1]
36
- if len(clean_v) >= 2 and clean_v[0] in ('"', "'") and clean_v[-1] == clean_v[0]:
37
- clean_v = clean_v[1:-1]
38
-
39
- if clean_k.strip() and clean_k != clean_v:
40
- # Eşleşme oranını %100'e çıkarmak için normalize edilmiş hali anahtar olur
41
- norm_k = clean_k.strip().replace('\r', '')
42
- processed[norm_k] = clean_v
43
- return processed
44
-
45
- def apply_translation(text, processed_translations):
46
- """Hızlı ve hata payı %0 olan çeviri uygulayıcı."""
47
  if not isinstance(text, (str, bytes)): return text
48
  is_bytes = isinstance(text, bytes)
49
  text_str = text.decode('utf-8', 'ignore') if is_bytes else text
50
 
51
- # Metni normalize et (boşlukları ve görünmez \r'leri sil)
52
- text_clean = text_str.strip().replace('\r', '')
53
-
54
- if text_clean in processed_translations:
55
- clean_v = processed_translations[text_clean]
56
-
57
- # Orijinal metnin başındaki ve sonundaki özel boşlukları (padding) bozmadan geri ekle!
58
- leading_space = text_str[:len(text_str) - len(text_str.lstrip())]
59
- trailing_space = text_str[len(text_str.rstrip()):]
60
-
61
- final_v = leading_space + clean_v + trailing_space
62
- return final_v.encode('utf-8') if is_bytes else final_v
63
 
 
 
 
 
64
  return text
65
 
66
  # --- 2. AST MOTORU (Düz Metni Bozmadan Sadece Hedefi Vurur) ---
@@ -99,18 +74,15 @@ def patch_ast(obj, translations, visited=None):
99
  label = apply_translation(item[0], translations)
100
  new_items.append((label, item[1], item[2]) if len(item) >= 3 else (label,) + item[1:])
101
  obj.items = new_items
102
- elif class_name == 'TranslateString' and hasattr(obj, 'old') and hasattr(obj, 'new'):
103
- # EN BÜYÜK HATA BURADAYDI: Çeviri, 'old' (İngilizce) ile aranıp 'new' (Türkçe) içine yazılmalıdır.
104
- translated = apply_translation(obj.old, translations)
105
- if translated != obj.old:
106
- obj.new = translated
107
 
108
  FORBIDDEN_KEYS = {'old', 'language', 'identifier', 'filename', 'name', 'label', 'parameters'}
109
  for k, v in list(obj.__dict__.items()):
110
  if k in FORBIDDEN_KEYS: continue
111
  if class_name in ('Say', 'TranslateSay') and k == 'what': continue
112
  if class_name in ('Menu', 'TranslateMenu') and k == 'items': continue
113
- if class_name == 'TranslateString' and k in ('new', 'old'): continue
114
 
115
  if isinstance(v, (str, bytes)):
116
  text_len = len(v) if isinstance(v, str) else len(v.decode('utf-8', 'ignore'))
@@ -120,23 +92,11 @@ def patch_ast(obj, translations, visited=None):
120
  patch_ast(v, translations, visited)
121
 
122
  # --- 3. ENDPOINT'LER ---
123
-
124
- @app.route('/', methods=['GET'])
125
- def home():
126
- return jsonify({
127
- "status": "Renpy Decompiler & Patcher API Sorunsuz Calisiyor!",
128
- "endpoints": {
129
- "decompile": "/decompile [POST]",
130
- "patch": "/patch [POST]"
131
- }
132
- })
133
-
134
  @app.route('/decompile', methods=['POST'])
135
  def decompile_rpyc():
136
  data = request.json
137
  if not data or 'filedata' not in data:
138
  return jsonify({"error": "Dosya verisi bulunamadı."}), 400
139
-
140
  try:
141
  file_data = base64.b64decode(data['filedata'])
142
  filename = data.get('filename', 'temp.rpyc')
@@ -154,7 +114,6 @@ def decompile_rpyc():
154
  if os.path.exists(rpy_filename): os.remove(rpy_filename)
155
 
156
  return jsonify({"success": True, "rpy_content": rpy_content})
157
-
158
  except Exception as e:
159
  return jsonify({"error": str(e)}), 500
160
 
@@ -163,13 +122,16 @@ def patch_endpoint():
163
  data = request.get_json()
164
  if not data or 'filedata' not in data or 'translations' not in data:
165
  return jsonify({"error": "Eksik veri gönderildi."}), 400
166
-
167
  try:
168
  file_bytes = base64.b64decode(data['filedata'])
169
  raw_translations = data['translations']
170
-
171
- # Çevirileri O(1) hızına ve %100 eşleşmeye hazırla
172
- processed_translations = prepare_translations(raw_translations)
 
 
 
 
173
 
174
  if file_bytes.startswith(b"RENPY RPC2"):
175
  position = 10
@@ -189,15 +151,20 @@ def patch_endpoint():
189
  if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
190
  orig_proto = raw_pickle[1]
191
  ast_tree = renpycompat.pickle_loads(raw_pickle)
192
- patch_ast(ast_tree, processed_translations)
193
  payloads[1] = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
194
  elif c["slot"] == 2:
195
  try:
196
- # Slot 2 (Kaynak Kod) yamalaması artık daha güvenli. Tırnaklarla değiştirilip kodları bozması engellendi.
197
  raw_source = zlib.decompress(chunk_data).decode('utf-8')
198
- for k, v in processed_translations.items():
199
- raw_source = raw_source.replace(f'"{k}"', f'"{v}"')
200
- raw_source = raw_source.replace(f"'{k}'", f"'{v}'")
 
 
 
 
 
 
201
  payloads[2] = zlib.compress(raw_source.encode('utf-8'))
202
  except Exception:
203
  payloads[2] = chunk_data
@@ -207,9 +174,9 @@ def patch_endpoint():
207
  new_dir = bytearray()
208
  current_offset = 10 + (len(chunks) + 1) * 12
209
  for c in chunks:
210
- chunk_payload = payloads[c["slot"]]
211
- new_dir.extend(struct.pack("III", c["slot"], current_offset, len(chunk_payload)))
212
- current_offset += len(chunk_payload)
213
  new_dir.extend(struct.pack("III", 0, 0, 0))
214
 
215
  new_file = bytearray(b"RENPY RPC2")
@@ -224,7 +191,7 @@ def patch_endpoint():
224
  if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
225
  orig_proto = raw_pickle[1]
226
  ast_tree = renpycompat.pickle_loads(raw_pickle)
227
- patch_ast(ast_tree, processed_translations)
228
  new_rpyc_bytes = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
229
 
230
  return jsonify({
 
11
  from decompiler import magic, renpycompat
12
 
13
  sys.setrecursionlimit(50000)
 
14
  app = Flask(__name__)
15
 
16
  # --- 1. YARDIMCI VE ZIRHLI ÇEVİRİ FONKSİYONLARI ---
 
22
  s = s.replace('\\\\', '\\')
23
  return s.replace('\r', '')
24
 
25
+ def apply_translation(text, translations):
26
+ """AST Zırhı: Sadece birebir eşleşen metinleri değiştirir."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if not isinstance(text, (str, bytes)): return text
28
  is_bytes = isinstance(text, bytes)
29
  text_str = text.decode('utf-8', 'ignore') if is_bytes else text
30
 
31
+ for k, v in translations.items():
32
+ clean_k = k[1:-1] if len(k) >= 2 and k[0] in ('"', "'") and k[-1] == k[0] else k
33
+ clean_v = v[1:-1] if len(v) >= 2 and v[0] in ('"', "'") and v[-1] == v[0] else v
 
 
 
 
 
 
 
 
 
34
 
35
+ # Eşleşme oranını artırmak için görünmez \r karakterlerini yoksay
36
+ if text_str.replace('\r', '') == clean_k.replace('\r', ''):
37
+ return clean_v.encode('utf-8') if is_bytes else clean_v
38
+
39
  return text
40
 
41
  # --- 2. AST MOTORU (Düz Metni Bozmadan Sadece Hedefi Vurur) ---
 
74
  label = apply_translation(item[0], translations)
75
  new_items.append((label, item[1], item[2]) if len(item) >= 3 else (label,) + item[1:])
76
  obj.items = new_items
77
+ elif class_name == 'TranslateString' and hasattr(obj, 'new'):
78
+ obj.new = apply_translation(obj.new, translations)
 
 
 
79
 
80
  FORBIDDEN_KEYS = {'old', 'language', 'identifier', 'filename', 'name', 'label', 'parameters'}
81
  for k, v in list(obj.__dict__.items()):
82
  if k in FORBIDDEN_KEYS: continue
83
  if class_name in ('Say', 'TranslateSay') and k == 'what': continue
84
  if class_name in ('Menu', 'TranslateMenu') and k == 'items': continue
85
+ if class_name == 'TranslateString' and k == 'new': continue
86
 
87
  if isinstance(v, (str, bytes)):
88
  text_len = len(v) if isinstance(v, str) else len(v.decode('utf-8', 'ignore'))
 
92
  patch_ast(v, translations, visited)
93
 
94
  # --- 3. ENDPOINT'LER ---
 
 
 
 
 
 
 
 
 
 
 
95
  @app.route('/decompile', methods=['POST'])
96
  def decompile_rpyc():
97
  data = request.json
98
  if not data or 'filedata' not in data:
99
  return jsonify({"error": "Dosya verisi bulunamadı."}), 400
 
100
  try:
101
  file_data = base64.b64decode(data['filedata'])
102
  filename = data.get('filename', 'temp.rpyc')
 
114
  if os.path.exists(rpy_filename): os.remove(rpy_filename)
115
 
116
  return jsonify({"success": True, "rpy_content": rpy_content})
 
117
  except Exception as e:
118
  return jsonify({"error": str(e)}), 500
119
 
 
122
  data = request.get_json()
123
  if not data or 'filedata' not in data or 'translations' not in data:
124
  return jsonify({"error": "Eksik veri gönderildi."}), 400
 
125
  try:
126
  file_bytes = base64.b64decode(data['filedata'])
127
  raw_translations = data['translations']
128
+
129
+ clean_translations = {}
130
+ for k, v in raw_translations.items():
131
+ clean_k = unescape_wp_string(k)
132
+ clean_v = unescape_wp_string(v)
133
+ if clean_k.strip() and clean_k != clean_v:
134
+ clean_translations[clean_k] = clean_v
135
 
136
  if file_bytes.startswith(b"RENPY RPC2"):
137
  position = 10
 
151
  if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
152
  orig_proto = raw_pickle[1]
153
  ast_tree = renpycompat.pickle_loads(raw_pickle)
154
+ patch_ast(ast_tree, clean_translations)
155
  payloads[1] = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
156
  elif c["slot"] == 2:
157
  try:
 
158
  raw_source = zlib.decompress(chunk_data).decode('utf-8')
159
+ for k, v in clean_translations.items():
160
+ # KRİTİK DÜZELTME: Gelen metinde tırnak olup olmadığına bakmaksızın,
161
+ # saf metne tırnak ekleyerek kaynak kod içerisindeki eşleşmeyi garantiye alıyoruz.
162
+ ck = k[1:-1] if len(k) >= 2 and k[0] in ('"', "'") and k[-1] == k[0] else k
163
+ cv = v[1:-1] if len(v) >= 2 and v[0] in ('"', "'") and v[-1] == v[0] else v
164
+
165
+ raw_source = raw_source.replace(f'"{ck}"', f'"{cv}"')
166
+ raw_source = raw_source.replace(f"'{ck}'", f"'{cv}'")
167
+
168
  payloads[2] = zlib.compress(raw_source.encode('utf-8'))
169
  except Exception:
170
  payloads[2] = chunk_data
 
174
  new_dir = bytearray()
175
  current_offset = 10 + (len(chunks) + 1) * 12
176
  for c in chunks:
177
+ data = payloads[c["slot"]]
178
+ new_dir.extend(struct.pack("III", c["slot"], current_offset, len(data)))
179
+ current_offset += len(data)
180
  new_dir.extend(struct.pack("III", 0, 0, 0))
181
 
182
  new_file = bytearray(b"RENPY RPC2")
 
191
  if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
192
  orig_proto = raw_pickle[1]
193
  ast_tree = renpycompat.pickle_loads(raw_pickle)
194
+ patch_ast(ast_tree, clean_translations)
195
  new_rpyc_bytes = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
196
 
197
  return jsonify({