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

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +98 -46
turbowarp-server/qr-converter.py CHANGED
@@ -4,6 +4,7 @@ import requests
4
  from PIL import Image
5
  from io import BytesIO
6
  import scratchcommunication
 
7
 
8
  # --- Scratchクラウド接続 ---
9
  PROJECT_ID = 1293416663
@@ -16,68 +17,105 @@ tw = scratchcommunication.TwCloudConnection(
16
  def get_var(name):
17
  try:
18
  return tw.get_variable(name=name, name_literal=False)
19
- except Exception:
 
 
20
  return None
21
 
22
  def set_var(name, value):
23
  try:
24
  return tw.set_variable(name=name, value=value, name_literal=False)
25
- except Exception:
 
 
26
  return None
27
 
28
  # --- n-chars.txt の読み込み ---
29
- with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
30
- n_chars = [line.strip() for line in f]
 
 
 
 
 
31
 
32
  def decode_prompt(encoded_str):
33
  """クラウド変数の数字列を元にプロンプト文字列に復号"""
34
- chars = []
35
- for i in range(0, len(encoded_str), 2):
36
- idx = int(encoded_str[i:i+2])
37
- if idx < len(n_chars):
38
- chars.append(n_chars[idx])
39
- return "".join(chars)
 
 
 
 
 
40
 
41
  def rgb_to_scratch_number(rgb):
42
- """RGBを0-999999の10進数に変換"""
43
- r, g, b = rgb
44
- return f"{r:03}{g:03}{b:03}"
 
 
 
 
45
 
46
  def generate_image(prompt):
47
  """APIから352x352の画像生成"""
48
- seed = random.randint(0, 999999)
49
- params = {
50
- "prompt": prompt,
51
- "negative_prompt": "nsfw, low quality",
52
- "width": 352,
53
- "height": 352,
54
- "num_inference_steps": 2,
55
- "guidance_scale": 0,
56
- "seed": seed,
57
- "randomize_seed": "true"
58
- }
59
- resp = requests.get("https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen", params=params)
60
- resp.raise_for_status()
61
- return Image.open(BytesIO(resp.content))
 
 
 
 
 
 
 
 
 
62
 
63
  def resize_and_encode(img):
64
  """90x90にリサイズして数字列に変換"""
65
- img = img.resize((90, 90))
66
- encoded = ""
67
- for y in range(90):
68
- for x in range(90):
69
- encoded += rgb_to_scratch_number(img.getpixel((x, y)))
70
- return "10" + encoded # 先頭に "10"
 
 
 
 
 
71
 
72
  def split_packets(data, max_length=9998):
73
  """10000文字制限に合わせて分割(先頭 '10' 含む)"""
74
- packets = []
75
- idx = 0
76
- while idx < len(data):
77
- chunk = data[idx:idx + max_length]
78
- packets.append(chunk)
79
- idx += max_length
80
- return packets
 
 
 
 
 
81
 
82
  # --- メインループ ---
83
  while True:
@@ -89,22 +127,36 @@ while True:
89
  user_id = n1[1:3] # 実際のIDはここを調整
90
  encoded_prompt = n1[3:]
91
  prompt = decode_prompt(encoded_prompt)
92
-
93
  # 画像生成
94
  img = generate_image(prompt)
 
 
 
 
 
95
  scratch_data = resize_and_encode(img)
96
-
97
  # パケット分割
98
  packets = split_packets(scratch_data)
99
  for pkt in packets:
100
  set_var("n1", pkt) # 送信
101
  time.sleep(0.2)
102
  # 次パケット送信待ち
103
- while get_var("n1") != "11":
104
- time.sleep(0.1)
105
-
 
 
 
 
 
 
 
 
106
  # 完了後リセット
107
  set_var("n0", "0")
108
  except Exception as e:
109
- print("Error:", e)
 
110
  time.sleep(0.2)
 
4
  from PIL import Image
5
  from io import BytesIO
6
  import scratchcommunication
7
+ import traceback
8
 
9
  # --- Scratchクラウド接続 ---
10
  PROJECT_ID = 1293416663
 
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
 
25
  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
 
33
  # --- n-chars.txt の読み込み ---
34
+ 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 = {
70
+ "prompt": prompt,
71
+ "negative_prompt": "nsfw, low quality",
72
+ "width": 352,
73
+ "height": 352,
74
+ "num_inference_steps": 2,
75
+ "guidance_scale": 0,
76
+ "seed": seed,
77
+ "randomize_seed": "true"
78
+ }
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:
 
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)