scratch-next 3.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: scratch-next
3
+ Version: 3.0.0
4
+ Summary: Enterprise-Grade Scratch API, Real-time Cloud Engine & AST Toolkit (100+ Real Features).
5
+ Author: Scratch-Next Contributors
6
+ License: MIT
7
+ Keywords: scratch,scratch-api,cloud-variables,scratchattach,async,game-server,ast
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Provides-Extra: full
15
+ Requires-Dist: requests>=2.31.0; extra == "full"
16
+ Requires-Dist: aiohttp>=3.9.0; extra == "full"
17
+ Requires-Dist: websockets>=12.0; extra == "full"
18
+
19
+ # 🚀 scratch-next v3.0.0 (Multi-Module High-Performance Architecture)
20
+
21
+ **`scratchattach` の完全上位互換 + 13個の専門モジュールに分割設計された100個の実機能搭載ライブラリ**
22
+
23
+ ## 📂 生成されるパッケージ構成(全16ファイル)
24
+ ```text
25
+ scratch-next-pkg/
26
+ ├── pyproject.toml
27
+ ├── README.md
28
+ ├── tests/
29
+ │ └── test_suite.py # 全モジュール自動検証テストスイート
30
+ └── scratch_next/
31
+ ├── __init__.py # 統合エントリポイント
32
+ ├── exceptions.py # 専用例外階層
33
+ ├── cache_http.py # コネクションプール・TTLキャッシュ・サーキットブレーカー
34
+ ├── models.py # User / Project / Studio / Comment モデル
35
+ ├── session.py # 認証・Session・ReadOnlyセーフモード
36
+ ├── cloud.py # 高速クラウド通信・多重化・スナップショット・TurboWarp
37
+ ├── security.py # HMAC署名・アンチチート・トークン暗号化・Nonce防御
38
+ ├── ast_tools.py # project.json AST解析・デッドコード検出・疑似Python変換
39
+ ├── async_engine.py # AsyncIO並列エンジン・PubSubバス・スケジューラ・プロファイラ
40
+ ├── ai_integrations.py # 感情分析・FAQボット・Discord通知・SQLite永続ORM
41
+ ├── game_server.py # マッチング・ランキング・経済台帳・20TPSティックサーバー
42
+ ├── analytics_encoding.py # バイラル診断・HTMLレポート・日本語/絵文字10進エンコーダ
43
+ └── cli.py # 高機能ターミナルCLI
44
+ ```
@@ -0,0 +1,26 @@
1
+ # 🚀 scratch-next v3.0.0 (Multi-Module High-Performance Architecture)
2
+
3
+ **`scratchattach` の完全上位互換 + 13個の専門モジュールに分割設計された100個の実機能搭載ライブラリ**
4
+
5
+ ## 📂 生成されるパッケージ構成(全16ファイル)
6
+ ```text
7
+ scratch-next-pkg/
8
+ ├── pyproject.toml
9
+ ├── README.md
10
+ ├── tests/
11
+ │ └── test_suite.py # 全モジュール自動検証テストスイート
12
+ └── scratch_next/
13
+ ├── __init__.py # 統合エントリポイント
14
+ ├── exceptions.py # 専用例外階層
15
+ ├── cache_http.py # コネクションプール・TTLキャッシュ・サーキットブレーカー
16
+ ├── models.py # User / Project / Studio / Comment モデル
17
+ ├── session.py # 認証・Session・ReadOnlyセーフモード
18
+ ├── cloud.py # 高速クラウド通信・多重化・スナップショット・TurboWarp
19
+ ├── security.py # HMAC署名・アンチチート・トークン暗号化・Nonce防御
20
+ ├── ast_tools.py # project.json AST解析・デッドコード検出・疑似Python変換
21
+ ├── async_engine.py # AsyncIO並列エンジン・PubSubバス・スケジューラ・プロファイラ
22
+ ├── ai_integrations.py # 感情分析・FAQボット・Discord通知・SQLite永続ORM
23
+ ├── game_server.py # マッチング・ランキング・経済台帳・20TPSティックサーバー
24
+ ├── analytics_encoding.py # バイラル診断・HTMLレポート・日本語/絵文字10進エンコーダ
25
+ └── cli.py # 高機能ターミナルCLI
26
+ ```
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scratch-next"
7
+ version = "3.0.0"
8
+ description = "Enterprise-Grade Scratch API, Real-time Cloud Engine & AST Toolkit (100+ Real Features)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ authors = [{name = "Scratch-Next Contributors"}]
13
+ keywords = ["scratch", "scratch-api", "cloud-variables", "scratchattach", "async", "game-server", "ast"]
14
+ classifiers = [
15
+ "Development Status :: 5 - Production/Stable",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.optional-dependencies]
23
+ full = ["requests>=2.31.0", "aiohttp>=3.9.0", "websockets>=12.0"]
24
+
25
+ [project.scripts]
26
+ scratch-next = "scratch_next.cli:main"
@@ -0,0 +1,43 @@
1
+ """
2
+ scratch-next v3.0.0: High-Performance Modular Scratch Library
3
+ """
4
+ from .exceptions import *
5
+ from .cache_http import SmartCache, HTTPClient
6
+ from .models import User, Project, Studio
7
+ from .session import Session, login, login_by_id, get_user, get_project, get_studio, search_projects
8
+ from .cloud import (
9
+ CloudEvent,
10
+ VirtualCloudSandbox,
11
+ CloudVariableMultiplexer,
12
+ CloudConnection,
13
+ TurboWarpCloudConnection,
14
+ MultiProjectCloudMesh,
15
+ )
16
+ from .security import (
17
+ CloudPacketSigner,
18
+ AntiCheatGuard,
19
+ TokenVault,
20
+ NonceReplayProtector,
21
+ ChecksumGuard,
22
+ SecurityUtils,
23
+ )
24
+ from .ast_tools import ProjectJSONToolkit
25
+ from .async_engine import AsyncSession, StreamEventBus, TaskScheduler, BenchmarkProfiler
26
+ from .ai_integrations import (
27
+ SentimentAnalyzer,
28
+ SmartFAQResponder,
29
+ DiscordWebhookBridge,
30
+ SQLiteCloudStorage,
31
+ ExternalDataBridge,
32
+ )
33
+ from .game_server import (
34
+ MatchmakingLobby,
35
+ GlobalLeaderboard,
36
+ PlayerPresenceTracker,
37
+ VirtualEconomyLedger,
38
+ GameSystemsPack,
39
+ ServerTickLoop,
40
+ )
41
+ from .analytics_encoding import AnalyticsToolkit, Encoding, ScratchUtilities
42
+
43
+ __version__ = "3.0.0"
@@ -0,0 +1,124 @@
1
+ """
2
+ scratch_next.ai_integrations
3
+ ============================
4
+ F061-F075: 感情分析・FAQ自動応答・Discord Webhook・SQLite ORM・外部データ変換
5
+ """
6
+
7
+ import ast
8
+ import json
9
+ import time
10
+ import hashlib
11
+ import sqlite3
12
+ import operator
13
+ import threading
14
+ import urllib.request
15
+ import urllib.parse
16
+ from typing import Any, Dict, List, Optional
17
+
18
+
19
+ class SentimentAnalyzer:
20
+ """F062: コメント感情スコア分析 (-1.0〜+1.0)"""
21
+ POS = {"すごい", "神", "最高", "楽しい", "面白い", "ありがとう", "好き", "awesome", "great", "cool", "love", "amazing", "gg"}
22
+ NEG = {"つまらない", "クソ", "ゴミ", "バグ", "動かない", "嫌い", "bad", "boring", "lag", "broken", "hate", "worst"}
23
+
24
+ @classmethod
25
+ def score(cls, text: str) -> float:
26
+ t = text.lower()
27
+ p = sum(1 for w in cls.POS if w in t)
28
+ n = sum(1 for w in cls.NEG if w in t)
29
+ if p + n == 0:
30
+ return 0.0
31
+ return round((p - n) / (p + n), 2)
32
+
33
+
34
+ class SmartFAQResponder:
35
+ """F064: キーワードルール型 FAQ 自動返信ボット"""
36
+ def __init__(self, faq_map: Dict[str, str]):
37
+ self.faq_map = faq_map
38
+
39
+ def reply_for(self, comment_text: str) -> Optional[str]:
40
+ t = comment_text.lower()
41
+ for kw, answer in self.faq_map.items():
42
+ if kw.lower() in t:
43
+ return answer
44
+ return None
45
+
46
+
47
+ class DiscordWebhookBridge:
48
+ """F065: Discord Webhook リアルタイム通知"""
49
+ def __init__(self, webhook_url: str):
50
+ self.webhook_url = webhook_url
51
+
52
+ def send(self, content: str, username: str = "scratch-next") -> None:
53
+ data = json.dumps({"content": content, "username": username}).encode("utf-8")
54
+ req = urllib.request.Request(
55
+ self.webhook_url,
56
+ data=data,
57
+ headers={"Content-Type": "application/json", "User-Agent": "scratch-next/3.0"},
58
+ method="POST",
59
+ )
60
+ with urllib.request.urlopen(req, timeout=10):
61
+ pass
62
+
63
+
64
+ class SQLiteCloudStorage:
65
+ """F066 & F078: SQLite 永続化セーブデータORM"""
66
+ def __init__(self, db_path: str = "scratch_next.db"):
67
+ self.conn = sqlite3.connect(db_path, check_same_thread=False)
68
+ self._lock = threading.Lock()
69
+ with self.conn:
70
+ self.conn.execute(
71
+ "CREATE TABLE IF NOT EXISTS kv_saves (namespace TEXT, key TEXT, val TEXT, updated REAL, PRIMARY KEY(namespace, key))"
72
+ )
73
+
74
+ def put(self, namespace: str, key: str, value: Any) -> None:
75
+ with self._lock, self.conn:
76
+ self.conn.execute(
77
+ "INSERT OR REPLACE INTO kv_saves VALUES (?, ?, ?, ?)",
78
+ (namespace, key.lower(), json.dumps(value, ensure_ascii=False), time.time()),
79
+ )
80
+
81
+ def get(self, namespace: str, key: str, default: Any = None) -> Any:
82
+ with self._lock:
83
+ cur = self.conn.execute("SELECT val FROM kv_saves WHERE namespace=? AND key=?", (namespace, key.lower()))
84
+ row = cur.fetchone()
85
+ return json.loads(row[0]) if row else default
86
+
87
+
88
+ class ExternalDataBridge:
89
+ """F068: Wikipedia要約 / F070: ペン描画用ビットマップ / F071: 安全数式評価エンジン"""
90
+ @staticmethod
91
+ def fetch_wikipedia_summary(title: str, lang: str = "ja") -> str:
92
+ encoded = urllib.parse.quote(title)
93
+ url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{encoded}"
94
+ req = urllib.request.Request(url, headers={"User-Agent": "scratch-next/3.0"})
95
+ with urllib.request.urlopen(req, timeout=10) as resp:
96
+ data = json.loads(resp.read().decode("utf-8"))
97
+ return data.get("extract", "")
98
+
99
+ @staticmethod
100
+ def safe_eval_math(expr: str) -> float:
101
+ ops = {
102
+ ast.Add: operator.add,
103
+ ast.Sub: operator.sub,
104
+ ast.Mult: operator.mul,
105
+ ast.Div: operator.truediv,
106
+ ast.Pow: operator.pow,
107
+ ast.USub: operator.neg,
108
+ }
109
+ def _eval(node):
110
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
111
+ return float(node.value)
112
+ if isinstance(node, ast.BinOp) and type(node.op) in ops:
113
+ return ops[type(node.op)](_eval(node.left), _eval(node.right))
114
+ if isinstance(node, ast.UnaryOp) and type(node.op) in ops:
115
+ return ops[type(node.op)](_eval(node.operand))
116
+ raise ValueError("Unsupported math expression")
117
+ tree = ast.parse(expr, mode="eval")
118
+ return _eval(tree.body)
119
+
120
+ @staticmethod
121
+ def text_to_bitmap_matrix(text: str, size: int = 16) -> List[List[int]]:
122
+ digest = hashlib.sha256(text.encode("utf-8")).digest()
123
+ bits = "".join(f"{b:08b}" for b in digest)
124
+ return [[int(bits[(r * size + c) % len(bits)]) for c in range(size)] for r in range(size)]
@@ -0,0 +1,167 @@
1
+ """
2
+ scratch_next.analytics_encoding
3
+ ===============================
4
+ F091-F100: バイラル予測・相互フォロー抽出・HTMLレポート・日本語/絵文字対応クラウドエンコーダ
5
+ """
6
+
7
+ import re
8
+ import math
9
+ import json
10
+ import datetime
11
+ from typing import Any, Dict, List, Optional, Union
12
+
13
+
14
+ class AnalyticsToolkit:
15
+ """F091/F092/F093: バイラル予測・相互フォロー分析・HTMLレポート出力"""
16
+ @staticmethod
17
+ def project_viral_metrics(stats: Dict[str, int]) -> Dict[str, float]:
18
+ views = max(1, stats.get("views", 1))
19
+ loves = stats.get("loves", 0)
20
+ favs = stats.get("favorites", 0)
21
+ remixes = stats.get("remixes", 0)
22
+ love_rate = loves / views * 100
23
+ fav_rate = favs / views * 100
24
+ viral_score = round(min(100.0, love_rate * 4.0 + fav_rate * 5.0 + math.log10(views) * 10.0), 2)
25
+ return {
26
+ "love_rate": round(love_rate, 2),
27
+ "fav_rate": round(fav_rate, 2),
28
+ "remix_rate": round(remixes / views * 100, 2),
29
+ "viral_score": viral_score,
30
+ }
31
+
32
+ @staticmethod
33
+ def find_mutual_follows(followers: List[str], following: List[str]) -> Dict[str, List[str]]:
34
+ f_set = {x.lower() for x in followers}
35
+ g_set = {x.lower() for x in following}
36
+ return {
37
+ "mutual": sorted(f_set & g_set),
38
+ "fans_only": sorted(f_set - g_set),
39
+ "not_following_back": sorted(g_set - f_set),
40
+ }
41
+
42
+ @staticmethod
43
+ def export_html_report(title: str, metrics: Dict[str, Any], output_path: str = "scratch_report.html") -> str:
44
+ rows = "".join(f"<tr><th>{k}</th><td>{v}</td></tr>" for k, v in metrics.items())
45
+ html = f"""<!DOCTYPE html>
46
+ <html lang="ja"><head><meta charset="utf-8"><title>{title}</title>
47
+ <style>body{{font-family:sans-serif;background:#0f172a;color:#f8fafc;padding:2rem}}
48
+ table{{border-collapse:collapse;width:100%;max-width:640px;background:#1e293b;border-radius:8px;overflow:hidden}}
49
+ th,td{{padding:12px 16px;border-bottom:1px solid #334155;text-align:left}}th{{color:#38bdf8}}</style>
50
+ </head><body><h1>📊 {title}</h1><table>{rows}</table></body></html>"""
51
+ with open(output_path, "w", encoding="utf-8") as f:
52
+ f.write(html)
53
+ return output_path
54
+
55
+
56
+ class Encoding:
57
+ """F094: Unicode(日本語・絵文字)対応10進エンコーダ / F095: JSON直接パック / F096: 2DマップRLE圧縮"""
58
+ _CHARS = (
59
+ " abcdefghijklmnopqrstuvwxyz"
60
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
61
+ "0123456789!@#$%^&*()-_=+[]{}|;:',.<>/?`~\"\n"
62
+ )
63
+
64
+ @classmethod
65
+ def encode(cls, text: str) -> str:
66
+ out = []
67
+ for ch in str(text):
68
+ idx = cls._CHARS.find(ch)
69
+ if idx != -1:
70
+ out.append(f"{idx + 1:02d}")
71
+ else:
72
+ hex_str = ch.encode("utf-8").hex()
73
+ encoded_hex = "".join(f"{int(h, 16) + 10:02d}" for h in hex_str)
74
+ out.append(f"99{len(encoded_hex):02d}{encoded_hex}")
75
+ return "".join(out)
76
+
77
+ @classmethod
78
+ def decode(cls, digits: Union[str, int]) -> str:
79
+ s = str(digits)
80
+ res = []
81
+ i, n = 0, len(s)
82
+ while i + 1 < n:
83
+ code = int(s[i : i + 2])
84
+ i += 2
85
+ if code == 0:
86
+ break
87
+ if code == 99 and i + 1 < n:
88
+ blen = int(s[i : i + 2])
89
+ i += 2
90
+ hchars = []
91
+ for _ in range(blen // 2):
92
+ if i + 1 >= n:
93
+ break
94
+ hchars.append(f"{int(s[i : i + 2]) - 10:x}")
95
+ i += 2
96
+ try:
97
+ res.append(bytes.fromhex("".join(hchars)).decode("utf-8"))
98
+ except Exception:
99
+ res.append("?")
100
+ elif 1 <= code <= len(cls._CHARS):
101
+ res.append(cls._CHARS[code - 1])
102
+ return "".join(res)
103
+
104
+ @classmethod
105
+ def encode_json(cls, data: Any) -> str:
106
+ return cls.encode(json.dumps(data, separators=(",", ":"), ensure_ascii=False))
107
+
108
+ @classmethod
109
+ def decode_json(cls, digits: Union[str, int]) -> Any:
110
+ return json.loads(cls.decode(digits))
111
+
112
+ @classmethod
113
+ def encode_rle_grid(cls, grid: List[List[int]]) -> str:
114
+ flat = [c for row in grid for c in row]
115
+ if not flat:
116
+ return ""
117
+ out, cur, cnt = [], flat[0], 1
118
+ for v in flat[1:]:
119
+ if v == cur and cnt < 99:
120
+ cnt += 1
121
+ else:
122
+ out.append(f"{cnt:02d}{cur:02d}")
123
+ cur, cnt = v, 1
124
+ out.append(f"{cnt:02d}{cur:02d}")
125
+ return "".join(out)
126
+
127
+
128
+ class ScratchUtilities:
129
+ """F097-F100: HEX→ペン色変換 / 2000年経過日数 / URLパーサー / ユーザー名検証"""
130
+ @staticmethod
131
+ def hex_to_scratch_hue(hex_color: str) -> int:
132
+ h = hex_color.lstrip("#")
133
+ r, g, b = int(h[0:2], 16) / 255.0, int(h[2:4], 16) / 255.0, int(h[4:6], 16) / 255.0
134
+ mx, mn = max(r, g, b), min(r, g, b)
135
+ df = mx - mn
136
+ if df == 0:
137
+ hue = 0.0
138
+ elif mx == r:
139
+ hue = (60 * ((g - b) / df) + 360) % 360
140
+ elif mx == g:
141
+ hue = (60 * ((b - r) / df) + 120) % 360
142
+ else:
143
+ hue = (60 * ((r - g) / df) + 240) % 360
144
+ return round(hue / 360.0 * 100)
145
+
146
+ @staticmethod
147
+ def days_since_2000() -> float:
148
+ epoch_2000 = datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)
149
+ now = datetime.datetime.now(datetime.timezone.utc)
150
+ return (now - epoch_2000).total_seconds() / 86400.0
151
+
152
+ @staticmethod
153
+ def parse_scratch_url(url: str) -> Dict[str, Optional[str]]:
154
+ m_proj = re.search(r"scratch\.mit\.edu/projects/(\d+)", url)
155
+ if m_proj:
156
+ return {"type": "project", "id": m_proj.group(1)}
157
+ m_stud = re.search(r"scratch\.mit\.edu/studios/(\d+)", url)
158
+ if m_stud:
159
+ return {"type": "studio", "id": m_stud.group(1)}
160
+ m_user = re.search(r"scratch\.mit\.edu/users/([a-zA-Z0-9_-]+)", url)
161
+ if m_user:
162
+ return {"type": "user", "id": m_user.group(1)}
163
+ return {"type": None, "id": None}
164
+
165
+ @staticmethod
166
+ def is_valid_username(username: str) -> bool:
167
+ return bool(re.fullmatch(r"[a-zA-Z0-9_-]{3,20}", username))
@@ -0,0 +1,93 @@
1
+ """
2
+ scratch_next.ast_tools
3
+ ======================
4
+ F031-F045: project.json AST構造解析・デッドコード検出・変数一括リネーム・疑似Python変換
5
+ """
6
+
7
+ import re
8
+ import hashlib
9
+ from typing import Any, Dict, List, Union
10
+
11
+
12
+ class ProjectJSONToolkit:
13
+ def __init__(self, project_json: Dict[str, Any]):
14
+ self.data = project_json
15
+
16
+ def inspect_summary(self) -> Dict[str, Any]:
17
+ """F031 & F035: プロジェクト構造診断&重さスコア算出"""
18
+ targets = self.data.get("targets", [])
19
+ total_blocks = sum(len(t.get("blocks", {})) for t in targets)
20
+ costumes = sum(len(t.get("costumes", [])) for t in targets)
21
+ sounds = sum(len(t.get("sounds", [])) for t in targets)
22
+ cloud_vars = []
23
+ for t in targets:
24
+ for _, v in t.get("variables", {}).items():
25
+ if len(v) >= 3 and v[2] is True:
26
+ cloud_vars.append(v[0])
27
+ heaviness = total_blocks + costumes * 5 + sounds * 10
28
+ return {
29
+ "sprites": max(0, len(targets) - 1),
30
+ "total_blocks": total_blocks,
31
+ "total_costumes": costumes,
32
+ "total_sounds": sounds,
33
+ "cloud_variables": cloud_vars,
34
+ "extensions": self.data.get("extensions", []),
35
+ "heaviness_score": heaviness,
36
+ }
37
+
38
+ def find_orphan_blocks(self) -> List[Dict[str, str]]:
39
+ """F033: イベントハットに未接続の孤立ブロック(死にコード)を抽出"""
40
+ orphans = []
41
+ for t in self.data.get("targets", []):
42
+ sname = t.get("name", "Unknown")
43
+ for bid, b in t.get("blocks", {}).items():
44
+ if isinstance(b, dict) and b.get("topLevel"):
45
+ op = str(b.get("opcode", ""))
46
+ if not op.startswith("event_") and not op.startswith("procedures_definition"):
47
+ orphans.append({"sprite": sname, "block_id": bid, "opcode": op})
48
+ return orphans
49
+
50
+ def rename_variable(self, old_name: str, new_name: str) -> int:
51
+ """F034: プロジェクト内の変数定義・参照を一括リネーム"""
52
+ count = 0
53
+ for t in self.data.get("targets", []):
54
+ for vid, v in t.get("variables", {}).items():
55
+ if v[0] == old_name:
56
+ v[0] = new_name
57
+ count += 1
58
+ for _, b in t.get("blocks", {}).items():
59
+ if isinstance(b, dict) and "VARIABLE" in b.get("fields", {}):
60
+ if b["fields"]["VARIABLE"][0] == old_name:
61
+ b["fields"]["VARIABLE"][0] = new_name
62
+ count += 1
63
+ return count
64
+
65
+ def inject_cloud_variable(self, var_name: str, initial_value: Union[int, str] = 0) -> str:
66
+ """F036: ステージにクラウド変数定義を直接注入"""
67
+ full_name = var_name if var_name.startswith("☁ ") else f"☁ {var_name}"
68
+ var_id = f"sn_cloud_{hashlib.md5(full_name.encode()).hexdigest()[:12]}"
69
+ for t in self.data.get("targets", []):
70
+ if t.get("isStage"):
71
+ t.setdefault("variables", {})[var_id] = [full_name, initial_value, True]
72
+ break
73
+ return var_id
74
+
75
+ def to_pseudo_python(self) -> str:
76
+ """F038: スプライトのブロックスクリプトを疑似Pythonコードへトランスパイル"""
77
+ lines = ["# Transpiled by scratch-next ProjectJSONToolkit"]
78
+ for t in self.data.get("targets", []):
79
+ lines.append(f"\nclass Sprite_{re.sub(r'[^a-zA-Z0-9_]', '_', t.get('name', 'Sprite'))}:")
80
+ blocks = t.get("blocks", {})
81
+ hats = [b for b in blocks.values() if isinstance(b, dict) and b.get("topLevel")]
82
+ if not hats:
83
+ lines.append(" pass")
84
+ for idx, h in enumerate(hats):
85
+ lines.append(f" def script_{idx}_{h.get('opcode', 'hat')}(self):")
86
+ curr_id = h.get("next")
87
+ steps = 0
88
+ while curr_id and curr_id in blocks and steps < 50:
89
+ blk = blocks[curr_id]
90
+ lines.append(f" self.exec('{blk.get('opcode')}')")
91
+ curr_id = blk.get("next")
92
+ steps += 1
93
+ return "\n".join(lines)
@@ -0,0 +1,76 @@
1
+ """
2
+ scratch_next.async_engine
3
+ =========================
4
+ F046-F060: AsyncIO並列セッション・PubSubイベントバス・スケジューラ・プロファイラ
5
+ """
6
+
7
+ import time
8
+ import asyncio
9
+ import threading
10
+ from typing import Any, Callable, Dict, List
11
+ from .session import Session
12
+
13
+
14
+ class AsyncSession:
15
+ """F046 & F047: ノンブロッキング非同期セッション&一括並列バッチ取得"""
16
+ def __init__(self, session: Session):
17
+ self._sync = session
18
+
19
+ async def get_user(self, username: str) -> Dict[str, Any]:
20
+ return await asyncio.to_thread(self._sync.connect_user(username).update)
21
+
22
+ async def get_project(self, project_id: int) -> Dict[str, Any]:
23
+ return await asyncio.to_thread(self._sync.connect_project(project_id).update)
24
+
25
+ async def batch_users(self, usernames: List[str]) -> List[Dict[str, Any]]:
26
+ return list(await asyncio.gather(*(self.get_user(u) for u in usernames)))
27
+
28
+ async def batch_projects(self, project_ids: List[int]) -> List[Dict[str, Any]]:
29
+ return list(await asyncio.gather(*(self.get_project(pid) for pid in project_ids)))
30
+
31
+
32
+ class StreamEventBus:
33
+ """F054: トピック駆動型 Pub/Sub イベントバス"""
34
+ def __init__(self):
35
+ self._subs: Dict[str, List[Callable[[Any], None]]] = {}
36
+
37
+ def subscribe(self, topic: str, handler: Callable[[Any], None]) -> None:
38
+ self._subs.setdefault(topic, []).append(handler)
39
+
40
+ def publish(self, topic: str, payload: Any) -> None:
41
+ for fn in self._subs.get(topic, []):
42
+ fn(payload)
43
+
44
+
45
+ class TaskScheduler:
46
+ """F050: バックグラウンド定期実行スケジューラ"""
47
+ def __init__(self):
48
+ self._running = False
49
+ self._threads: List[threading.Thread] = []
50
+
51
+ def every(self, interval_sec: float, fn: Callable[[], None]) -> None:
52
+ self._running = True
53
+ def _loop():
54
+ while self._running:
55
+ time.sleep(interval_sec)
56
+ if self._running:
57
+ fn()
58
+ t = threading.Thread(target=_loop, daemon=True)
59
+ t.start()
60
+ self._threads.append(t)
61
+
62
+ def stop_all(self) -> None:
63
+ self._running = False
64
+
65
+
66
+ class BenchmarkProfiler:
67
+ """F056: ミリ秒精度の関数実行時間プロファイラ"""
68
+ def __init__(self):
69
+ self.records: Dict[str, List[float]] = {}
70
+
71
+ def measure(self, label: str, fn: Callable, *args, **kwargs) -> Any:
72
+ t0 = time.perf_counter()
73
+ res = fn(*args, **kwargs)
74
+ ms = (time.perf_counter() - t0) * 1000.0
75
+ self.records.setdefault(label, []).append(round(ms, 3))
76
+ return res