izuemon commited on
Commit
d9350d8
·
verified ·
1 Parent(s): edbd86d

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +44 -71
turbowarp-server/qr-converter.py CHANGED
@@ -17,8 +17,14 @@ tw = scratchcommunication.TwCloudConnection(
17
  def get_var(name):
18
  try:
19
  return tw.get_variable(name=name, name_literal=False)
 
 
 
 
 
 
20
  except Exception as e:
21
- print(f"[ERROR] get_var('{name}') failed: {e}")
22
  traceback.print_exc()
23
  return None
24
 
@@ -26,7 +32,7 @@ def set_var(name, value):
26
  try:
27
  return tw.set_variable(name=name, value=value, name_literal=False)
28
  except Exception as e:
29
- print(f"[ERROR] set_var('{name}', {value}) failed: {e}")
30
  traceback.print_exc()
31
  return None
32
 
@@ -35,35 +41,26 @@ try:
35
  with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
36
  n_chars = [line.strip() for line in f]
37
  except Exception as e:
38
- print(f"[ERROR] Failed to load n-chars.txt: {e}")
39
  traceback.print_exc()
40
  n_chars = []
41
 
42
  def decode_prompt(encoded_str):
43
- """クラウド変数の数字列を元にプロンプト文字列に復号"""
44
- try:
45
- chars = []
46
- for i in range(0, len(encoded_str), 2):
47
  idx = int(encoded_str[i:i+2])
48
  if idx < len(n_chars):
49
  chars.append(n_chars[idx])
50
- return "".join(chars)
51
- except Exception as e:
52
- print(f"[ERROR] decode_prompt failed for '{encoded_str}': {e}")
53
- traceback.print_exc()
54
- return ""
55
 
56
  def rgb_to_scratch_number(rgb):
57
- try:
58
- r, g, b = rgb
59
- return f"{r:03}{g:03}{b:03}"
60
- except Exception as e:
61
- print(f"[ERROR] rgb_to_scratch_number failed for {rgb}: {e}")
62
- traceback.print_exc()
63
- return "000000000"
64
 
65
  def generate_image(prompt):
66
- """APIから352x352の画像生成"""
67
  try:
68
  seed = random.randint(0, 999999)
69
  params = {
@@ -79,84 +76,60 @@ def generate_image(prompt):
79
  resp = requests.get(
80
  "https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen",
81
  params=params,
82
- timeout=30
83
  )
84
  resp.raise_for_status()
85
  return Image.open(BytesIO(resp.content))
86
  except Exception as e:
87
- print(f"[ERROR] generate_image failed for prompt '{prompt}': {e}")
88
  traceback.print_exc()
89
  return None
90
 
91
  def resize_and_encode(img):
92
- """90x90にリサイズして数字列に変換"""
93
- try:
94
- img = img.resize((90, 90))
95
- encoded = ""
96
- for y in range(90):
97
- for x in range(90):
98
- encoded += rgb_to_scratch_number(img.getpixel((x, y)))
99
- return "10" + encoded # 先頭に "10"
100
- except Exception as e:
101
- print(f"[ERROR] resize_and_encode failed: {e}")
102
- traceback.print_exc()
103
- return "10"
104
 
105
  def split_packets(data, max_length=9998):
106
- """10000文字制限に合わせて分割(先頭 '10' 含む)"""
107
- try:
108
- packets = []
109
- idx = 0
110
- while idx < len(data):
111
- chunk = data[idx:idx + max_length]
112
- packets.append(chunk)
113
- idx += max_length
114
- return packets
115
- except Exception as e:
116
- print(f"[ERROR] split_packets failed: {e}")
117
- traceback.print_exc()
118
- return [data]
119
 
120
  # --- メインループ ---
121
  while True:
122
  try:
123
  n1 = get_var("n1")
124
- if n1 and len(n1) >= 3 and n1[0] == "0": # ID受信フラグ
125
- if get_var("n0") == "0": # 他ユーザー未使用
126
  set_var("n0", "1")
127
- user_id = n1[1:3] # 実際のIDはここを調整
128
  encoded_prompt = n1[3:]
129
  prompt = decode_prompt(encoded_prompt)
130
-
131
- # 画像生成
132
  img = generate_image(prompt)
133
  if img is None:
134
- print(f"[WARNING] Image generation failed for user {user_id}. Skipping.")
135
  set_var("n0", "0")
 
136
  continue
137
-
138
  scratch_data = resize_and_encode(img)
139
-
140
- # パケット分割
141
  packets = split_packets(scratch_data)
 
142
  for pkt in packets:
143
- set_var("n1", pkt) # 送信
144
  time.sleep(0.2)
145
- # 次パケット送信待ち
146
- try:
147
- timeout = time.time() + 10 # 10秒でタイムアウト
148
- while get_var("n1") != "11":
149
- if time.time() > timeout:
150
- print(f"[WARNING] Packet acknowledgement timeout for user {user_id}.")
151
- break
152
- time.sleep(0.1)
153
- except Exception as e:
154
- print(f"[ERROR] Waiting for packet ack failed: {e}")
155
- traceback.print_exc()
156
-
157
- # 完了後リセット
158
  set_var("n0", "0")
159
  except Exception as e:
160
- print(f"[ERROR] Main loop exception: {e}")
161
  traceback.print_exc()
162
  time.sleep(0.2)
 
17
  def get_var(name):
18
  try:
19
  return tw.get_variable(name=name, name_literal=False)
20
+ except scratchcommunication.exceptions.NotSupported as e:
21
+ print(f"[WARN] NotSupported error while getting '{name}': {e}")
22
+ return None
23
+ except KeyError as e:
24
+ print(f"[ERROR] KeyError while getting '{name}': {e}")
25
+ return None
26
  except Exception as e:
27
+ print(f"[ERROR] Unexpected error while getting '{name}': {e}")
28
  traceback.print_exc()
29
  return None
30
 
 
32
  try:
33
  return tw.set_variable(name=name, value=value, name_literal=False)
34
  except Exception as e:
35
+ print(f"[ERROR] Failed to set '{name}' to '{value}': {e}")
36
  traceback.print_exc()
37
  return None
38
 
 
41
  with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
42
  n_chars = [line.strip() for line in f]
43
  except Exception as e:
44
+ print(f"[FATAL] Failed to load n-chars.txt: {e}")
45
  traceback.print_exc()
46
  n_chars = []
47
 
48
  def decode_prompt(encoded_str):
49
+ chars = []
50
+ for i in range(0, len(encoded_str), 2):
51
+ try:
 
52
  idx = int(encoded_str[i:i+2])
53
  if idx < len(n_chars):
54
  chars.append(n_chars[idx])
55
+ except Exception as e:
56
+ print(f"[WARN] Failed to decode chunk '{encoded_str[i:i+2]}': {e}")
57
+ return "".join(chars)
 
 
58
 
59
  def rgb_to_scratch_number(rgb):
60
+ r, g, b = rgb
61
+ return f"{r:03}{g:03}{b:03}"
 
 
 
 
 
62
 
63
  def generate_image(prompt):
 
64
  try:
65
  seed = random.randint(0, 999999)
66
  params = {
 
76
  resp = requests.get(
77
  "https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen",
78
  params=params,
79
+ timeout=20
80
  )
81
  resp.raise_for_status()
82
  return Image.open(BytesIO(resp.content))
83
  except Exception as e:
84
+ print(f"[ERROR] Image generation failed for prompt '{prompt}': {e}")
85
  traceback.print_exc()
86
  return None
87
 
88
  def resize_and_encode(img):
89
+ img = img.resize((90, 90))
90
+ encoded = ""
91
+ for y in range(90):
92
+ for x in range(90):
93
+ encoded += rgb_to_scratch_number(img.getpixel((x, y)))
94
+ return "10" + encoded
 
 
 
 
 
 
95
 
96
  def split_packets(data, max_length=9998):
97
+ packets = []
98
+ idx = 0
99
+ while idx < len(data):
100
+ chunk = data[idx:idx + max_length]
101
+ packets.append(chunk)
102
+ idx += max_length
103
+ return packets
 
 
 
 
 
 
104
 
105
  # --- メインループ ---
106
  while True:
107
  try:
108
  n1 = get_var("n1")
109
+ if n1 and len(n1) >= 3 and n1[0] == "0":
110
+ if get_var("n0") == "0":
111
  set_var("n0", "1")
112
+ user_id = n1[1:3]
113
  encoded_prompt = n1[3:]
114
  prompt = decode_prompt(encoded_prompt)
115
+
 
116
  img = generate_image(prompt)
117
  if img is None:
 
118
  set_var("n0", "0")
119
+ time.sleep(1)
120
  continue
121
+
122
  scratch_data = resize_and_encode(img)
 
 
123
  packets = split_packets(scratch_data)
124
+
125
  for pkt in packets:
126
+ set_var("n1", pkt)
127
  time.sleep(0.2)
128
+ while get_var("n1") != "11":
129
+ time.sleep(0.1)
130
+
 
 
 
 
 
 
 
 
 
 
131
  set_var("n0", "0")
132
  except Exception as e:
133
+ print(f"[CRITICAL] Main loop error: {e}")
134
  traceback.print_exc()
135
  time.sleep(0.2)