izuemon commited on
Commit
14cf19d
·
verified ·
1 Parent(s): 3cf8956

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +65 -103
turbowarp-server/qr-converter.py CHANGED
@@ -4,145 +4,107 @@ import requests
4
  from PIL import Image
5
  from io import BytesIO
6
  import scratchcommunication
7
- import traceback
8
 
9
- # --- Turbowarpクラウド接続 ---
10
- PROJECT_ID = "1293416663"
11
  tw = scratchcommunication.TwCloudConnection(
12
  project_id=PROJECT_ID,
13
  username="server",
14
- contact_info="contact",
15
- cloud_host="wss://clouddata.turbowarp.org/",
16
- accept_strs=False, # 数値を扱いやすくする
17
- reconnect=True
18
  )
19
 
20
- # Quickaccess有効化(辞書のように扱える)
21
- tw.enable_quickaccess()
 
 
 
 
 
 
 
 
 
22
 
23
  # --- n-chars.txt の読み込み ---
24
- try:
25
- with open("turbowarp-server/n-chars.txt", "r", encoding="utf-8") as f:
26
- n_chars = [line.strip() for line in f]
27
- except Exception as e:
28
- print(f"[FATAL] n-chars.txt 読み込み失敗: {e}")
29
- traceback.print_exc()
30
- n_chars = []
31
 
32
- # --- ユーティリティ関数 ---
33
  def decode_prompt(encoded_str):
 
34
  chars = []
35
  for i in range(0, len(encoded_str), 2):
36
- try:
37
- idx = int(encoded_str[i:i+2])
38
- if idx < len(n_chars):
39
- chars.append(n_chars[idx])
40
- except Exception as e:
41
- print(f"[WARN] decode失敗: {encoded_str[i:i+2]} -> {e}")
42
  return "".join(chars)
43
 
44
  def rgb_to_scratch_number(rgb):
 
45
  r, g, b = rgb
46
  return f"{r:03}{g:03}{b:03}"
47
 
48
  def generate_image(prompt):
49
- try:
50
- seed = random.randint(0, 999999)
51
- params = {
52
- "prompt": prompt,
53
- "negative_prompt": "nsfw, low quality",
54
- "width": 352,
55
- "height": 352,
56
- "num_inference_steps": 2,
57
- "guidance_scale": 0,
58
- "seed": seed,
59
- "randomize_seed": "true"
60
- }
61
- resp = requests.get(
62
- "https://izuemon-pixart-alpha-pixart-sigma-xl-2-1024-ms.hf.space/gen",
63
- params=params,
64
- timeout=20
65
- )
66
- resp.raise_for_status()
67
- return Image.open(BytesIO(resp.content))
68
- except Exception as e:
69
- print(f"[ERROR] 画像生成失敗: '{prompt}' -> {e}")
70
- traceback.print_exc()
71
- return None
72
 
73
  def resize_and_encode(img):
 
74
  img = img.resize((90, 90))
75
  encoded = ""
76
  for y in range(90):
77
  for x in range(90):
78
  encoded += rgb_to_scratch_number(img.getpixel((x, y)))
79
- return "10" + encoded
80
 
81
  def split_packets(data, max_length=9998):
 
82
  packets = []
83
  idx = 0
84
  while idx < len(data):
85
- packets.append(data[idx:idx + max_length])
 
86
  idx += max_length
87
  return packets
88
 
89
  # --- メインループ ---
90
  while True:
91
  try:
92
- # n1 の取得
93
- try:
94
- n1_value = tw["n1"] # 文字列の変数名でアクセス
95
- if isinstance(n1_value, int):
96
- n1_value = str(n1_value) # 数値場合文字列に変換
97
- except KeyError:
98
- n1_value = None
99
- except Exception as e:
100
- print(f"[ERROR] n1取得エラー: {e}")
101
- n1_value = None
102
-
103
- # n0 の取得
104
- try:
105
- n0_value = tw["n0"]
106
- if isinstance(n0_value, int):
107
- n0_value = int(n0_value) # もしくはそのまま整数でOK
108
- except KeyError:
109
- n0_value = None
110
- except Exception as e:
111
- print(f"[ERROR] n0取得エラー: {e}")
112
- n0_value = None
113
-
114
- if n1 and len(n1) >= 3 and n1[0] == "0" and n0 == 0:
115
- tw["n0"] = 1 # 処理中フラグ
116
-
117
- user_id = n1[1:3]
118
- encoded_prompt = n1[3:]
119
- prompt = decode_prompt(encoded_prompt)
120
-
121
- # 画像生成
122
- img = generate_image(prompt)
123
- if img is None:
124
- tw["n0"] = 0
125
- time.sleep(1)
126
- continue
127
-
128
- scratch_data = resize_and_encode(img)
129
- packets = split_packets(scratch_data)
130
-
131
- # パケット送信
132
- for pkt in packets:
133
- tw["n1"] = pkt
134
- time.sleep(0.2)
135
- # 次パケット送信待ち
136
- start = time.time()
137
- while get_var("n1") != "11":
138
- if time.time() - start > 10: # 10秒でタイムアウト
139
- break
140
- time.sleep(0.1)
141
-
142
- # 完了
143
- tw["n0"] = 0
144
-
145
  except Exception as e:
146
- print(f"[CRITICAL] メインループ例外: {e}")
147
- traceback.print_exc()
148
  time.sleep(0.2)
 
4
  from PIL import Image
5
  from io import BytesIO
6
  import scratchcommunication
 
7
 
8
+ # --- Scratchクラウド接続 ---
9
+ PROJECT_ID = "1293030706"
10
  tw = scratchcommunication.TwCloudConnection(
11
  project_id=PROJECT_ID,
12
  username="server",
13
+ contact_info="contact"
 
 
 
14
  )
15
 
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:
84
  try:
85
+ n1 = get_var("n1")
86
+ if n1 and len(n1) >= 3 and n1[0] == "0": # ID受信フラグ
87
+ if get_var("n0") == "0": # 他ユーザー未使用
88
+ set_var("n0", "1")
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)