izuemon commited on
Commit
f3b6b14
·
verified ·
1 Parent(s): fd4ff16

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +50 -50
turbowarp-server/qr-converter.py CHANGED
@@ -19,9 +19,6 @@ 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'")
@@ -29,19 +26,18 @@ def get_var(name):
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" # エラー時も"0"を返す
45
 
46
  def set_var(name, value):
47
  try:
@@ -62,7 +58,7 @@ def encode_prompt(prompt):
62
  """プロンプト文字列を数字列にエンコード(半角スペースは96として特別処理)"""
63
  encoded = ""
64
  for char in prompt:
65
- if char == " ": # 半角スペースを特別に96として処理
66
  encoded += "96"
67
  else:
68
  try:
@@ -80,7 +76,7 @@ def decode_prompt(encoded_str):
80
  i = 0
81
  while i < len(encoded_str):
82
  idx = int(encoded_str[i:i+2])
83
- if idx == 96: # 96は半角スペースとして扱う
84
  chars.append(" ")
85
  elif idx < len(n_chars):
86
  chars.append(n_chars[idx])
@@ -92,9 +88,12 @@ def decode_prompt(encoded_str):
92
  return decoded
93
 
94
  def rgb_to_scratch_number(rgb):
95
- """RGBを0-999999の10進数に変換"""
96
  r, g, b = rgb
97
- return f"{r:03}{g:03}{b:03}"
 
 
 
98
 
99
  def generate_image(prompt):
100
  """APIから352x352の画像生成"""
@@ -117,81 +116,77 @@ def generate_image(prompt):
117
  return img
118
 
119
  def resize_and_encode(img):
120
- """90x90にリサイズして数字列に変換"""
121
  img = img.resize((90, 90))
122
  print("[INFO] Resized image to 90x90.")
 
123
  encoded = ""
124
  for y in range(90):
125
  for x in range(90):
126
  encoded += rgb_to_scratch_number(img.getpixel((x, y)))
127
- print(f"[INFO] Image encoded to string of length {len(encoded)}.")
 
 
128
  return encoded
129
 
130
  def split_packets(data, max_length=9998):
131
- """10000文字制限に合わせて分割(先頭 '10' 含む)"""
132
  packets = []
133
  idx = 0
134
  while idx < len(data):
135
  chunk = data[idx:idx + max_length]
136
  packets.append(chunk)
137
  idx += max_length
138
- print(f"[INFO] Data split into {len(packets)} packet(s).")
 
 
 
 
 
 
139
  return packets
140
 
141
  # --- メインループ ---
142
  print("[INFO] Starting main loop...")
143
- last_processed_id = "" # 最後に処理したIDを記録
144
-
145
- # 初期化時に変数をリセット
146
  set_var("n0", "0")
147
  set_var("n1", "0")
148
- time.sleep(1) # 設定が反映されるのを待つ
149
 
150
  while True:
151
  try:
152
- # 変数を取得
153
  n1 = get_var("n1")
154
  n0 = get_var("n0")
155
 
156
- # デバッグ情報
157
- print(f"[DEBUG] n0='{n0}', n1='{n1[:30]}...' if n1 and len(n1)>30 else n1")
158
-
159
- # n0が利用可能かチェック(厳密な比較)
160
- is_n0_free = (n0 == "0")
161
- print(f"[DEBUG] is_n0_free: {is_n0_free}")
162
-
163
  # n1が存在し、長さが3以上で、先頭が"0"(新規リクエスト)
164
  if n1 and len(n1) >= 3 and n1[0] == "0":
165
- user_id = n1[1:3] # ユーザーID(2桁)
166
- request_data = n1 # 完全なリクエストデータ
167
 
168
  print(f"[INFO] Received request from user {user_id}")
169
  print(f"[INFO] Request data length: {len(request_data)}")
170
- print(f"[INFO] Request data preview: {request_data[:50]}...")
171
 
172
  # 同じリクエストを繰り返し処理しないようにチェック
173
  if request_data == last_processed_id:
174
  print("[INFO] Already processed this request, marking as read...")
175
- # 既読マークをつける(先頭を"01"に変更)
176
  marked_as_read = "01" + request_data[2:]
177
  set_var("n1", marked_as_read)
178
  time.sleep(0.1)
179
  continue
180
 
181
  # n0が利用可能かチェック
182
- if is_n0_free:
183
  print("[INFO] n0 is free, starting processing...")
184
 
185
  # 処理中フラグをセット
186
  set_var("n0", "1")
187
 
188
- # リクエストを既読にする(先頭を"01"に変更)
189
  marked_as_read = "01" + request_data[2:]
190
  set_var("n1", marked_as_read)
191
 
192
- # プロンプトをデコード(先頭の"0" + ユーザーID(2桁)を除去)
193
  encoded_prompt = request_data[3:]
194
- print(f"[INFO] Encoded prompt length: {len(encoded_prompt)}")
195
  prompt = decode_prompt(encoded_prompt)
196
  print(f"[INFO] Decoded prompt: '{prompt}'")
197
 
@@ -199,17 +194,22 @@ while True:
199
  img = generate_image(prompt)
200
  scratch_data = resize_and_encode(img)
201
 
 
 
 
 
202
  # パケット分割
203
- packets = split_packets(scratch_data)
204
 
205
  # パケット送信
206
  for i, pkt in enumerate(packets):
207
- print(f"[INFO] Sending packet {i+1}/{len(packets)}")
 
208
  set_var("n1", "10" + pkt)
209
 
210
- if i < len(packets) - 1:
211
- # 次のパケットACKを待つ
212
- print("[INFO] Waiting for ACK '11'...")
213
  ack_timeout = 0
214
  ack_received = False
215
  while ack_timeout < 50: # 5秒タイムアウト
@@ -218,7 +218,7 @@ while True:
218
  print("[INFO] Received ACK")
219
  ack_received = True
220
  break
221
- time.sleep(0.3)
222
  ack_timeout += 1
223
 
224
  if not ack_received:
@@ -226,7 +226,7 @@ while True:
226
  set_var("n0", "0")
227
  break
228
  else:
229
- # 最後のパケット完了を待つ
230
  print("[INFO] Waiting for completion '99'...")
231
  complete_timeout = 0
232
  complete_received = False
@@ -236,7 +236,7 @@ while True:
236
  print("[INFO] Received completion signal")
237
  complete_received = True
238
  break
239
- time.sleep(0.3)
240
  complete_timeout += 1
241
 
242
  if not complete_received:
@@ -245,21 +245,21 @@ while True:
245
  # 完了後リセット
246
  print("[INFO] Transmission complete. Resetting n0.")
247
  set_var("n0", "0")
248
- last_processed_id = request_data # 処理済みとして記録
249
- print(f"[INFO] Set last_processed_id to: {last_processed_id[:50]}...")
250
 
251
  else:
252
- print("[INFO] n0 is busy, waiting...")
253
  else:
254
- # n1が条件を満たさない場合
255
- if n1:
256
- print(f"[DEBUG] n1 does not meet conditions: first char='{n1[0] if n1 else 'None'}', length={len(n1) if n1 else 0}")
257
  else:
258
- print("[DEBUG] n1 is None or empty")
259
 
260
  except Exception as e:
261
  print(f"[ERROR] Exception in main loop: {e}")
262
  import traceback
263
  traceback.print_exc()
 
 
264
 
265
- time.sleep(0.5) # 少し長めの待機時間
 
19
  try:
20
  value = tw.get_variable(name=name, name_literal=False)
21
 
 
 
 
22
  # Noneの場合は"0"として扱う
23
  if value is None:
24
  print(f"[WARNING] Variable '{name}' is None, treating as '0'")
 
26
 
27
  # 様々な型を文字列に変換
28
  if isinstance(value, (int, float)):
29
+ value = str(int(value))
30
  print(f"[GET] Variable '{name}' converted from number to string: '{value}'")
31
  elif not isinstance(value, str):
32
  value = str(value)
33
  print(f"[GET] Variable '{name}' converted from {type(value).__name__} to string: '{value}'")
34
 
 
35
  display_value = value[:50] + "..." if len(value) > 50 else value
36
  print(f"[GET] Variable '{name}' = '{display_value}'")
37
  return value
38
  except Exception as e:
39
  print(f"[ERROR] Failed to get variable '{name}': {e}")
40
+ return "0"
41
 
42
  def set_var(name, value):
43
  try:
 
58
  """プロンプト文字列を数字列にエンコード(半角スペースは96として特別処理)"""
59
  encoded = ""
60
  for char in prompt:
61
+ if char == " ":
62
  encoded += "96"
63
  else:
64
  try:
 
76
  i = 0
77
  while i < len(encoded_str):
78
  idx = int(encoded_str[i:i+2])
79
+ if idx == 96:
80
  chars.append(" ")
81
  elif idx < len(n_chars):
82
  chars.append(n_chars[idx])
 
88
  return decoded
89
 
90
  def rgb_to_scratch_number(rgb):
91
+ """RGBを0-999999の6桁の10進数に変換(RGB各2桁ではなく、6桁の数字)"""
92
  r, g, b = rgb
93
+ # RGBを1つの6桁の数字に変換(例: RGB(255,128,64) -> 255128064)
94
+ value = (r * 10000) + (g * 100) + b
95
+ # 6桁にゼロパディング
96
+ return f"{value:06d}"
97
 
98
  def generate_image(prompt):
99
  """APIから352x352の画像生成"""
 
116
  return img
117
 
118
  def resize_and_encode(img):
119
+ """90x90にリサイズして6桁の数字列に変換"""
120
  img = img.resize((90, 90))
121
  print("[INFO] Resized image to 90x90.")
122
+
123
  encoded = ""
124
  for y in range(90):
125
  for x in range(90):
126
  encoded += rgb_to_scratch_number(img.getpixel((x, y)))
127
+
128
+ expected_length = 90 * 90 * 6 # 8100 * 6 = 48600
129
+ print(f"[INFO] Image encoded to string of length {len(encoded)} (expected: {expected_length})")
130
  return encoded
131
 
132
  def split_packets(data, max_length=9998):
133
+ """10000文字制限に合わせて分割(送信時の先頭 '10' 含むため、実質9998文字)"""
134
  packets = []
135
  idx = 0
136
  while idx < len(data):
137
  chunk = data[idx:idx + max_length]
138
  packets.append(chunk)
139
  idx += max_length
140
+
141
+ # パケット数の計算
142
+ total_packets = len(packets)
143
+ print(f"[INFO] Data split into {total_packets} packet(s).")
144
+ print(f"[INFO] Total data length: {len(data)}, Max per packet: {max_length}")
145
+ print(f"[INFO] Expected packets: {len(data) // max_length + (1 if len(data) % max_length else 0)}")
146
+
147
  return packets
148
 
149
  # --- メインループ ---
150
  print("[INFO] Starting main loop...")
151
+ last_processed_id = ""
 
 
152
  set_var("n0", "0")
153
  set_var("n1", "0")
154
+ time.sleep(1)
155
 
156
  while True:
157
  try:
 
158
  n1 = get_var("n1")
159
  n0 = get_var("n0")
160
 
 
 
 
 
 
 
 
161
  # n1が存在し、長さが3以上で、先頭が"0"(新規リクエスト)
162
  if n1 and len(n1) >= 3 and n1[0] == "0":
163
+ user_id = n1[1:3]
164
+ request_data = n1
165
 
166
  print(f"[INFO] Received request from user {user_id}")
167
  print(f"[INFO] Request data length: {len(request_data)}")
 
168
 
169
  # 同じリクエストを繰り返し処理しないようにチェック
170
  if request_data == last_processed_id:
171
  print("[INFO] Already processed this request, marking as read...")
 
172
  marked_as_read = "01" + request_data[2:]
173
  set_var("n1", marked_as_read)
174
  time.sleep(0.1)
175
  continue
176
 
177
  # n0が利用可能かチェック
178
+ if n0 == "0":
179
  print("[INFO] n0 is free, starting processing...")
180
 
181
  # 処理中フラグをセット
182
  set_var("n0", "1")
183
 
184
+ # リクエストを既読にする
185
  marked_as_read = "01" + request_data[2:]
186
  set_var("n1", marked_as_read)
187
 
188
+ # プロンプトをデコード
189
  encoded_prompt = request_data[3:]
 
190
  prompt = decode_prompt(encoded_prompt)
191
  print(f"[INFO] Decoded prompt: '{prompt}'")
192
 
 
194
  img = generate_image(prompt)
195
  scratch_data = resize_and_encode(img)
196
 
197
+ # データサイズの確認
198
+ print(f"[INFO] Total image data size: {len(scratch_data)} characters")
199
+ print(f"[INFO] Expected packets: {len(scratch_data) // 9998 + (1 if len(scratch_data) % 9998 else 0)}")
200
+
201
  # パケット分割
202
+ packets = split_packets(scratch_data, max_length=9998)
203
 
204
  # パケット送信
205
  for i, pkt in enumerate(packets):
206
+ packet_num = i + 1
207
+ print(f"[INFO] Sending packet {packet_num}/{len(packets)} (size: {len(pkt)} chars)")
208
  set_var("n1", "10" + pkt)
209
 
210
+ if packet_num < len(packets):
211
+ # 中間パケット: ACK '11' を待つ
212
+ print(f"[INFO] Waiting for ACK '11' (packet {packet_num}/{len(packets)})...")
213
  ack_timeout = 0
214
  ack_received = False
215
  while ack_timeout < 50: # 5秒タイムアウト
 
218
  print("[INFO] Received ACK")
219
  ack_received = True
220
  break
221
+ time.sleep(0.1)
222
  ack_timeout += 1
223
 
224
  if not ack_received:
 
226
  set_var("n0", "0")
227
  break
228
  else:
229
+ # 最パケット: 完了 '99' を待つ
230
  print("[INFO] Waiting for completion '99'...")
231
  complete_timeout = 0
232
  complete_received = False
 
236
  print("[INFO] Received completion signal")
237
  complete_received = True
238
  break
239
+ time.sleep(0.1)
240
  complete_timeout += 1
241
 
242
  if not complete_received:
 
245
  # 完了後リセット
246
  print("[INFO] Transmission complete. Resetting n0.")
247
  set_var("n0", "0")
248
+ last_processed_id = request_data
 
249
 
250
  else:
251
+ print(f"[INFO] n0 is busy (value: '{n0}'), waiting...")
252
  else:
253
+ if n1 and len(n1) >= 1:
254
+ print(f"[DEBUG] n1[0]='{n1[0]}', length={len(n1)}")
 
255
  else:
256
+ print("[DEBUG] No valid request")
257
 
258
  except Exception as e:
259
  print(f"[ERROR] Exception in main loop: {e}")
260
  import traceback
261
  traceback.print_exc()
262
+ # エラー時はn0をリセット
263
+ set_var("n0", "0")
264
 
265
+ time.sleep(0.2)