-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1950 lines (1795 loc) · 72.8 KB
/
main.py
File metadata and controls
1950 lines (1795 loc) · 72.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import base64
import hashlib
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from http.cookies import SimpleCookie
from pathlib import Path
from typing import Any, Callable, Optional
from urllib.parse import urlparse
CHAT_URL = "https://chatgpt.com/"
CHAT_REQUIREMENTS_URL = "https://chatgpt.com/backend-api/sentinel/chat-requirements"
CHAT_BACKEND_URL = "https://chatgpt.com/backend-api/f/conversation"
CHAT_FILES_URL = "https://chatgpt.com/backend-api/files"
DEFAULT_AUTH_FILE = Path("auth_data.json")
APP_STATE_FILE = Path("webchat_state.json")
LEGACY_CLI_STATE_FILE = Path("cli_state.json")
LEGACY_CHATS_STATE_FILE = Path("g4f_chats.json")
DEFAULT_MODEL = "gpt-4o-mini"
DEFAULT_TIMEOUT_SECONDS = 90
PREFETCH_TTL_SECONDS = 20.0
SUPPORTED_MODELS = [
"gpt-5-2",
"gpt-5-2-instant",
"gpt-5-2-thinking",
"gpt-5-1",
"gpt-5-1-instant",
"gpt-5-1-thinking",
"gpt-5",
"gpt-5-instant",
"gpt-5-thinking",
"gpt-4",
"gpt-4.1",
"gpt-4.1-mini",
"gpt-4.5",
"gpt-4o",
"gpt-4o-mini",
"o1",
"o1-mini",
"o3-mini",
"o3-mini-high",
"o4-mini",
"o4-mini-high",
]
MODEL_ALIASES = {
"gpt-5.1": "gpt-5-1",
"gpt-4.1": "gpt-4.1",
"gpt-4.1-mini": "gpt-4.1-mini",
"gpt-4.5": "gpt-4.5",
}
DEFAULT_RUNTIME_STATE = {
"model": DEFAULT_MODEL,
"language": "en",
"web_search": False,
"reasoning_effort": None,
"show_metrics": True,
}
UPLOAD_HEADERS = {
"accept": "application/json, text/plain, */*",
"accept-language": "en-US,en;q=0.8",
"priority": "u=1, i",
"referer": CHAT_URL,
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
}
FILE_CACHE: dict[str, dict[str, Any]] = {}
WARNED_JSON_READ_ERRORS: set[str] = set()
class UiColors:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
GRAY = "\033[90m"
def supports_color() -> bool:
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("TERM", "").lower() == "dumb":
return False
return sys.stdout.isatty()
USE_COLOR = supports_color()
def paint(text: str, color: str = "", bold: bool = False, dim: bool = False) -> str:
if not USE_COLOR:
return text
prefix = ""
if bold:
prefix += UiColors.BOLD
if dim:
prefix += UiColors.DIM
if color:
prefix += color
return f"{prefix}{text}{UiColors.RESET}"
def info(text: str) -> None:
print(paint(text, UiColors.BLUE))
def success(text: str) -> None:
print(paint(text, UiColors.GREEN))
def warning(text: str) -> None:
print(paint(text, UiColors.YELLOW))
def error(text: str) -> None:
print(paint(text, UiColors.RED, bold=True))
TRANSLATIONS = {
"en": {
"assistant_prefix": "assistant> ",
"warmup": "Warmup...",
"warmup_ok": "ok",
"warmup_skip": "skip",
"startup_error": "Startup error: {error_type}: {error}",
"mini_cli": "Mini ChatGPT CLI. Type /help",
"auth_source": "Auth source: {auth_source}",
"no_active_chat": "No active chat selected",
"new_chat_title": "New chat",
"active_chat": "Active: {chat_id} [{mode}] {title} (conversation_id: {conversation_id})",
"temporary_mode": "temporary",
"persistent_mode": "persistent",
"chat_list_empty": "Chat list is empty",
"settings": "Settings: model={model}, language={language}, search_hint={search_hint}, effort_hint={effort_hint}, metrics={metrics}",
"model_not_listed": "Current model is not in the list: {model}",
"img_usage": "Usage: /img <path_or_url> :: <prompt>",
"file_not_found": "File not found: {path}",
"empty_media_path": "Empty media path",
"help_text": """\
Commands:
/help Show commands
/models Show available models
/list Show chats
/active Show active chat
/new [tmp=true|false] [title]
/use <chat_id>
/delete [chat_id]
/reset
/tmp <true|false>
/title <text>
/rename <text>
/clear
Runtime:
/settings
/model <name>
/lang <en|ru> Set interface + default reply language
/ws <true|false> Best-effort web search hint
/effort <standard|extended|off>
Best-effort reasoning hint
/metrics <true|false> Toggle metrics output
Media:
/img <path_or_url> :: <prompt>
/exit
""",
"created_chat": "Created chat: {chat_id} (temporary={temporary})",
"created_default_chat": "Created default chat: {chat_id}",
"usage_use": "Usage: /use <chat_id>",
"deleted_chat": "Deleted chat: {chat_id}",
"no_chats_left": "No chats left. Create a new one with /new",
"reset_chat": "Reset chat context: {chat_id}",
"temporary_value": "temporary={value}",
"usage_title": "Usage: /title <text>",
"unknown_command": "Unknown command. Type /help",
"search_hint_info": "web_search is a best-effort hint. Use /reset or /new to apply it cleanly.",
"effort_hint_info": "reasoning_effort is a best-effort hint. Use /reset or /new to apply it cleanly.",
"command_error": "Command error: {error_type}: {error}",
"request_error": "Request error: {error_type}: {error}",
},
"ru": {
"assistant_prefix": "ассистент> ",
"warmup": "Прогрев...",
"warmup_ok": "ok",
"warmup_skip": "skip",
"startup_error": "Ошибка запуска: {error_type}: {error}",
"mini_cli": "Mini ChatGPT CLI. Введите /help",
"auth_source": "Источник авторизации: {auth_source}",
"no_active_chat": "Активный чат не выбран",
"new_chat_title": "Новый чат",
"active_chat": "Активный чат: {chat_id} [{mode}] {title} (conversation_id: {conversation_id})",
"temporary_mode": "temporary",
"persistent_mode": "persistent",
"chat_list_empty": "Список чатов пуст",
"settings": "Настройки: model={model}, language={language}, search_hint={search_hint}, effort_hint={effort_hint}, metrics={metrics}",
"model_not_listed": "Текущей модели нет в списке: {model}",
"img_usage": "Использование: /img <path_or_url> :: <prompt>",
"file_not_found": "Файл не найден: {path}",
"empty_media_path": "Пустой путь к файлу",
"help_text": """\
Команды:
/help Показать команды
/models Показать доступные модели
/list Показать чаты
/active Показать активный чат
/new [tmp=true|false] [title]
/use <chat_id>
/delete [chat_id]
/reset
/tmp <true|false>
/title <text>
/rename <text>
/clear
Режим:
/settings
/model <name>
/lang <en|ru> Язык интерфейса и ответов по умолчанию
/ws <true|false> Best-effort подсказка для web search
/effort <standard|extended|off>
Best-effort подсказка для reasoning
/metrics <true|false> Включить или выключить метрики
Медиа:
/img <path_or_url> :: <prompt>
/exit
""",
"created_chat": "Создан чат: {chat_id} (temporary={temporary})",
"created_default_chat": "Создан чат по умолчанию: {chat_id}",
"usage_use": "Использование: /use <chat_id>",
"deleted_chat": "Удален чат: {chat_id}",
"no_chats_left": "Чатов не осталось. Создайте новый через /new",
"reset_chat": "Сброшен контекст чата: {chat_id}",
"temporary_value": "temporary={value}",
"usage_title": "Использование: /title <text>",
"unknown_command": "Неизвестная команда. Введите /help",
"search_hint_info": "web_search работает как best-effort hint. Для чистого применения используйте /reset или /new.",
"effort_hint_info": "reasoning_effort работает как best-effort hint. Для чистого применения используйте /reset или /new.",
"command_error": "Ошибка команды: {error_type}: {error}",
"request_error": "Ошибка запроса: {error_type}: {error}",
},
}
def normalize_language(value: Any) -> str:
normalized = str(value or "en").strip().lower()
return normalized if normalized in {"en", "ru"} else "en"
def tr(locale: str, key: str, **kwargs: Any) -> str:
normalized = normalize_language(locale)
template = TRANSLATIONS.get(normalized, TRANSLATIONS["en"]).get(key)
if template is None:
template = TRANSLATIONS["en"].get(key, key)
return str(template).format(**kwargs)
def assistant_prefix_text(language: str) -> str:
return paint(tr(language, "assistant_prefix"), UiColors.GREEN, bold=True)
def parse_bool(value: str) -> bool:
normalized = value.strip().lower()
if normalized in {"1", "true", "t", "yes", "y", "on"}:
return True
if normalized in {"0", "false", "f", "no", "n", "off"}:
return False
raise ValueError(f"Invalid boolean value: {value}")
def parse_reasoning_effort(value: str) -> str | None:
normalized = value.strip().lower()
if normalized in {"off", "none", "-", ""}:
return None
if normalized not in {"standard", "extended"}:
raise ValueError("Effort must be one of: standard, extended, off")
return normalized
def parse_language(value: str) -> str:
normalized = str(value or "").strip().lower()
if normalized not in {"en", "ru"}:
raise ValueError("Language must be one of: en, ru")
return normalized
def _safe_print(text: str) -> None:
try:
print(text, end="", flush=True)
except UnicodeEncodeError:
data = text.encode(sys.stdout.encoding or "utf-8", errors="replace")
if hasattr(sys.stdout, "buffer"):
sys.stdout.buffer.write(data)
sys.stdout.flush()
else:
sys.stdout.write(data.decode(sys.stdout.encoding or "utf-8", errors="replace"))
sys.stdout.flush()
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def _format_metric_seconds(value: Any) -> str:
if isinstance(value, (int, float)):
return f"{value:.3f}s"
return "-"
def _warn_json_read_error(path: Path, error: Exception) -> None:
try:
key = str(path.resolve())
except OSError:
key = str(path)
if key in WARNED_JSON_READ_ERRORS:
return
WARNED_JSON_READ_ERRORS.add(key)
warning(f"Warning: failed to load JSON from {path}: {error}. Treating it as empty.")
def _read_json_dict(path: Path, *, warn_on_error: bool = False) -> dict[str, Any]:
if not path.is_file():
return {}
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
if warn_on_error:
_warn_json_read_error(path, error)
return {}
return payload if isinstance(payload, dict) else {}
def _load_app_state_payload(state_path: str | Path = APP_STATE_FILE) -> dict[str, Any]:
return _read_json_dict(Path(state_path), warn_on_error=True)
def _save_app_state_payload(
payload: dict[str, Any],
state_path: str | Path = APP_STATE_FILE,
) -> None:
target_path = Path(state_path)
target_path.parent.mkdir(parents=True, exist_ok=True)
serialized = json.dumps(payload, ensure_ascii=False, indent=2)
temp_path: Optional[Path] = None
try:
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
delete=False,
dir=target_path.parent,
prefix=f".{target_path.name}.",
suffix=".tmp",
) as handle:
handle.write(serialized)
temp_path = Path(handle.name)
temp_path.replace(target_path)
finally:
if temp_path is not None:
try:
temp_path.unlink(missing_ok=True)
except OSError:
pass
def _build_runtime_system_prompt(
language: str,
web_search: bool,
reasoning_effort: Optional[str],
) -> Optional[str]:
lines: list[str] = []
if normalize_language(language) == "ru":
lines.append("Always answer in Russian unless the user explicitly asks for another language.")
else:
lines.append("Always answer in English unless the user explicitly asks for another language.")
if not web_search:
lines.append("Do not browse the web or use search unless the user explicitly asks for it.")
if reasoning_effort == "standard":
lines.append("Prefer concise reasoning and avoid extended deliberation unless necessary.")
elif reasoning_effort == "extended":
lines.append("Take extra care and reason more thoroughly before answering.")
if not lines:
return None
return "\n".join(lines)
def load_cli_state(state_path: str | Path = APP_STATE_FILE) -> dict[str, Any]:
state = DEFAULT_RUNTIME_STATE.copy()
payload = _load_app_state_payload(state_path).get("runtime")
if not isinstance(payload, dict):
payload = _read_json_dict(LEGACY_CLI_STATE_FILE)
model = payload.get("model")
if isinstance(model, str) and model.strip():
state["model"] = model.strip()
language = payload.get("language")
if isinstance(language, str):
state["language"] = normalize_language(language)
if isinstance(payload.get("web_search"), bool):
state["web_search"] = payload["web_search"]
reasoning_effort = payload.get("reasoning_effort")
if reasoning_effort is None:
state["reasoning_effort"] = None
elif isinstance(reasoning_effort, str):
try:
state["reasoning_effort"] = parse_reasoning_effort(reasoning_effort)
except ValueError:
pass
if isinstance(payload.get("show_metrics"), bool):
state["show_metrics"] = payload["show_metrics"]
return state
def save_cli_state(
state: dict[str, Any],
state_path: str | Path = APP_STATE_FILE,
) -> None:
runtime_payload = {
"model": state["model"],
"language": normalize_language(state["language"]),
"web_search": bool(state["web_search"]),
"reasoning_effort": state["reasoning_effort"],
"show_metrics": bool(state["show_metrics"]),
}
payload = _load_app_state_payload(state_path)
payload["runtime"] = runtime_payload
_save_app_state_payload(payload, state_path)
@dataclass
class AuthData:
api_key: Optional[str] = None
api_key_source: Optional[str] = None
cookies: dict[str, str] = field(default_factory=dict)
headers: dict[str, str] = field(default_factory=dict)
expires: Optional[int] = None
proof_token: Any = None
turnstile_token: Optional[str] = None
@classmethod
def from_json(cls, path: str | Path) -> "AuthData":
payload = json.loads(Path(path).read_text(encoding="utf-8"))
return cls(
api_key=payload.get("api_key"),
cookies=payload.get("cookies") or {},
headers=payload.get("headers") or {},
expires=payload.get("expires"),
proof_token=payload.get("proof_token"),
turnstile_token=payload.get("turnstile_token"),
)
def _iter_env_candidates() -> list[Path]:
script_dir = Path(__file__).resolve().parent
candidates = [
Path.cwd() / ".env",
script_dir / ".env",
script_dir.parent / ".env",
]
unique: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
key = str(candidate.resolve())
if key in seen:
continue
seen.add(key)
unique.append(candidate)
return unique
def _load_access_token() -> Optional[str]:
if os.getenv("accessToken"):
return os.getenv("accessToken")
for env_path in _iter_env_candidates():
if not env_path.is_file():
continue
try:
text = env_path.read_text(encoding="utf-8")
except OSError:
continue
for raw_line in text.splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
if name.strip() != "accessToken":
continue
token = value.strip().strip("'").strip('"')
if token:
os.environ["accessToken"] = token
return token
return None
def _get_access_token_expiry(access_token: Optional[str]) -> Optional[datetime]:
if not access_token or access_token.count(".") < 2:
return None
try:
payload = access_token.split(".", 2)[1]
payload += "=" * (-len(payload) % 4)
data = json.loads(base64.urlsafe_b64decode(payload))
exp = data.get("exp")
if exp is None:
return None
return datetime.fromtimestamp(int(exp), tz=timezone.utc)
except Exception:
return None
def load_auth_data(auth_file: str | Path = DEFAULT_AUTH_FILE) -> AuthData:
auth_path = Path(auth_file)
try:
auth = AuthData.from_json(auth_path)
except FileNotFoundError:
auth = AuthData()
except OSError as error:
raise RuntimeError(f"Failed to read auth data from {auth_path}: {error}") from error
except ValueError as error:
raise RuntimeError(f"Failed to parse auth data from {auth_path}: {error}") from error
candidates: list[tuple[str, str]] = []
if auth.api_key:
candidates.append((f"{auth_path.name}:api_key", auth.api_key))
env_api_key = _load_access_token()
if env_api_key and env_api_key != auth.api_key:
candidates.append((".env:accessToken", env_api_key))
expired_sources: list[str] = []
now_utc = datetime.now(timezone.utc)
for source, token in candidates:
expires_at = _get_access_token_expiry(token)
if expires_at is not None and expires_at <= now_utc:
expires_local = expires_at.astimezone()
expired_sources.append(
f"{source} expired at {expires_local.strftime('%Y-%m-%d %H:%M:%S %z')}"
)
continue
auth.api_key = token
auth.api_key_source = source
break
if not auth.api_key:
if expired_sources:
raise RuntimeError(
"All available access tokens are expired: "
+ "; ".join(expired_sources)
+ ". Refresh authorization before running the CLI."
)
raise RuntimeError(
f"No access token found. Expected api_key in {auth_path.name}"
" or accessToken in .env."
)
return auth
def _build_base_headers(auth: AuthData) -> dict[str, str]:
headers: dict[str, str] = {}
for key, value in auth.headers.items():
if key is None or value is None:
continue
key_str = str(key).lower()
if key_str in {"authorization", "cookie"}:
continue
headers[key_str] = str(value)
headers.setdefault("accept", "*/*")
headers.setdefault("accept-language", "en-US,en;q=0.8")
headers.setdefault("content-type", "application/json")
headers.setdefault("referer", CHAT_URL)
headers.setdefault(
"user-agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
)
return headers
def _generate_answer(seed: str, diff: str, config: list[Any], max_attempts: int = 500_000) -> tuple[str, bool]:
diff_len = len(diff)
seed_encoded = seed.encode()
p1 = (json.dumps(config[:3], separators=(",", ":"), ensure_ascii=False)[:-1] + ",").encode()
p2 = ("," + json.dumps(config[4:9], separators=(",", ":"), ensure_ascii=False)[1:-1] + ",").encode()
p3 = ("," + json.dumps(config[10:], separators=(",", ":"), ensure_ascii=False)[1:]).encode()
target_diff = bytes.fromhex(diff)
for i in range(max_attempts):
d1 = str(i).encode()
d2 = str(i >> 1).encode()
string = p1 + d1 + p2 + d2 + p3
base_encode = base64.b64encode(string)
hash_value = hashlib.new("sha3_512", seed_encoded + base_encode).digest()
if hash_value[:diff_len] <= target_diff:
return base_encode.decode(), True
fallback = base64.b64encode(f'"{seed}"'.encode()).decode()
return "wQ8Lk5FbGpA2NcR9dShT6gYjU7VxZ4D" + fallback, False
def _get_requirements_token(config: list[Any]) -> str:
require, solved = _generate_answer(format(random.random()), "0fffff", config)
if not solved:
raise RuntimeError("Failed to solve requirements challenge")
return "gAAAAAC" + require
def _generate_proof_token(
*,
required: bool,
seed: str = "",
difficulty: str = "",
user_agent: Optional[str] = None,
proof_token: Any = None,
) -> Optional[str]:
if not required:
return None
if proof_token is None:
screen = random.choice([3008, 4010, 6000]) * random.choice([1, 2, 4])
parse_time = datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT")
proof_token = [
screen,
parse_time,
None,
0,
user_agent,
"https://tcr9i.chat.openai.com/v2/35536E1E-65B4-4D96-9D97-6ADB7EFF8147/api.js",
"dpl=1440a687921de39ff5ee56b92807faaadce73f13",
"en",
"en-US",
None,
"plugins-[object PluginArray]",
random.choice(
[
"_reactListeningcfilawjnerp",
"_reactListening9ne2dfo1i47",
"_reactListening410nzwhan2a",
]
),
random.choice(["alert", "ontransitionend", "onprogress"]),
]
diff_len = len(difficulty)
for i in range(100_000):
proof_token[3] = i
payload = json.dumps(proof_token)
base = base64.b64encode(payload.encode()).decode()
hash_value = hashlib.sha3_512((seed + base).encode()).digest()
if hash_value.hex()[:diff_len] <= difficulty:
return "gAAAAAB" + base
fallback = base64.b64encode(f'"{seed}"'.encode()).decode()
return "gAAAAABwQ8Lk5FbGpA2NcR9dShT6gYjU7VxZ4D" + fallback
def _extract_data_uri(data_uri: str) -> bytes:
match = re.match(r"^data:([^;]+);base64,(.+)$", data_uri, re.IGNORECASE | re.DOTALL)
if not match:
raise ValueError("Invalid data URI")
return base64.b64decode(match.group(2))
def _detect_file_type(binary_data: bytes) -> tuple[str, str]:
if binary_data.startswith(b"\xff\xd8\xff"):
return ".jpg", "image/jpeg"
if binary_data.startswith(b"\x89PNG\r\n\x1a\n"):
return ".png", "image/png"
if binary_data.startswith((b"GIF87a", b"GIF89a")):
return ".gif", "image/gif"
if binary_data.startswith(b"RIFF") and binary_data[8:12] == b"WEBP":
return ".webp", "image/webp"
raise ValueError("Unsupported media format")
def _get_png_size(data: bytes) -> tuple[Optional[int], Optional[int]]:
if len(data) < 24:
return None, None
return int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big")
def _get_gif_size(data: bytes) -> tuple[Optional[int], Optional[int]]:
if len(data) < 10:
return None, None
return int.from_bytes(data[6:8], "little"), int.from_bytes(data[8:10], "little")
def _get_jpeg_size(data: bytes) -> tuple[Optional[int], Optional[int]]:
index = 2
while index + 9 < len(data):
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
index += 2
if marker in {0xD8, 0xD9}:
continue
if marker in {0x01} or 0xD0 <= marker <= 0xD7:
continue
if index + 2 > len(data):
break
segment_length = int.from_bytes(data[index:index + 2], "big")
if segment_length < 2 or index + segment_length > len(data):
break
if marker in {
0xC0, 0xC1, 0xC2, 0xC3,
0xC5, 0xC6, 0xC7,
0xC9, 0xCA, 0xCB,
0xCD, 0xCE, 0xCF,
}:
if index + 7 <= len(data):
height = int.from_bytes(data[index + 3:index + 5], "big")
width = int.from_bytes(data[index + 5:index + 7], "big")
return width, height
break
index += segment_length
return None, None
def _get_webp_size(data: bytes) -> tuple[Optional[int], Optional[int]]:
if len(data) < 30:
return None, None
chunk_type = data[12:16]
if chunk_type == b"VP8X" and len(data) >= 30:
width = 1 + int.from_bytes(data[24:27], "little")
height = 1 + int.from_bytes(data[27:30], "little")
return width, height
if chunk_type == b"VP8 " and len(data) >= 30:
width = int.from_bytes(data[26:28], "little") & 0x3FFF
height = int.from_bytes(data[28:30], "little") & 0x3FFF
return width, height
if chunk_type == b"VP8L" and len(data) >= 25:
bits = int.from_bytes(data[21:25], "little")
width = (bits & 0x3FFF) + 1
height = ((bits >> 14) & 0x3FFF) + 1
return width, height
return None, None
def _get_image_size(data: bytes, mime_type: str) -> tuple[Optional[int], Optional[int]]:
if mime_type == "image/png":
return _get_png_size(data)
if mime_type == "image/gif":
return _get_gif_size(data)
if mime_type == "image/jpeg":
return _get_jpeg_size(data)
if mime_type == "image/webp":
return _get_webp_size(data)
return None, None
class ChatGPTWebClient:
def __init__(self, auth_file: str | Path = DEFAULT_AUTH_FILE, timeout: int = DEFAULT_TIMEOUT_SECONDS):
self.auth = load_auth_data(auth_file)
self.timeout = max(10, int(timeout))
self.base_headers = _build_base_headers(self.auth)
self.curl_bin = shutil.which("curl.exe") or shutil.which("curl")
if not self.curl_bin:
raise RuntimeError(
"curl executable was not found. Install curl or run on a system where curl is available."
)
self.prefetched_requirements: Optional[dict[str, Any]] = None
self.prefetched_proof_header: Optional[str] = None
self.prefetched_ts = 0.0
def _build_headers(self, extra: Optional[dict[str, str]] = None) -> dict[str, str]:
headers = dict(self.base_headers)
if self.auth.api_key:
headers["authorization"] = f"Bearer {self.auth.api_key}"
if self.auth.cookies:
headers["cookie"] = "; ".join(f"{k}={v}" for k, v in self.auth.cookies.items())
if extra:
headers.update({key: value for key, value in extra.items() if value is not None})
return headers
def _update_cookies_from_text(self, header_text: str) -> None:
for raw_line in header_text.splitlines():
if not raw_line.lower().startswith("set-cookie:"):
continue
raw_cookie = raw_line.split(":", 1)[1].strip()
jar = SimpleCookie()
jar.load(raw_cookie)
for key, morsel in jar.items():
self.auth.cookies[key] = morsel.value
@staticmethod
def _extract_status_code(header_text: str) -> int:
status = 0
for raw_line in header_text.splitlines():
line = raw_line.strip()
if not line.startswith("HTTP/"):
continue
parts = line.split()
if len(parts) >= 2 and parts[1].isdigit():
status = int(parts[1])
return status
def _build_curl_command(
self,
method: str,
url: str,
headers: dict[str, str],
header_path: str,
body_path: Optional[str] = None,
*,
no_buffer: bool = False,
follow_redirects: bool = False,
) -> list[str]:
command = [
self.curl_bin,
"-sS",
"--compressed",
"--connect-timeout",
"10",
"--max-time",
str(self.timeout),
"-X",
method.upper(),
url,
"-D",
header_path,
]
if no_buffer:
command.insert(1, "-N")
if follow_redirects:
command.insert(1, "-L")
for key, value in headers.items():
command.extend(["-H", f"{key}: {value}"])
if body_path is not None:
command.extend(["--data-binary", f"@{body_path}"])
return command
def _run_curl(
self,
method: str,
url: str,
headers: dict[str, str],
body: Optional[bytes] = None,
*,
persist_cookies: bool = True,
follow_redirects: bool = False,
) -> tuple[int, bytes, str]:
payload_path: Optional[str] = None
with tempfile.NamedTemporaryFile(delete=False) as header_file:
header_path = header_file.name
try:
if body is not None:
with tempfile.NamedTemporaryFile(delete=False) as payload_file:
payload_file.write(body)
payload_path = payload_file.name
command = self._build_curl_command(
method,
url,
headers,
header_path,
payload_path,
follow_redirects=follow_redirects,
)
result = subprocess.run(command, capture_output=True)
header_text = Path(header_path).read_text(encoding="utf-8", errors="replace")
if persist_cookies:
self._update_cookies_from_text(header_text)
status = self._extract_status_code(header_text)
if result.returncode != 0 and not status:
stderr_text = result.stderr.decode("utf-8", errors="replace")
raise RuntimeError(f"curl failed: {stderr_text.strip() or result.returncode}")
return status, result.stdout, header_text
finally:
try:
Path(header_path).unlink(missing_ok=True)
except OSError:
pass
if payload_path:
try:
Path(payload_path).unlink(missing_ok=True)
except OSError:
pass
def _json_request(
self,
method: str,
url: str,
payload: Optional[dict[str, Any]],
headers: dict[str, str],
) -> tuple[int, Any]:
body = None if payload is None else json.dumps(payload, ensure_ascii=False).encode("utf-8")
status, raw_body, _ = self._run_curl(method, url, headers, body)
if not raw_body:
return status, None
body_text = raw_body.decode("utf-8", errors="replace")
try:
return status, json.loads(body_text)
except ValueError:
return status, body_text
def warmup(self) -> bool:
try:
requirements = self._get_chat_requirements()
proof_header = self._build_proof_header(requirements)
except Exception:
return False
token = requirements.get("token") if isinstance(requirements, dict) else None
if isinstance(token, str) and token:
self.prefetched_requirements = requirements
self.prefetched_proof_header = proof_header
self.prefetched_ts = time.monotonic()
return True
return False
def _take_prefetched_requirements(self) -> Optional[tuple[dict[str, Any], Optional[str]]]:
if self.prefetched_requirements is None:
return None
if time.monotonic() - self.prefetched_ts > PREFETCH_TTL_SECONDS:
self.prefetched_requirements = None
self.prefetched_proof_header = None
self.prefetched_ts = 0.0
return None
requirements = self.prefetched_requirements
proof_header = self.prefetched_proof_header
self.prefetched_requirements = None
self.prefetched_proof_header = None
self.prefetched_ts = 0.0
return requirements, proof_header
def _get_ready_requirements(self) -> tuple[dict[str, Any], Optional[str]]:
prefetched = self._take_prefetched_requirements()
if prefetched is not None:
return prefetched
requirements = self._get_chat_requirements()
return requirements, self._build_proof_header(requirements)
def _get_chat_requirements(self) -> dict[str, Any]:
req_input = None
if isinstance(self.auth.proof_token, list):
try:
req_input = _get_requirements_token(self.auth.proof_token)
except Exception:
req_input = None
headers = self._build_headers({"accept": "*/*", "content-type": "application/json"})
status, data = self._json_request("POST", CHAT_REQUIREMENTS_URL, {"p": req_input}, headers)
if status in {401, 403}:
raise RuntimeError(f"chat-requirements status={status}")
if status >= 400:
raise RuntimeError(f"chat-requirements status={status}: {data}")
if not isinstance(data, dict):
raise RuntimeError("chat-requirements response is not a dict")
return data
def _build_proof_header(self, requirements: dict[str, Any]) -> Optional[str]:
proof_block = requirements.get("proofofwork")
if not isinstance(proof_block, dict):
return None
return _generate_proof_token(
required=bool(proof_block.get("required")),
seed=str(proof_block.get("seed") or ""),
difficulty=str(proof_block.get("difficulty") or ""),
user_agent=self.base_headers.get("user-agent"),
proof_token=self.auth.proof_token if isinstance(self.auth.proof_token, list) else None,
)
def _media_to_bytes(self, media_data: Any) -> bytes:
if isinstance(media_data, bytes):
return media_data
if isinstance(media_data, bytearray):
return bytes(media_data)
if isinstance(media_data, Path):
return media_data.read_bytes()
if isinstance(media_data, os.PathLike):
return Path(media_data).read_bytes()
if isinstance(media_data, str):
if media_data.startswith("data:"):
return _extract_data_uri(media_data)
if media_data.startswith(("http://", "https://")):
status, raw_body, _ = self._run_curl(
"GET",
media_data,
{"user-agent": self.base_headers.get("user-agent", "")},
persist_cookies=False,
follow_redirects=True,
)
if not 200 <= status < 300:
raise RuntimeError(f"Media download failed: status={status}")
return raw_body
raise ValueError("Unsupported media string. Use file path, URL, or data URI.")
raise ValueError("Unsupported media type")
def _upload_media_files(self, media: list[tuple[Any, Optional[str]]]) -> list[dict[str, Any]]:
uploaded: list[dict[str, Any]] = []
for media_item in media:
media_data, filename = media_item
data_bytes = self._media_to_bytes(media_data)