Spaces:
Running
Running
Update turbowarp-server/qr-converter.py
Browse files- turbowarp-server/qr-converter.py +62 -46
turbowarp-server/qr-converter.py
CHANGED
|
@@ -19,6 +19,9 @@ def get_var(name):
|
|
| 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'")
|
|
@@ -32,6 +35,7 @@ def get_var(name):
|
|
| 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
|
|
@@ -88,12 +92,13 @@ def decode_prompt(encoded_str):
|
|
| 88 |
return decoded
|
| 89 |
|
| 90 |
def rgb_to_scratch_number(rgb):
|
| 91 |
-
"""RGBを
|
| 92 |
r, g, b = rgb
|
| 93 |
-
#
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
| 97 |
|
| 98 |
def generate_image(prompt):
|
| 99 |
"""APIから352x352の画像生成"""
|
|
@@ -116,39 +121,49 @@ def generate_image(prompt):
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
expected_length =
|
| 129 |
-
print(f"[INFO]
|
| 130 |
return encoded
|
| 131 |
|
| 132 |
def split_packets(data, max_length=9998):
|
| 133 |
-
"""10000文字制限に合わせて分割(
|
| 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 |
-
|
| 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)
|
|
@@ -158,7 +173,11 @@ while True:
|
|
| 158 |
n1 = get_var("n1")
|
| 159 |
n0 = get_var("n0")
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
if n1 and len(n1) >= 3 and n1[0] == "0":
|
| 163 |
user_id = n1[1:3]
|
| 164 |
request_data = n1
|
|
@@ -166,67 +185,65 @@ while True:
|
|
| 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
|
| 172 |
marked_as_read = "01" + request_data[2:]
|
| 173 |
set_var("n1", marked_as_read)
|
| 174 |
time.sleep(0.1)
|
| 175 |
continue
|
| 176 |
|
| 177 |
-
|
| 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 |
|
| 193 |
-
# 画像生成
|
| 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
|
|
|
|
| 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
|
| 211 |
-
#
|
| 212 |
-
print(f"[INFO] Waiting for ACK
|
| 213 |
ack_timeout = 0
|
| 214 |
ack_received = False
|
| 215 |
-
while ack_timeout < 50:
|
| 216 |
current_n1 = get_var("n1")
|
| 217 |
if current_n1 == "11":
|
| 218 |
-
print("[INFO] Received ACK")
|
| 219 |
ack_received = True
|
| 220 |
break
|
| 221 |
-
time.sleep(0.
|
| 222 |
ack_timeout += 1
|
| 223 |
|
| 224 |
if not ack_received:
|
| 225 |
-
print("[ERROR] ACK timeout")
|
| 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,30 +253,29 @@ while True:
|
|
| 236 |
print("[INFO] Received completion signal")
|
| 237 |
complete_received = True
|
| 238 |
break
|
| 239 |
-
time.sleep(0.
|
| 240 |
complete_timeout += 1
|
| 241 |
|
| 242 |
if not complete_received:
|
| 243 |
print("[ERROR] Completion timeout")
|
| 244 |
|
| 245 |
-
# 完了
|
| 246 |
print("[INFO] Transmission complete. Resetting n0.")
|
| 247 |
set_var("n0", "0")
|
| 248 |
last_processed_id = request_data
|
|
|
|
| 249 |
|
| 250 |
else:
|
| 251 |
-
print(
|
| 252 |
else:
|
| 253 |
-
if n1
|
| 254 |
-
print(f"[DEBUG] n1
|
| 255 |
else:
|
| 256 |
-
print("[DEBUG]
|
| 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.
|
|
|
|
| 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'")
|
|
|
|
| 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
|
|
|
|
| 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)
|
|
|
|
| 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
|
|
|
|
| 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
|
|
|
|
| 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)
|