izuemon commited on
Commit
8e6d125
·
verified ·
1 Parent(s): cf53b0c

Update turbowarp-server/qr-converter.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/qr-converter.py +96 -78
turbowarp-server/qr-converter.py CHANGED
@@ -1,92 +1,110 @@
1
  import time
 
2
  import requests
 
 
3
  import scratchcommunication
4
 
 
5
  PROJECT_ID = 1293030706
6
-
7
- # Scratchクラウド接続
8
  tw = scratchcommunication.TwCloudConnection(
9
  project_id=PROJECT_ID,
10
  username="server",
11
- contact_info="contact",
12
- reconnect=True,
13
- receive_from_websocket=True,
14
- accept_strs=True # 文字列も取得可能
15
  )
16
 
17
- # short_id を a-z0-9 → 00~35 に変換
18
- def encode_short_id(short_id):
19
- chars = "abcdefghijklmnopqrstuvwxyz0123456789"
20
- result = ""
21
- for c in short_id.lower(): # 念のため小文字化
22
- if c in chars:
23
- result += f"{chars.index(c):02d}"
24
- else:
25
- result += "00" # 不明文字は00
26
- return result
27
-
28
- last_n1 = None
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  while True:
31
  try:
32
- # クラウド変数 n1 の取得
33
- n1 = tw.get_variable(name="n1", name_literal=False)
34
- if n1 is None:
35
- time.sleep(0.2)
36
- continue
37
- n1 = str(n1).strip()
38
-
39
- if n1 != last_n1:
40
- last_n1 = n1
41
-
42
- if len(n1) < 3:
43
- continue # 3桁以上ない場合はスキップ
44
-
45
- mode = n1[0] # 0: 受信/送信待ち, 1: レスポンス返却
46
- read_flag = n1[1] # 0: 未読, 1: 既読
47
- content = n1[2:] # 3桁目以降 = ID
48
-
49
- # -----------------------------
50
- # Scratch サーバー
51
- # -----------------------------
52
- if mode == "0" and read_flag == "0":
53
- # 使用中フラグ
54
- tw.set_variable(name="n0", value=1)
55
- print("受信ID:", content)
56
-
57
- # 既読に変更
58
- tw.set_variable(name="n1", value="0" + "1" + content)
59
-
60
- # APIアクセス
61
- url = f"https://20.rf.gd/set.php?project_id={content}"
62
- try:
63
- res = requests.get(url, cookies={"__test": "872039d283902860e895efb6018d2632"}, timeout=5)
64
- res.raise_for_status()
65
- data = res.json()
66
- short_id = data.get("short_id", "000")
67
- except requests.exceptions.RequestException as e:
68
- print("API接続エラー:", e)
69
- short_id = "000"
70
- except ValueError:
71
- print("API JSON解析エラー")
72
- short_id = "000"
73
-
74
- print("short_id:", short_id)
75
-
76
- encoded = encode_short_id(short_id)
77
-
78
- # サーバー → Scratch にレスポンス書き込み
79
- tw.set_variable(name="n1", value="1" + "0" + encoded)
80
-
81
- # -----------------------------
82
- # Scratch が既読にしたら n0 を解放
83
- # -----------------------------
84
- elif mode == "1" and read_flag == "1":
85
- tw.set_variable(name="n0", value=0)
86
- print("通信完了。n0を0に戻しました。")
87
-
88
- time.sleep(0.2)
89
-
90
  except Exception as e:
91
- print("エラー:", e)
92
- time.sleep(1)
 
1
  import time
2
+ import random
3
  import requests
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("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)