Spaces:
Running
Running
Update turbowarp-server/qr-converter.py
Browse files- turbowarp-server/qr-converter.py +126 -82
turbowarp-server/qr-converter.py
CHANGED
|
@@ -19,29 +19,38 @@ 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 |
return "0"
|
| 25 |
|
| 26 |
# 様々な型を文字列に変換
|
| 27 |
if isinstance(value, (int, float)):
|
| 28 |
-
value = str(int(value))
|
|
|
|
| 29 |
elif not isinstance(value, str):
|
| 30 |
value = str(value)
|
|
|
|
| 31 |
|
|
|
|
|
|
|
|
|
|
| 32 |
return value
|
| 33 |
except Exception as e:
|
| 34 |
print(f"[ERROR] Failed to get variable '{name}': {e}")
|
| 35 |
-
return "0"
|
| 36 |
|
| 37 |
def set_var(name, value):
|
| 38 |
try:
|
| 39 |
tw.set_variable(name=name, value=value, name_literal=False)
|
| 40 |
-
print(f"[SET] {name} = {value[:50]}..." if len(value) > 50 else f"[SET] {name} = {value}")
|
| 41 |
return True
|
| 42 |
except Exception as e:
|
| 43 |
print(f"[ERROR] Failed to set variable '{name}': {e}")
|
| 44 |
-
return
|
| 45 |
|
| 46 |
# --- n-chars.txt の読み込み ---
|
| 47 |
print("[INFO] Loading n-chars.txt...")
|
|
@@ -49,6 +58,22 @@ with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
|
|
| 49 |
n_chars = [line.strip() for line in f]
|
| 50 |
print(f"[INFO] Loaded {len(n_chars)} characters.")
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def decode_prompt(encoded_str):
|
| 53 |
"""クラウド変数の数字列を元にプロンプト文字列に復号(96は半角スペースとして処理)"""
|
| 54 |
chars = []
|
|
@@ -63,7 +88,7 @@ def decode_prompt(encoded_str):
|
|
| 63 |
print(f"[WARNING] Invalid index {idx} at position {i}")
|
| 64 |
i += 2
|
| 65 |
decoded = "".join(chars)
|
| 66 |
-
print(f"[DECODE]
|
| 67 |
return decoded
|
| 68 |
|
| 69 |
def rgb_to_scratch_number(rgb):
|
|
@@ -88,134 +113,153 @@ def generate_image(prompt):
|
|
| 88 |
resp = requests.get("https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen", params=params)
|
| 89 |
resp.raise_for_status()
|
| 90 |
img = Image.open(BytesIO(resp.content))
|
| 91 |
-
print(f"[INFO] Image generated: size={img.size}")
|
| 92 |
return img
|
| 93 |
|
| 94 |
def resize_and_encode(img):
|
| 95 |
"""90x90にリサイズして数字列に変換"""
|
| 96 |
img = img.resize((90, 90))
|
| 97 |
-
print("[INFO] Resized to 90x90")
|
| 98 |
encoded = ""
|
| 99 |
for y in range(90):
|
| 100 |
for x in range(90):
|
| 101 |
encoded += rgb_to_scratch_number(img.getpixel((x, y)))
|
| 102 |
-
print(f"[INFO]
|
| 103 |
return encoded
|
| 104 |
|
| 105 |
def split_packets(data, max_length=9998):
|
| 106 |
-
"""10000文字制限に合わせて分割"""
|
| 107 |
packets = []
|
| 108 |
idx = 0
|
| 109 |
while idx < len(data):
|
| 110 |
chunk = data[idx:idx + max_length]
|
| 111 |
packets.append(chunk)
|
| 112 |
idx += max_length
|
| 113 |
-
print(f"[INFO]
|
| 114 |
return packets
|
| 115 |
|
| 116 |
-
def wait_for_signal(expected_value, timeout_seconds=5):
|
| 117 |
-
"""特定のシグナルを待つ"""
|
| 118 |
-
start_time = time.time()
|
| 119 |
-
while time.time() - start_time < timeout_seconds:
|
| 120 |
-
current = get_var("n1")
|
| 121 |
-
if current == expected_value:
|
| 122 |
-
return True
|
| 123 |
-
time.sleep(0.1)
|
| 124 |
-
return False
|
| 125 |
-
|
| 126 |
# --- メインループ ---
|
| 127 |
print("[INFO] Starting main loop...")
|
| 128 |
-
last_processed_id = ""
|
| 129 |
|
| 130 |
-
# 初期化
|
| 131 |
set_var("n0", "0")
|
| 132 |
set_var("n1", "0")
|
| 133 |
-
|
| 134 |
|
| 135 |
while True:
|
| 136 |
try:
|
| 137 |
-
|
| 138 |
n1 = get_var("n1")
|
|
|
|
| 139 |
|
| 140 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
if n1 and len(n1) >= 3 and n1[0] == "0":
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
#
|
| 146 |
if request_data == last_processed_id:
|
| 147 |
-
print(
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
| 150 |
continue
|
| 151 |
|
| 152 |
-
# n0が
|
| 153 |
-
if
|
| 154 |
-
print(
|
| 155 |
|
| 156 |
-
# 処理中フラグを
|
| 157 |
set_var("n0", "1")
|
| 158 |
|
| 159 |
-
# リクエストを既読にする
|
| 160 |
-
|
|
|
|
| 161 |
|
| 162 |
-
# プロンプトをデコード
|
| 163 |
encoded_prompt = request_data[3:]
|
|
|
|
| 164 |
prompt = decode_prompt(encoded_prompt)
|
|
|
|
| 165 |
|
| 166 |
-
# 画像生成
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
#
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
success = False
|
| 185 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
|
| 188 |
-
set_var("n1", "0")
|
| 189 |
-
print(f"[INFO] ACK received for packet {i+1}")
|
| 190 |
-
|
| 191 |
-
if success:
|
| 192 |
-
# 完了シグナルを待つ
|
| 193 |
-
print("[INFO] Waiting for completion signal...")
|
| 194 |
-
if wait_for_signal("99", timeout_seconds=10):
|
| 195 |
-
print("[INFO] Completion received")
|
| 196 |
-
set_var("n1", "0")
|
| 197 |
-
else:
|
| 198 |
print("[ERROR] Completion timeout")
|
| 199 |
-
|
| 200 |
-
# 処理完了
|
| 201 |
-
last_processed_id = request_data
|
| 202 |
-
|
| 203 |
-
except Exception as e:
|
| 204 |
-
print(f"[ERROR] Image processing failed: {e}")
|
| 205 |
-
import traceback
|
| 206 |
-
traceback.print_exc()
|
| 207 |
|
| 208 |
-
#
|
|
|
|
| 209 |
set_var("n0", "0")
|
| 210 |
-
|
|
|
|
| 211 |
|
| 212 |
else:
|
| 213 |
-
print(
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
except Exception as e:
|
| 218 |
-
print(f"[ERROR]
|
| 219 |
import traceback
|
| 220 |
traceback.print_exc()
|
| 221 |
-
|
|
|
|
|
|
| 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" # エラー時も"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}")
|
| 53 |
+
return None
|
| 54 |
|
| 55 |
# --- n-chars.txt の読み込み ---
|
| 56 |
print("[INFO] Loading n-chars.txt...")
|
|
|
|
| 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 == " ": # 半角スペースを特別に96として処理
|
| 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 = []
|
|
|
|
| 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):
|
|
|
|
| 113 |
resp = requests.get("https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen", params=params)
|
| 114 |
resp.raise_for_status()
|
| 115 |
img = Image.open(BytesIO(resp.content))
|
| 116 |
+
print(f"[INFO] Image generated: size={img.size}, mode={img.mode}")
|
| 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 |
|
| 198 |
+
# 画像生成
|
| 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秒タイムアウト
|
| 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.3)
|
| 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
|
| 233 |
+
while complete_timeout < 50:
|
| 234 |
+
current_n1 = get_var("n1")
|
| 235 |
+
if current_n1 == "99":
|
| 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:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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) # 少し長めの待機時間
|