izuemon commited on
Commit
2e2fb83
·
verified ·
1 Parent(s): 42d5a7a

Update turbowarp-server/gpt.py

Browse files
Files changed (1) hide show
  1. turbowarp-server/gpt.py +46 -39
turbowarp-server/gpt.py CHANGED
@@ -20,59 +20,44 @@ slots = [f"n{i}" for i in range(1, 10)]
20
  # ---------------------
21
  # 文字テーブル
22
  # ---------------------
 
23
  chars = []
24
  with open("turbowarp-server/n-chars.txt", encoding="utf8") as f:
25
  for line in f:
26
  chars.append(line.strip())
27
 
28
- # 半角・全角スペースを chars に追加
29
- if " " not in chars: chars.append(" ")
30
- if " " not in chars: chars.append(" ")
31
-
32
- def encode(text, for_history=False):
33
- """
34
- text を数字列に変換
35
- for_history=True の場合は履歴区切り文字 '99' を使う
36
- 改行は送受信用 98
37
- """
38
  out = ""
39
  for c in text:
40
  if c in chars:
41
  i = chars.index(c)
42
  out += f"{i:02d}"
43
- elif c == "\n":
44
- out += "98" # メッセージ内改行
45
- elif for_history and c == "\x1e": # 履歴区切り用の特別文字
46
- out += "99"
47
- else:
48
- # 未登録文字は無視
49
- pass
50
  return out
51
 
52
  def decode(data):
53
- """
54
- 数字列を文字列に戻す
55
- 98 → メッセージ内改行
56
- 99 → 履歴区切りマーカー
57
- """
58
  text = ""
59
  for i in range(0, len(data), 2):
60
  num = int(data[i:i+2])
61
- if num == 98:
62
  text += "\n"
63
- elif num == 99:
64
- text += "__HIST__" # 履歴区切りとして特殊文字
65
  else:
66
  text += chars[num]
67
  return text
68
 
69
  # ---------------------
70
- # TwCloudConnection のラッパー
71
  # ---------------------
 
72
  def get_var(name):
 
 
 
 
73
  try:
 
74
  return tw.get_variable(name=name, name_literal=False)
75
  except Exception:
 
76
  return None
77
 
78
  def set_var(name, value):
@@ -84,6 +69,7 @@ def set_var(name, value):
84
  # ---------------------
85
  # n0管理
86
  # ---------------------
 
87
  def get_used():
88
  v = get_var("n0")
89
  if not v:
@@ -103,8 +89,9 @@ def remove_used(i):
103
  set_var("n0", "".join(u))
104
 
105
  # ---------------------
106
- # ChatGPT API
107
  # ---------------------
 
108
  def ask_gpt(history):
109
  messages = [SYSTEM_PROMPT] + history
110
  r = requests.post(
@@ -122,9 +109,13 @@ def ask_gpt(history):
122
  # ---------------------
123
  # 送信
124
  # ---------------------
 
125
  def send(slot, text):
126
  encoded = encode(text)
 
 
127
  size = 99996
 
128
  packets = [encoded[i:i+size] for i in range(0, len(encoded), size)]
129
  total = len(packets)
130
 
@@ -135,21 +126,28 @@ def send(slot, text):
135
 
136
  while True:
137
  v = get_var(slot)
 
138
  if v and len(v) > 2 and v[2] == "1":
139
  break
140
  if time.time() - start > 10:
 
141
  return
142
  time.sleep(0.1)
143
 
144
  # ---------------------
145
  # メインループ
146
  # ---------------------
 
147
  buffers = {}
148
 
149
  while True:
150
  for i, slot in enumerate(slots, 1):
151
  v = get_var(slot)
152
- if not v or len(v) < 3:
 
 
 
 
153
  continue
154
 
155
  unread = v[2] == "0"
@@ -158,18 +156,25 @@ while True:
158
 
159
  add_used(i)
160
 
 
161
  try:
162
  total = int(v[1])
163
  except Exception:
 
164
  remove_used(i)
165
  continue
166
 
167
  data = v[3:]
168
- newv = v[:2] + "1" + v[3:] # 既読フラグ
169
- set_var(slot, newv)
 
 
 
 
170
 
171
  if slot not in buffers:
172
  buffers[slot] = []
 
173
  buffers[slot].append(data)
174
 
175
  if len(buffers[slot]) < total:
@@ -178,18 +183,20 @@ while True:
178
  joined = "".join(buffers[slot])
179
  decoded = decode(joined)
180
 
181
- # 履歴単位で分割
182
- histories = decoded.split("__HIST__")
183
 
184
- history_for_api = []
185
- for h in histories:
186
- lines = h.split("\n") # 98 が改行としてデコード済み
187
- for line in lines:
188
- if line.strip():
189
- history_for_api.append({"role": "user", "content": line})
 
 
190
 
191
  try:
192
- reply = ask_gpt(history_for_api)
193
  except Exception:
194
  reply = "エラーが発生しました。"
195
 
 
20
  # ---------------------
21
  # 文字テーブル
22
  # ---------------------
23
+
24
  chars = []
25
  with open("turbowarp-server/n-chars.txt", encoding="utf8") as f:
26
  for line in f:
27
  chars.append(line.strip())
28
 
29
+ def encode(text):
 
 
 
 
 
 
 
 
 
30
  out = ""
31
  for c in text:
32
  if c in chars:
33
  i = chars.index(c)
34
  out += f"{i:02d}"
 
 
 
 
 
 
 
35
  return out
36
 
37
  def decode(data):
 
 
 
 
 
38
  text = ""
39
  for i in range(0, len(data), 2):
40
  num = int(data[i:i+2])
41
+ if num == 99:
42
  text += "\n"
 
 
43
  else:
44
  text += chars[num]
45
  return text
46
 
47
  # ---------------------
48
+ # TwCloudConnection の正しいラッパー
49
  # ---------------------
50
+
51
  def get_var(name):
52
+ """
53
+ TwCloudConnection の get_variable はキーワード引数で使う必要があるので
54
+ ここでラップする(戻り値はそのまま)。
55
+ """
56
  try:
57
+ # name_literal を必要に応じて True に切り替えてください
58
  return tw.get_variable(name=name, name_literal=False)
59
  except Exception:
60
+ # 例外は None を返す(呼び出し側でチェック)
61
  return None
62
 
63
  def set_var(name, value):
 
69
  # ---------------------
70
  # n0管理
71
  # ---------------------
72
+
73
  def get_used():
74
  v = get_var("n0")
75
  if not v:
 
89
  set_var("n0", "".join(u))
90
 
91
  # ---------------------
92
+ # API
93
  # ---------------------
94
+
95
  def ask_gpt(history):
96
  messages = [SYSTEM_PROMPT] + history
97
  r = requests.post(
 
109
  # ---------------------
110
  # 送信
111
  # ---------------------
112
+
113
  def send(slot, text):
114
  encoded = encode(text)
115
+
116
+ # TurboWarp 環境なら問題ないとのことなのでそのまま
117
  size = 99996
118
+
119
  packets = [encoded[i:i+size] for i in range(0, len(encoded), size)]
120
  total = len(packets)
121
 
 
126
 
127
  while True:
128
  v = get_var(slot)
129
+ # 値が存在して、長さが期待を満たすか、安全に確認
130
  if v and len(v) > 2 and v[2] == "1":
131
  break
132
  if time.time() - start > 10:
133
+ # タイムアウト
134
  return
135
  time.sleep(0.1)
136
 
137
  # ---------------------
138
  # メインループ
139
  # ---------------------
140
+
141
  buffers = {}
142
 
143
  while True:
144
  for i, slot in enumerate(slots, 1):
145
  v = get_var(slot)
146
+
147
+ if not v:
148
+ continue
149
+
150
+ if len(v) < 3:
151
  continue
152
 
153
  unread = v[2] == "0"
 
156
 
157
  add_used(i)
158
 
159
+ # v のフォーマットは "フラグ(1桁) + total(1桁) + '0' + データ..." の前提
160
  try:
161
  total = int(v[1])
162
  except Exception:
163
+ # 不正データならスキップして使用解除
164
  remove_used(i)
165
  continue
166
 
167
  data = v[3:]
168
+
169
+ # 既読フラグを立てる(インデックス 2 を "1" にする)
170
+ # 文字列操作で安全にセット
171
+ if len(v) >= 3:
172
+ newv = v[:2] + "1" + v[3:]
173
+ set_var(slot, newv)
174
 
175
  if slot not in buffers:
176
  buffers[slot] = []
177
+
178
  buffers[slot].append(data)
179
 
180
  if len(buffers[slot]) < total:
 
183
  joined = "".join(buffers[slot])
184
  decoded = decode(joined)
185
 
186
+ history = []
187
+ parts = decoded.split("\n")
188
 
189
+ for j in range(0, len(parts), 2):
190
+ # parts[j] がユーザーメッセージ、parts[j+1] が(将来の拡張用など)
191
+ if parts[j].strip() == "":
192
+ continue
193
+ history.append({
194
+ "role": "user",
195
+ "content": parts[j]
196
+ })
197
 
198
  try:
199
+ reply = ask_gpt(history)
200
  except Exception:
201
  reply = "エラーが発生しました。"
202