izuemon commited on
Commit
8931145
·
verified ·
1 Parent(s): 8b1b0b7

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +127 -43
turbowarp-server/qr-converter.py CHANGED
@@ -18,16 +18,35 @@ print("[INFO] Connected successfully.")
18
  def get_var(name):
19
  try:
20
  value = tw.get_variable(name=name, name_literal=False)
21
- print(f"[GET] Variable '{name}' = {value[:50]}..." if value and len(value) > 50 else f"[GET] Variable '{name}' = {value}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  return value
23
  except Exception as e:
24
  print(f"[ERROR] Failed to get variable '{name}': {e}")
25
- return None
26
 
27
  def set_var(name, value):
28
  try:
29
  tw.set_variable(name=name, value=value, name_literal=False)
30
- print(f"[SET] Variable '{name}' = {value[:50]}..." if len(value) > 50 else f"[SET] Variable '{name}' = {value}")
31
  return True
32
  except Exception as e:
33
  print(f"[ERROR] Failed to set variable '{name}': {e}")
@@ -39,21 +58,47 @@ with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
39
  n_chars = [line.strip() for line in f]
40
  print(f"[INFO] Loaded {len(n_chars)} characters.")
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def decode_prompt(encoded_str):
43
- """クラウド変数の数字列を元にプロンプト文字列に復号"""
44
  chars = []
45
- for i in range(0, len(encoded_str), 2):
 
46
  idx = int(encoded_str[i:i+2])
47
- if idx < len(n_chars):
 
 
48
  chars.append(n_chars[idx])
 
 
 
49
  decoded = "".join(chars)
50
  print(f"[DECODE] Encoded prompt -> '{decoded[:50]}...'")
51
  return decoded
52
 
53
  def rgb_to_scratch_number(rgb):
54
- """RGBを0-999999の10進数に変換"""
55
  r, g, b = rgb
56
- return f"{r:03}{g:03}{b:03}"
 
 
 
 
57
 
58
  def generate_image(prompt):
59
  """APIから352x352の画像生成"""
@@ -76,122 +121,161 @@ def generate_image(prompt):
76
  return img
77
 
78
  def resize_and_encode(img):
79
- """90x90にリサイズして数字列に変換"""
80
  img = img.resize((90, 90))
81
  print("[INFO] Resized image to 90x90.")
 
82
  encoded = ""
 
 
83
  for y in range(90):
84
  for x in range(90):
85
- encoded += rgb_to_scratch_number(img.getpixel((x, y)))
86
- print(f"[INFO] Image encoded to string of length {len(encoded)}.")
87
- return "10" + encoded # 先頭に "10"
 
 
 
 
 
 
 
 
 
88
 
89
  def split_packets(data, max_length=9998):
90
  """10000文字制限に合わせて分割(先頭 '10' 含む)"""
91
  packets = []
92
  idx = 0
 
 
 
93
  while idx < len(data):
94
  chunk = data[idx:idx + max_length]
95
  packets.append(chunk)
96
  idx += max_length
97
- print(f"[INFO] Data split into {len(packets)} packet(s).")
 
 
98
  return packets
99
 
100
  # --- メインループ ---
101
  print("[INFO] Starting main loop...")
102
- last_processed_id = "" # 最後に処理したIDを記録
 
 
 
 
 
103
 
104
  while True:
105
  try:
106
  n1 = get_var("n1")
107
  n0 = get_var("n0")
108
 
109
- # n1が存在し、長さが3以上で、先頭が"0"(新規リクエスト)
 
 
 
 
110
  if n1 and len(n1) >= 3 and n1[0] == "0":
111
- user_id = n1[1:3] # ユーザーID(2桁)
112
- request_data = n1 # 完全なリクエストデータ
113
 
114
  print(f"[INFO] Received request from user {user_id}")
115
  print(f"[INFO] Request data length: {len(request_data)}")
116
 
117
- # 同じリクエストを繰り返し処理しないようにチェック
118
  if request_data == last_processed_id:
119
- print("[INFO] Already processed this request, marking as read...")
120
- # 既読マークをつける(先頭を"01"に変更)
121
  marked_as_read = "01" + request_data[2:]
122
  set_var("n1", marked_as_read)
123
  time.sleep(0.1)
124
  continue
125
 
126
- # n0が利用可能かチェック
127
- if n0 == "0" or n0 is None:
128
  print("[INFO] n0 is free, starting processing...")
129
 
130
- # 処理中フラグをセット
131
  set_var("n0", "1")
132
 
133
- # リクエストを既読にする(先頭を"01"に変更)
134
  marked_as_read = "01" + request_data[2:]
135
  set_var("n1", marked_as_read)
136
 
137
- # プロンプトをデコード(先頭の"0" + ユーザーID(2桁)を除去)
138
  encoded_prompt = request_data[3:]
 
139
  prompt = decode_prompt(encoded_prompt)
 
140
 
141
- # 画像生成
142
  img = generate_image(prompt)
143
  scratch_data = resize_and_encode(img)
144
 
145
  # パケット分割
146
  packets = split_packets(scratch_data)
 
147
 
148
- # 最初のパケット送信
149
  for i, pkt in enumerate(packets):
150
- print(f"[INFO] Sending packet {i+1}/{len(packets)}")
151
- set_var("n1", pkt)
 
 
 
152
 
153
  if i < len(packets) - 1:
154
- # 次のパケットのACK
155
- print("[INFO] Waiting for ACK '11'...")
156
  ack_timeout = 0
157
- while ack_timeout < 50: # 5秒タイムアウト
 
158
  current_n1 = get_var("n1")
159
  if current_n1 == "11":
160
- print("[INFO] Received ACK")
 
161
  break
162
- time.sleep(0.1)
163
  ack_timeout += 1
164
 
165
- if ack_timeout >= 50:
166
- print("[ERROR] ACK timeout")
167
  set_var("n0", "0")
168
  break
169
  else:
170
- # 最後のパケットは完了
171
  print("[INFO] Waiting for completion '99'...")
172
  complete_timeout = 0
 
173
  while complete_timeout < 50:
174
  current_n1 = get_var("n1")
175
  if current_n1 == "99":
176
  print("[INFO] Received completion signal")
 
177
  break
178
- time.sleep(0.1)
179
  complete_timeout += 1
 
 
 
180
 
181
- # 完了後リセット
182
  print("[INFO] Transmission complete. Resetting n0.")
183
  set_var("n0", "0")
184
- last_processed_id = request_data # 処理済みとして記録
 
185
 
186
  else:
187
  print("[INFO] n0 is busy, waiting...")
188
  else:
189
- # 何もしない
190
- pass
 
 
191
 
192
  except Exception as e:
193
  print(f"[ERROR] Exception in main loop: {e}")
194
  import traceback
195
  traceback.print_exc()
196
 
197
- time.sleep(0.2)
 
18
  def get_var(name):
19
  try:
20
  value = tw.get_variable(name=name, name_literal=False)
21
+
22
+ # デバッグ用に生の値を出力
23
+ print(f"[DEBUG] Raw value of '{name}': {value} (type: {type(value).__name__})")
24
+
25
+ # Noneの場合は"0"として扱う
26
+ if value is None:
27
+ print(f"[WARNING] Variable '{name}' is None, treating as '0'")
28
+ return "0"
29
+
30
+ # 様々な型を文字列に変換
31
+ if isinstance(value, (int, float)):
32
+ value = str(int(value))
33
+ print(f"[GET] Variable '{name}' converted from number to string: '{value}'")
34
+ elif not isinstance(value, str):
35
+ value = str(value)
36
+ print(f"[GET] Variable '{name}' converted from {type(value).__name__} to string: '{value}'")
37
+
38
+ # 表示用に切り詰め
39
+ display_value = value[:50] + "..." if len(value) > 50 else value
40
+ print(f"[GET] Variable '{name}' = '{display_value}'")
41
  return value
42
  except Exception as e:
43
  print(f"[ERROR] Failed to get variable '{name}': {e}")
44
+ return "0"
45
 
46
  def set_var(name, value):
47
  try:
48
  tw.set_variable(name=name, value=value, name_literal=False)
49
+ print(f"[SET] Variable '{name}' = '{value[:50]}...'" if len(value) > 50 else f"[SET] Variable '{name}' = '{value}'")
50
  return True
51
  except Exception as e:
52
  print(f"[ERROR] Failed to set variable '{name}': {e}")
 
58
  n_chars = [line.strip() for line in f]
59
  print(f"[INFO] Loaded {len(n_chars)} characters.")
60
 
61
+ def encode_prompt(prompt):
62
+ """プロンプト文字列を数字列にエンコード(半角スペースは96として特別処理)"""
63
+ encoded = ""
64
+ for char in prompt:
65
+ if char == " ":
66
+ encoded += "96"
67
+ else:
68
+ try:
69
+ idx = n_chars.index(char)
70
+ encoded += f"{idx:02d}"
71
+ except ValueError:
72
+ print(f"[WARNING] Character '{char}' not found in n_chars, skipping")
73
+ continue
74
+ print(f"[ENCODE] Prompt encoded to length {len(encoded)}")
75
+ return encoded
76
+
77
  def decode_prompt(encoded_str):
78
+ """クラウド変数の数字列を元にプロンプト文字列に復号(96は半角スペースとして処理)"""
79
  chars = []
80
+ i = 0
81
+ while i < len(encoded_str):
82
  idx = int(encoded_str[i:i+2])
83
+ if idx == 96:
84
+ chars.append(" ")
85
+ elif idx < len(n_chars):
86
  chars.append(n_chars[idx])
87
+ else:
88
+ print(f"[WARNING] Invalid index {idx} at position {i}")
89
+ i += 2
90
  decoded = "".join(chars)
91
  print(f"[DECODE] Encoded prompt -> '{decoded[:50]}...'")
92
  return decoded
93
 
94
  def rgb_to_scratch_number(rgb):
95
+ """RGBを6桁の10進数に変換 (R:00-99, G:00-99, B:00-99)"""
96
  r, g, b = rgb
97
+ # 各色を0-99の範囲に収める(元が0-255の場合)
98
+ r_scaled = int(r * 99 / 255)
99
+ g_scaled = int(g * 99 / 255)
100
+ b_scaled = int(b * 99 / 255)
101
+ return f"{r_scaled:02d}{g_scaled:02d}{b_scaled:02d}"
102
 
103
  def generate_image(prompt):
104
  """APIから352x352の画像生成"""
 
121
  return img
122
 
123
  def resize_and_encode(img):
124
+ """90x90にリサイズして6桁の数字列に変換(各ピクセル6桁)"""
125
  img = img.resize((90, 90))
126
  print("[INFO] Resized image to 90x90.")
127
+
128
  encoded = ""
129
+ total_pixels = 0
130
+
131
  for y in range(90):
132
  for x in range(90):
133
+ pixel = img.getpixel((x, y))
134
+ # RGB値を取得(RGBAの場合はRGBのみ使用)
135
+ if len(pixel) >= 3:
136
+ r, g, b = pixel[:3]
137
+ else:
138
+ r, g, b = pixel, pixel, pixel
139
+ encoded += rgb_to_scratch_number((r, g, b))
140
+ total_pixels += 1
141
+
142
+ expected_length = total_pixels * 6
143
+ print(f"[INFO] Encoded {total_pixels} pixels to string of length {len(encoded)} (expected: {expected_length})")
144
+ return encoded
145
 
146
  def split_packets(data, max_length=9998):
147
  """10000文字制限に合わせて分割(先頭 '10' 含む)"""
148
  packets = []
149
  idx = 0
150
+ total_length = len(data)
151
+ expected_packets = (total_length + max_length - 1) // max_length
152
+
153
  while idx < len(data):
154
  chunk = data[idx:idx + max_length]
155
  packets.append(chunk)
156
  idx += max_length
157
+
158
+ print(f"[INFO] Data length: {total_length}, max packet size: {max_length}")
159
+ print(f"[INFO] Expected {expected_packets} packets, actual {len(packets)} packets")
160
  return packets
161
 
162
  # --- メインループ ---
163
  print("[INFO] Starting main loop...")
164
+ last_processed_id = ""
165
+
166
+ # 初期化
167
+ set_var("n0", "0")
168
+ set_var("n1", "0")
169
+ time.sleep(1)
170
 
171
  while True:
172
  try:
173
  n1 = get_var("n1")
174
  n0 = get_var("n0")
175
 
176
+ print(f"[DEBUG] n0='{n0}', n1='{n1[:30]}...' if n1 and len(n1)>30 else n1")
177
+
178
+ is_n0_free = (n0 == "0")
179
+ print(f"[DEBUG] is_n0_free: {is_n0_free}")
180
+
181
  if n1 and len(n1) >= 3 and n1[0] == "0":
182
+ user_id = n1[1:3]
183
+ request_data = n1
184
 
185
  print(f"[INFO] Received request from user {user_id}")
186
  print(f"[INFO] Request data length: {len(request_data)}")
187
 
 
188
  if request_data == last_processed_id:
189
+ print("[INFO] Already processed, marking as read...")
 
190
  marked_as_read = "01" + request_data[2:]
191
  set_var("n1", marked_as_read)
192
  time.sleep(0.1)
193
  continue
194
 
195
+ if is_n0_free:
 
196
  print("[INFO] n0 is free, starting processing...")
197
 
198
+ # 処理中フラグ
199
  set_var("n0", "1")
200
 
201
+ # リクエストを既読に
202
  marked_as_read = "01" + request_data[2:]
203
  set_var("n1", marked_as_read)
204
 
205
+ # プロンプトをデコード
206
  encoded_prompt = request_data[3:]
207
+ print(f"[INFO] Encoded prompt length: {len(encoded_prompt)}")
208
  prompt = decode_prompt(encoded_prompt)
209
+ print(f"[INFO] Decoded prompt: '{prompt}'")
210
 
211
+ # 画像生成とエンコード
212
  img = generate_image(prompt)
213
  scratch_data = resize_and_encode(img)
214
 
215
  # パケット分割
216
  packets = split_packets(scratch_data)
217
+ print(f"[INFO] Will send {len(packets)} packets")
218
 
219
+ # パケット送信
220
  for i, pkt in enumerate(packets):
221
+ packet_num = i + 1
222
+ print(f"[INFO] Sending packet {packet_num}/{len(packets)} (size: {len(pkt)} chars)")
223
+
224
+ # パケット送信
225
+ set_var("n1", "10" + pkt)
226
 
227
  if i < len(packets) - 1:
228
+ # ACK待
229
+ print(f"[INFO] Waiting for ACK for packet {packet_num}...")
230
  ack_timeout = 0
231
+ ack_received = False
232
+ while ack_timeout < 50:
233
  current_n1 = get_var("n1")
234
  if current_n1 == "11":
235
+ print(f"[INFO] Received ACK for packet {packet_num}")
236
+ ack_received = True
237
  break
238
+ time.sleep(0.2)
239
  ack_timeout += 1
240
 
241
+ if not ack_received:
242
+ print(f"[ERROR] ACK timeout for packet {packet_num}")
243
  set_var("n0", "0")
244
  break
245
  else:
246
+ # 完了待
247
  print("[INFO] Waiting for completion '99'...")
248
  complete_timeout = 0
249
+ complete_received = False
250
  while complete_timeout < 50:
251
  current_n1 = get_var("n1")
252
  if current_n1 == "99":
253
  print("[INFO] Received completion signal")
254
+ complete_received = True
255
  break
256
+ time.sleep(0.2)
257
  complete_timeout += 1
258
+
259
+ if not complete_received:
260
+ print("[ERROR] Completion timeout")
261
 
262
+ # 完了
263
  print("[INFO] Transmission complete. Resetting n0.")
264
  set_var("n0", "0")
265
+ last_processed_id = request_data
266
+ print(f"[INFO] Set last_processed_id")
267
 
268
  else:
269
  print("[INFO] n0 is busy, waiting...")
270
  else:
271
+ if n1:
272
+ print(f"[DEBUG] n1 condition not met: first char='{n1[0] if n1 else 'None'}', length={len(n1) if n1 else 0}")
273
+ else:
274
+ print("[DEBUG] n1 is None or empty")
275
 
276
  except Exception as e:
277
  print(f"[ERROR] Exception in main loop: {e}")
278
  import traceback
279
  traceback.print_exc()
280
 
281
+ time.sleep(0.3)