CostalCry commited on
Commit
412be29
1 Parent(s): f97b8e7

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +12 -0
  2. .github/FUNDING.yml +13 -0
  3. .github/README.md +68 -0
  4. .github/README_RU.md +66 -0
  5. .gitignore +152 -0
  6. LICENSE +674 -0
  7. README.md +1 -7
  8. assets/custom.css +655 -0
  9. assets/custom.js +705 -0
  10. assets/external-scripts.js +2 -0
  11. assets/favicon.ico +0 -0
  12. assets/html/appearance_switcher.html +6 -0
  13. assets/html/billing_info.html +9 -0
  14. assets/html/footer.html +1 -0
  15. assets/html/update.html +25 -0
  16. autoinstall_linux.sh +63 -0
  17. backend/auto_proxy.py +121 -0
  18. backend/backend.py +253 -0
  19. backend/backend_old_async.py +369 -0
  20. backend/check.py +85 -0
  21. backend/config.py +9 -0
  22. backend/embedding_processing.py +72 -0
  23. configs/ds_config_chatbot.json +17 -0
  24. docker-compose/.env +9 -0
  25. docker-compose/docker-compose.traefik.yml +73 -0
  26. docker-compose/docker-compose.yml +16 -0
  27. dockerfile +28 -0
  28. endpoint.py +21 -0
  29. entrypoint.sh +13 -0
  30. g4f/Provider/AItianhu.py +77 -0
  31. g4f/Provider/AItianhuSpace.py +92 -0
  32. g4f/Provider/Acytoo.py +50 -0
  33. g4f/Provider/AiAsk.py +45 -0
  34. g4f/Provider/Aibn.py +57 -0
  35. g4f/Provider/Aichat.py +55 -0
  36. g4f/Provider/Ails.py +106 -0
  37. g4f/Provider/Aivvm.py +84 -0
  38. g4f/Provider/Bing.py +302 -0
  39. g4f/Provider/ChatBase.py +63 -0
  40. g4f/Provider/ChatForAi.py +54 -0
  41. g4f/Provider/Chatgpt4Online.py +40 -0
  42. g4f/Provider/ChatgptAi.py +75 -0
  43. g4f/Provider/ChatgptDemo.py +61 -0
  44. g4f/Provider/ChatgptDuo.py +58 -0
  45. g4f/Provider/ChatgptX.py +98 -0
  46. g4f/Provider/Cromicle.py +50 -0
  47. g4f/Provider/FreeGpt.py +60 -0
  48. g4f/Provider/GPTalk.py +84 -0
  49. g4f/Provider/GptForLove.py +83 -0
  50. g4f/Provider/GptGo.py +81 -0
.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ start_endpoint.bat
2
+ start.bat
3
+ .gitignore
4
+ .github
5
+ .git
6
+ .env
7
+ LICENCE
8
+ install_ubuntu.sh
9
+ install_on_huggingface.md
10
+ docker-compose.yml
11
+ config.json
12
+ docker-compose/
.github/FUNDING.yml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4
+ patreon: # Replace with a single Patreon username
5
+ open_collective: # Replace with a single Open Collective username
6
+ ko_fi: # Replace with a single Ko-fi username
7
+ tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8
+ community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9
+ liberapay: # Replace with a single Liberapay username
10
+ issuehunt: # Replace with a single IssueHunt username
11
+ otechie: # Replace with a single Otechie username
12
+ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13
+ custom: # ['https://boosty.to/neurogen']
.github/README.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <a href="https://t.me/neurogen_news">
3
+ <img src="https://readme-typing-svg.herokuapp.com?font=Jura&weight=700&size=30&duration=4000&pause=1000&color=1BED29&center=true&width=435&lines=NeuroGPT+by+NeurogenAI" alt="NeuroGPT" />
4
+ </a>
5
+
6
+ <strong> <a href="https://github.com/Em1tSan/NeuroGPT/blob/main/.github/README_RU.md">Русский</a> | English </strong>
7
+
8
+ > ### The project is currently undergoing a transition to another client and reconstruction of the API. Technical work is continuing. We apologize for any inconvenience.
9
+
10
+ <p> Free API service providing access to GPT-3.5, GPT-4, and other language models. Before using it, please make sure you check out our <a href="https://github.com/Em1tSan/NeuroGPT/wiki#english-language">wiki</a>. The project utilizes a modified version of <a href="https://github.com/xtekky/gpt4free">gpt4free</a>, as well as <a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT">ChuanhuChatGPT</a> as a web interface. We extend our gratitude to the authors.</p>
11
+
12
+ <p>
13
+ <a href="https://github.com/Em1tSan/NeuroGPT/blob/main/LICENSE">
14
+ <img src="https://img.shields.io/badge/license-GPL_3.0-darkgreen.svg" alt="license"/>
15
+ </a>
16
+ <a href="https://github.com/Em1tSan/NeuroGPT/commits/main">
17
+ <img src="https://img.shields.io/badge/latest-v1.5.4-darkgreen.svg" alt="latest"/>
18
+ </a></p>
19
+
20
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#windows">
21
+ <img src="https://img.shields.io/badge/-Windows-1371c3?logo=windows" alt="windows"/>
22
+ </a>
23
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#linux">
24
+ <img src="https://img.shields.io/badge/-Linux-F1502F?logo=linux" alt="linux"/>
25
+ </a>
26
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#macos">
27
+ <img src="https://img.shields.io/badge/-MacOS-C0BFC0?logo=apple" alt="macos"/>
28
+ </a>
29
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#portable-version">
30
+ <img src="https://img.shields.io/badge/-Portable version-8080ff?logo=portable" alt="portable"/>
31
+ </a>
32
+
33
+ <br> News and feedback: <br/>
34
+
35
+ <a href="https://t.me/neurogen_news">
36
+ <img src="https://img.shields.io/badge/-Telegram channel-0088CC?logo=telegram" alt="telegram"/>
37
+ </a>
38
+ <a href="https://t.me/neurogen_chat">
39
+ <img src="https://img.shields.io/badge/-Telegram chat-0088CC?logo=telegram" alt="telegram_chat"/>
40
+ </a>
41
+
42
+ <br> Support the project: <br/>
43
+
44
+ <a href="https://boosty.to/neurogen">
45
+ <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Boosty_logo.svg/512px-Boosty_logo.svg.png?20230209172145" alt="neurogen_boosty" width="20%">
46
+ </a>
47
+
48
+ </div>
49
+
50
+ ## Features
51
+
52
+ - Web search
53
+ - [Model list](https://status.neuroapi.host/v1/status)
54
+ - Dialog context
55
+ - No-logs
56
+ - API endpoint
57
+ - Dialog history
58
+ - Setting generation parameters for GPT models
59
+ - Built-in prompt templates and jailbreaks for various tasks
60
+
61
+ <div align="center">
62
+ <img src="https://github.com/NealBelov/screenshots/blob/main/img_03.png?raw=true" width="100%">
63
+
64
+ ***
65
+
66
+ [![Star History Chart](https://api.star-history.com/svg?repos=Em1tSan/NeuroGPT&type=Date)](https://star-history.com/#Em1tSan/NeuroGPT&Date)
67
+
68
+ </div>
.github/README_RU.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <a href="https://t.me/neurogen_news">
3
+ <img src="https://readme-typing-svg.herokuapp.com?font=Jura&weight=700&size=30&duration=4000&pause=1000&color=1BED29&center=true&width=435&lines=NeuroGPT+by+NeurogenAI" alt="NeuroGPT" />
4
+ </a>
5
+
6
+ <strong> Русский | <a href="https://github.com/Em1tSan/NeuroGPT#readme">English </a></strong>
7
+
8
+ <p> Бесплатный API-сервис, предоставляющий доступ к GPT-3.5, GPT-4 и другим языковым моделям. Перед использованием, пожалуйста, убедитесь, что ознакомились с нашей <a href="https://github.com/Em1tSan/NeuroGPT/wiki#english-language">wiki</a>. В проекте используется модифицированная версия <a href="https://github.com/xtekky/gpt4free">gpt4free</a>, а также <a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT">ChuanhuChatGPT</a> в качестве веб-интерфейса. Выражаем благодарность авторам. </p>
9
+
10
+ <p>
11
+ <a href="https://github.com/Em1tSan/NeuroGPT/blob/main/LICENSE">
12
+ <img src="https://img.shields.io/badge/license-GPL_3.0-darkgreen.svg" alt="license"/>
13
+ </a>
14
+ <a href="https://github.com/Em1tSan/NeuroGPT/commits/main">
15
+ <img src="https://img.shields.io/badge/latest-v1.5.3-darkgreen.svg" alt="latest"/>
16
+ </a></p>
17
+
18
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#windows">
19
+ <img src="https://img.shields.io/badge/-Windows-1371c3?logo=windows" alt="windows"/>
20
+ </a>
21
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#linux">
22
+ <img src="https://img.shields.io/badge/-Linux-F1502F?logo=linux" alt="linux"/>
23
+ </a>
24
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#macos">
25
+ <img src="https://img.shields.io/badge/-MacOS-C0BFC0?logo=apple" alt="macos"/>
26
+ </a>
27
+ <a href="https://github.com/Em1tSan/NeuroGPT/wiki/Installing-and-running#portable-version">
28
+ <img src="https://img.shields.io/badge/-Портативная версия-8080ff?logo=portable" alt="portable"/>
29
+ </a>
30
+
31
+ <br> Новости и обратная связь: <br/>
32
+
33
+ <a href="https://t.me/neurogen_news">
34
+ <img src="https://img.shields.io/badge/-Telegram канал-0088CC?logo=telegram" alt="telegram"/>
35
+ </a>
36
+ <a href="https://t.me/neurogen_chat">
37
+ <img src="https://img.shields.io/badge/-Telegram чат-0088CC?logo=telegram" alt="telegram_chat"/>
38
+ </a>
39
+
40
+ <br> Поддержать проект: <br/>
41
+
42
+ <a href="https://boosty.to/neurogen">
43
+ <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Boosty_logo.svg/512px-Boosty_logo.svg.png?20230209172145" alt="neurogen_boosty" width="20%">
44
+ </a>
45
+
46
+ </div>
47
+
48
+ ## Возможности
49
+
50
+ - Веб-поиск
51
+ - [Список моделей](https://status.neuroapi.host/v1/status)
52
+ - Контекст беседы
53
+ - Отсутствие логов
54
+ - История диалога
55
+ - Режим endpoint для работы с API
56
+ - Изменение параметров генерации для GPT-моделей
57
+ - Встроенные джейлбрейки и шаблоны промптов под разные задачи
58
+
59
+ <div align="center">
60
+ <img src="https://github.com/NealBelov/screenshots/blob/main/img_03.png?raw=true" width="100%">
61
+
62
+ ***
63
+
64
+ [![Star History Chart](https://api.star-history.com/svg?repos=Em1tSan/NeuroGPT&type=Date)](https://star-history.com/#Em1tSan/NeuroGPT&Date)
65
+
66
+ </div>
.gitignore ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+ history/
30
+ index/
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ .python-version
88
+
89
+ # pipenv
90
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
91
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
92
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
93
+ # install all needed dependencies.
94
+ #Pipfile.lock
95
+
96
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
97
+ __pypackages__/
98
+
99
+ # Celery stuff
100
+ celerybeat-schedule
101
+ celerybeat.pid
102
+
103
+ # SageMath parsed files
104
+ *.sage.py
105
+
106
+ # Environments
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+ python/
114
+ git/
115
+ history/
116
+
117
+
118
+ # Spyder project settings
119
+ .spyderproject
120
+ .spyproject
121
+
122
+ # Rope project settings
123
+ .ropeproject
124
+
125
+ # mkdocs documentation
126
+ /site
127
+
128
+ # mypy
129
+ .mypy_cache/
130
+ .dmypy.json
131
+ dmypy.json
132
+
133
+ # Pyre type checker
134
+ .pyre/
135
+
136
+ # Mac system file
137
+ **/.DS_Store
138
+
139
+ #vscode
140
+ .vscode
141
+
142
+ # 配置文件/模型文件
143
+ api_key.txt
144
+ config.json
145
+ auth.json
146
+ .models/
147
+ lora/
148
+ .idea
149
+ templates/*
150
+ code_improver.yaml
151
+ .history
152
+ config.json
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
  title: NeuroGPT
3
- emoji: 👁
4
- colorFrom: pink
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 4.27.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: NeuroGPT
3
+ app_file: webui_en.py
 
 
4
  sdk: gradio
5
  sdk_version: 4.27.0
 
 
6
  ---
 
 
assets/custom.css ADDED
@@ -0,0 +1,655 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --chatbot-color-light: #000000;
3
+ --chatbot-color-dark: #FFFFFF;
4
+ --chatbot-background-color-light: #F3F3F3;
5
+ --chatbot-background-color-dark: #121111;
6
+ --message-user-background-color-light: #95EC69;
7
+ --message-user-background-color-dark: #26B561;
8
+ --message-bot-background-color-light: #FFFFFF;
9
+ --message-bot-background-color-dark: #2C2C2C;
10
+ --switch-checkbox-color-light: #e5e7eb;
11
+ --switch-checkbox-color-dark: #515151;
12
+ }
13
+
14
+
15
+ #app_title {
16
+ font-weight: var(--prose-header-text-weight);
17
+ font-size: var(--text-xxl);
18
+ line-height: 1.3;
19
+ text-align: left;
20
+ margin-top: 6px;
21
+ white-space: nowrap;
22
+ }
23
+ #description {
24
+ text-align: center;
25
+ margin: 32px 0 4px 0;
26
+ }
27
+
28
+ /* Fix padding error when container=False */
29
+ div.form {
30
+ background: none !important;
31
+ }
32
+
33
+ /* Advanced page */
34
+ #advanced_warning {
35
+ display: flex;
36
+ flex-wrap: wrap;
37
+ flex-direction: column;
38
+ align-content: center;
39
+ }
40
+
41
+ /* Gradio footer info */
42
+ footer {
43
+ /* display: none !important; */
44
+ margin-top: .2em !important;
45
+ font-size: 85%;
46
+ }
47
+ #footer {
48
+ text-align: center;
49
+ }
50
+ #footer div {
51
+ display: inline-block;
52
+ }
53
+ #footer .versions{
54
+ font-size: 85%;
55
+ opacity: 0.60;
56
+ }
57
+
58
+ #float_display {
59
+ position: absolute;
60
+ max-height: 30px;
61
+ }
62
+ #toast-update {
63
+ position: absolute;
64
+ display: flex;
65
+ top: -500px;
66
+ width: 100%;
67
+ justify-content: center;
68
+ z-index: var(--layer-top);
69
+ transition: top 0.3s ease-out;
70
+ }
71
+ #check-chuanhu-update {
72
+ position: absolute;
73
+ align-items: center;
74
+ display: flex;
75
+ flex-direction: column;
76
+ justify-content: center;
77
+ margin: var(--size-6) var(--size-4);
78
+ box-shadow: var(--shadow-drop-lg);
79
+ border: 1px solid var(--block-label-border-color);
80
+ border-radius: var(--container-radius);
81
+ background: var(--background-fill-primary);
82
+ padding: var(--size-4) var(--size-6);
83
+ min-width: 360px;
84
+ max-width: 480px;
85
+ overflow: hidden;
86
+ pointer-events: auto;
87
+ }
88
+ #version-info-title {
89
+ font-size: 1.2em;
90
+ font-weight: bold;
91
+ text-align: start;
92
+ width: 100%;
93
+ }
94
+ #release-note-wrap {
95
+ width: 100%;
96
+ max-width: 400px;
97
+ height: 120px;
98
+ border: solid 1px var(--border-color-primary);
99
+ overflow: auto;
100
+ padding: 0 8px;
101
+ }
102
+ #release-note-wrap.hideK {
103
+ display: none;
104
+ }
105
+ .btn-update-group {
106
+ display: flex;
107
+ justify-content: space-evenly;
108
+ align-items: center;
109
+ width: 100%;
110
+ padding-top: 10px;
111
+ }
112
+ .btn-update-group.hideK {
113
+ display: none;
114
+ }
115
+ /* user_info */
116
+ #user_info.block {
117
+ white-space: nowrap;
118
+ position: absolute; left: 8em; top: .8em;
119
+ z-index: var(--layer-2);
120
+ box-shadow: var(--block-shadow);
121
+ border: none!important; border-radius: var(--block-label-radius);
122
+ background: var(--color-accent);
123
+ padding: var(--block-label-padding);
124
+ font-size: var(--block-label-text-size); line-height: var(--line-sm);
125
+ width: auto; max-height: 30px!important;
126
+ opacity: 1;
127
+ transition: opacity 0.3s ease-in-out;
128
+ }
129
+ #user_info.block .wrap {
130
+ opacity: 0;
131
+ }
132
+ #user_info p {
133
+ color: white;
134
+ font-weight: var(--block-label-text-weight);
135
+ }
136
+ #user_info.hideK {
137
+ opacity: 0;
138
+ transition: opacity 1s ease-in-out;
139
+ }
140
+
141
+ /* status_display */
142
+ #status_display {
143
+ display: flex;
144
+ min-height: 2em;
145
+ align-items: flex-end;
146
+ justify-content: flex-end;
147
+ }
148
+ #status_display p {
149
+ font-size: .85em;
150
+ font-family: ui-monospace, "SF Mono", "SFMono-Regular", "Menlo", "Consolas", "Liberation Mono", "Microsoft Yahei UI", "Microsoft Yahei", monospace;
151
+ /* Fallback to Microsoft Yahei on Windows */
152
+ color: var(--body-text-color-subdued);
153
+ }
154
+
155
+ #status_display {
156
+ transition: all 0.6s;
157
+ }
158
+ #chuanhu_chatbot {
159
+ transition: height 0.3s ease;
160
+ }
161
+
162
+ /* usage_display */
163
+ .insert_block {
164
+ position: relative;
165
+ margin: 0;
166
+ padding: 8px 12px;
167
+ box-shadow: var(--block-shadow);
168
+ border-width: var(--block-border-width);
169
+ border-color: var(--block-border-color);
170
+ border-radius: var(--block-radius);
171
+ background: var(--block-background-fill);
172
+ width: 100%;
173
+ line-height: var(--line-sm);
174
+ min-height: 2em;
175
+ }
176
+ #usage_display p, #usage_display span {
177
+ margin: 0;
178
+ font-size: .85em;
179
+ color: var(--body-text-color-subdued);
180
+ }
181
+ .progress-bar {
182
+ background-color: var(--input-background-fill);;
183
+ margin: .5em 0 !important;
184
+ height: 20px;
185
+ border-radius: 10px;
186
+ overflow: hidden;
187
+ }
188
+ .progress {
189
+ background-color: var(--block-title-background-fill);
190
+ height: 100%;
191
+ border-radius: 10px;
192
+ text-align: right;
193
+ transition: width 0.5s ease-in-out;
194
+ }
195
+ .progress-text {
196
+ /* color: white; */
197
+ color: var(--color-accent) !important;
198
+ font-size: 1em !important;
199
+ font-weight: bold;
200
+ padding-right: 10px;
201
+ line-height: 20px;
202
+ }
203
+
204
+ /* Light/dark mode switch */
205
+ #apSwitch input[type="checkbox"] {
206
+ margin: 0 !important;
207
+ }
208
+ #apSwitch label.apSwitch {
209
+ display: flex;
210
+ align-items: center;
211
+ cursor: pointer;
212
+ color: var(--body-text-color);
213
+ font-weight: var(--checkbox-label-text-weight);
214
+ font-size: var(--checkbox-label-text-size);
215
+ line-height: var(--line-md);
216
+ margin: 2px 0 !important;
217
+ }
218
+ input[type="checkbox"]#apSwitch_checkbox::before {
219
+ background: none !important;
220
+ content: '';
221
+ border: none !important;
222
+ box-shadow: none !important;
223
+ font-size: 22px;
224
+ top: -4.4px;
225
+ left: -1px;
226
+ }
227
+ input:checked[type="checkbox"]#apSwitch_checkbox::before {
228
+ content: '';
229
+ left: 16px;
230
+ }
231
+ /* .apSwitch {
232
+ top: 2px;
233
+ display: inline-block;
234
+ height: 22px;
235
+ position: relative;
236
+ width: 40px;
237
+ border-radius: 11px;
238
+ box-shadow: inset 0 0 1px 0 rgba(0,0,0,0.05), inset 0 0 2px 0 rgba(0,0,0,0.08) !important;
239
+ }
240
+ .apSwitch input {
241
+ display: none !important;
242
+ }
243
+ .apSlider {
244
+ background-color: var(--neutral-200);
245
+ bottom: 0;
246
+ cursor: pointer;
247
+ left: 0;
248
+ position: absolute;
249
+ right: 0;
250
+ top: 0;
251
+ transition: .4s;
252
+ font-size: 22px;
253
+ border-radius: 11px;
254
+ }
255
+ .apSlider::before {
256
+ transform: scale(0.9);
257
+ position: absolute;
258
+ transition: .4s;
259
+ content: "🌞";
260
+ }
261
+ input:checked + .apSlider {
262
+ background-color: var(--primary-600);
263
+ }
264
+ input:checked + .apSlider::before {
265
+ transform: translateX(18px);
266
+ content:"🌚";
267
+ } */
268
+ .switch_checkbox label {
269
+ flex-direction: row-reverse;
270
+ justify-content: space-between;
271
+ }
272
+ .switch_checkbox input[type="checkbox"] + span {
273
+ margin-left: 0 !important;
274
+ }
275
+ .switch_checkbox input[type="checkbox"] {
276
+ -moz-appearance: none;
277
+ appearance: none;
278
+ -webkit-appearance: none;
279
+ outline: none;
280
+ }
281
+ .switch_checkbox input[type="checkbox"] {
282
+ display: inline-block !important;
283
+ position: relative !important;
284
+ border: none !important;
285
+ outline: none;
286
+ width: 40px !important;
287
+ height: 22px !important;
288
+ border-radius: 11px !important;
289
+ background-image: none !important;
290
+ box-shadow: inset 0 0 1px 0 rgba(0,0,0,0.05), inset 0 0 2px 0 rgba(0,0,0,0.08) !important;
291
+ background-image: none !important;
292
+ background-color: var(--switch-checkbox-color-light) !important;
293
+ transition: .2s ease background-color;
294
+ }
295
+ .dark .switch_checkbox input[type="checkbox"] {
296
+ background-color: var(--switch-checkbox-color-dark) !important;
297
+ }
298
+ .switch_checkbox input[type="checkbox"]::before {
299
+ content: "";
300
+ position: absolute;
301
+ width: 22px;
302
+ height: 22px;
303
+ top: 0;
304
+ left: 0;
305
+ background: #FFFFFF;
306
+ border: 0.5px solid rgba(0,0,0,0.02);
307
+ box-shadow: 0 0 0 0 rgba(0,0,0,0.15), 0 1px 0 0 rgba(0,0,0,0.05);
308
+ transform: scale(0.9);
309
+ border-radius: 11px !important;
310
+ transition: .4s ease all;
311
+ box-shadow: var(--input-shadow);
312
+ }
313
+ .switch_checkbox input:checked[type="checkbox"] {
314
+ background-color: var(--primary-600) !important;
315
+ }
316
+ .switch_checkbox input:checked[type="checkbox"]::before {
317
+ background-color: #fff;
318
+ left: 18px;
319
+ }
320
+
321
+ /* Override Slider Styles (for webkit browsers like Safari and Chrome)
322
+ * Hope this proposal can be implemented soon https://github.com/w3c/csswg-drafts/issues/4410
323
+ * Sliders are too inconsistent across platforms
324
+ */
325
+ input[type="range"] {
326
+ -webkit-appearance: none;
327
+ height: 4px;
328
+ background: var(--input-background-fill);
329
+ border-radius: 5px;
330
+ background-image: linear-gradient(var(--primary-500),var(--primary-500));
331
+ background-size: 0% 100%;
332
+ background-repeat: no-repeat;
333
+ }
334
+ input[type="range"]::-webkit-slider-thumb {
335
+ -webkit-appearance: none;
336
+ height: 20px;
337
+ width: 20px;
338
+ border-radius: 50%;
339
+ border: solid 0.5px #ddd;
340
+ background-color: white;
341
+ cursor: ew-resize;
342
+ box-shadow: var(--input-shadow);
343
+ transition: background-color .1s ease;
344
+ }
345
+ input[type="range"]::-webkit-slider-thumb:hover {
346
+ background: var(--neutral-50);
347
+ }
348
+ input[type=range]::-webkit-slider-runnable-track {
349
+ -webkit-appearance: none;
350
+ box-shadow: none;
351
+ border: none;
352
+ background: transparent;
353
+ }
354
+
355
+ hr.append-display {
356
+ margin: 8px 0;
357
+ border: none;
358
+ height: 1px;
359
+ border-top-width: 0;
360
+ background-image: linear-gradient(to right, rgba(50,50,50, 0.1), rgba(150, 150, 150, 0.8), rgba(50,50,50, 0.1));
361
+ }
362
+ .source-a {
363
+ font-size: 0.8em;
364
+ max-width: 100%;
365
+ margin: 0;
366
+ display: flex;
367
+ flex-direction: row;
368
+ flex-wrap: wrap;
369
+ align-items: center;
370
+ /* background-color: #dddddd88; */
371
+ border-radius: 1.5rem;
372
+ padding: 0.2em;
373
+ }
374
+ .source-a a {
375
+ display: inline-block;
376
+ background-color: #aaaaaa50;
377
+ border-radius: 1rem;
378
+ padding: 0.5em;
379
+ text-align: center;
380
+ text-overflow: ellipsis;
381
+ overflow: hidden;
382
+ min-width: 20%;
383
+ white-space: nowrap;
384
+ margin: 0.2rem 0.1rem;
385
+ text-decoration: none !important;
386
+ flex: 1;
387
+ transition: flex 0.5s;
388
+ }
389
+ .source-a a:hover {
390
+ background-color: #aaaaaa20;
391
+ flex: 2;
392
+ }
393
+
394
+ #submit_btn, #cancel_btn {
395
+ height: 42px !important;
396
+ }
397
+ #submit_btn::before {
398
+ content: url("data:image/svg+xml, %3Csvg width='21px' height='20px' viewBox='0 0 21 20' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E %3Cg id='page' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E %3Cg id='send' transform='translate(0.435849, 0.088463)' fill='%23FFFFFF' fill-rule='nonzero'%3E %3Cpath d='M0.579148261,0.0428666046 C0.301105539,-0.0961547561 -0.036517765,0.122307382 0.0032026237,0.420210298 L1.4927172,18.1553639 C1.5125774,18.4334066 1.79062012,18.5922882 2.04880264,18.4929872 L8.24518329,15.8913017 L11.6412765,19.7441794 C11.8597387,19.9825018 12.2370824,19.8832008 12.3165231,19.5852979 L13.9450591,13.4882182 L19.7839562,11.0255541 C20.0619989,10.8865327 20.0818591,10.4694687 19.7839562,10.3105871 L0.579148261,0.0428666046 Z M11.6138902,17.0883151 L9.85385903,14.7195502 L0.718169621,0.618812241 L12.69945,12.9346347 L11.6138902,17.0883151 Z' id='shape'%3E%3C/path%3E %3C/g%3E %3C/g%3E %3C/svg%3E");
399
+ height: 21px;
400
+ }
401
+ #cancel_btn::before {
402
+ content: url("data:image/svg+xml,%3Csvg width='21px' height='21px' viewBox='0 0 21 21' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E %3Cg id='pg' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E %3Cpath d='M10.2072007,20.088463 C11.5727865,20.088463 12.8594566,19.8259823 14.067211,19.3010209 C15.2749653,18.7760595 16.3386126,18.0538087 17.2581528,17.1342685 C18.177693,16.2147282 18.8982283,15.1527965 19.4197586,13.9484733 C19.9412889,12.7441501 20.202054,11.4557644 20.202054,10.0833163 C20.202054,8.71773046 19.9395733,7.43106036 19.4146119,6.22330603 C18.8896505,5.01555169 18.1673997,3.95018885 17.2478595,3.0272175 C16.3283192,2.10424615 15.2646719,1.3837109 14.0569176,0.865611739 C12.8491633,0.34751258 11.5624932,0.088463 10.1969073,0.088463 C8.83132146,0.088463 7.54636692,0.34751258 6.34204371,0.865611739 C5.1377205,1.3837109 4.07407321,2.10424615 3.15110186,3.0272175 C2.22813051,3.95018885 1.5058797,5.01555169 0.984349419,6.22330603 C0.46281914,7.43106036 0.202054,8.71773046 0.202054,10.0833163 C0.202054,11.4557644 0.4645347,12.7441501 0.9894961,13.9484733 C1.5144575,15.1527965 2.23670831,16.2147282 3.15624854,17.1342685 C4.07578877,18.0538087 5.1377205,18.7760595 6.34204371,19.3010209 C7.54636692,19.8259823 8.83475258,20.088463 10.2072007,20.088463 Z M10.2072007,18.2562448 C9.07493099,18.2562448 8.01471483,18.0452309 7.0265522,17.6232031 C6.03838956,17.2011753 5.17031614,16.6161693 4.42233192,15.8681851 C3.6743477,15.1202009 3.09105726,14.2521274 2.67246059,13.2639648 C2.25386392,12.2758022 2.04456558,11.215586 2.04456558,10.0833163 C2.04456558,8.95104663 2.25386392,7.89083047 2.67246059,6.90266784 C3.09105726,5.9145052 3.6743477,5.04643178 4.42233192,4.29844756 C5.17031614,3.55046334 6.036674,2.9671729 7.02140552,2.54857623 C8.00613703,2.12997956 9.06463763,1.92068122 10.1969073,1.92068122 C11.329177,1.92068122 12.3911087,2.12997956 13.3827025,2.54857623 C14.3742962,2.9671729 15.2440852,3.55046334 15.9920694,4.29844756 C16.7400537,5.04643178 17.3233441,5.9145052 17.7419408,6.90266784 C18.1605374,7.89083047 18.3698358,8.95104663 18.3698358,10.0833163 C18.3698358,11.215586 18.1605374,12.2758022 17.7419408,13.2639648 C17.3233441,14.2521274 16.7400537,15.1202009 15.9920694,15.8681851 C15.2440852,16.6161693 14.3760118,17.2011753 13.3878492,17.6232031 C12.3996865,18.0452309 11.3394704,18.2562448 10.2072007,18.2562448 Z M7.65444721,13.6242324 L12.7496608,13.6242324 C13.0584616,13.6242324 13.3003556,13.5384544 13.4753427,13.3668984 C13.6503299,13.1953424 13.7378234,12.9585951 13.7378234,12.6566565 L13.7378234,7.49968276 C13.7378234,7.19774418 13.6503299,6.96099688 13.4753427,6.78944087 C13.3003556,6.61788486 13.0584616,6.53210685 12.7496608,6.53210685 L7.65444721,6.53210685 C7.33878414,6.53210685 7.09345904,6.61788486 6.91847191,6.78944087 C6.74348478,6.96099688 6.65599121,7.19774418 6.65599121,7.49968276 L6.65599121,12.6566565 C6.65599121,12.9585951 6.74348478,13.1953424 6.91847191,13.3668984 C7.09345904,13.5384544 7.33878414,13.6242324 7.65444721,13.6242324 Z' id='shape' fill='%23FF3B30' fill-rule='nonzero'%3E%3C/path%3E %3C/g%3E %3C/svg%3E");
403
+ height: 21px;
404
+ }
405
+ /* list */
406
+ ol:not(.options), ul:not(.options) {
407
+ padding-inline-start: 2em !important;
408
+ }
409
+
410
+ /* Light theme (default) */
411
+ #chuanhu_chatbot {
412
+ background-color: var(--chatbot-background-color-light) !important;
413
+ color: var(--chatbot-color-light) !important;
414
+ }
415
+ [data-testid = "bot"] {
416
+ background-color: var(--message-bot-background-color-light) !important;
417
+ }
418
+ [data-testid = "user"] {
419
+ background-color: var(--message-user-background-color-light) !important;
420
+ }
421
+ /* Dark theme */
422
+ .dark #chuanhu_chatbot {
423
+ background-color: var(--chatbot-background-color-dark) !important;
424
+ color: var(--chatbot-color-dark) !important;
425
+ }
426
+ .dark [data-testid = "bot"] {
427
+ background-color: var(--message-bot-background-color-dark) !important;
428
+ }
429
+ .dark [data-testid = "user"] {
430
+ background-color: var(--message-user-background-color-dark) !important;
431
+ }
432
+
433
+ /* Devices with screen width >= 500px */
434
+ /* Height adjustments written in JavaScript since 2023.4.8 */
435
+ @media screen and (min-width: 500px) {
436
+ #chuanhu_chatbot {
437
+ height: calc(100vh - 200px);
438
+ }
439
+ #chuanhu_chatbot>.wrapper>.wrap {
440
+ max-height: calc(100vh - 200px - var(--line-sm)*1rem - 2*var(--block-label-margin) );
441
+ }
442
+ }
443
+ /* Devices with screen width < 500px */
444
+ @media screen and (max-width: 499px) {
445
+ #chuanhu_chatbot {
446
+ height: calc(100vh - 140px);
447
+ }
448
+ #chuanhu_chatbot>.wrapper>.wrap {
449
+ max-height: calc(100vh - 140px - var(--line-sm)*1rem - 2*var(--block-label-margin) );
450
+ }
451
+ [data-testid = "bot"] {
452
+ max-width: 95% !important;
453
+ }
454
+ #app_title h1{
455
+ letter-spacing: -1px; font-size: 22px;
456
+ }
457
+ }
458
+ #chuanhu_chatbot>.wrapper>.wrap {
459
+ overflow-x: hidden;
460
+ }
461
+ /* Chat bubbles */
462
+ .message {
463
+ border-radius: var(--radius-xl) !important;
464
+ border: none;
465
+ padding: var(--spacing-xl) !important;
466
+ font-size: var(--text-md) !important;
467
+ line-height: var(--line-md) !important;
468
+ min-height: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
469
+ min-width: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
470
+ }
471
+ [data-testid = "bot"] {
472
+ max-width: 85%;
473
+ border-bottom-left-radius: 0 !important;
474
+ }
475
+ [data-testid = "user"] {
476
+ max-width: 85%;
477
+ width: auto !important;
478
+ border-bottom-right-radius: 0 !important;
479
+ }
480
+
481
+ .message.user p {
482
+ white-space: pre-wrap;
483
+ }
484
+ .message .user-message {
485
+ display: block;
486
+ padding: 0 !important;
487
+ white-space: pre-wrap;
488
+ }
489
+
490
+ .message .md-message p {
491
+ margin-top: 0.6em !important;
492
+ margin-bottom: 0.6em !important;
493
+ }
494
+ .message .md-message p:first-child { margin-top: 0 !important; }
495
+ .message .md-message p:last-of-type { margin-bottom: 0 !important; }
496
+
497
+ .message .md-message {
498
+ display: block;
499
+ padding: 0 !important;
500
+ }
501
+ .message .raw-message p {
502
+ margin:0 !important;
503
+ }
504
+ .message .raw-message {
505
+ display: block;
506
+ padding: 0 !important;
507
+ white-space: pre-wrap;
508
+ }
509
+ .raw-message.hideM, .md-message.hideM {
510
+ display: none;
511
+ }
512
+
513
+ /* Custom buttons */
514
+ .chuanhu-btn {
515
+ border-radius: 5px;
516
+ /* background-color: #E6E6E6 !important; */
517
+ color: rgba(120, 120, 120, 0.64) !important;
518
+ padding: 4px !important;
519
+ position: absolute;
520
+ right: -22px;
521
+ cursor: pointer !important;
522
+ transition: color .2s ease, background-color .2s ease;
523
+ }
524
+ .chuanhu-btn:hover {
525
+ background-color: rgba(167, 167, 167, 0.25) !important;
526
+ color: unset !important;
527
+ }
528
+ .chuanhu-btn:active {
529
+ background-color: rgba(167, 167, 167, 0.5) !important;
530
+ }
531
+ .chuanhu-btn:focus {
532
+ outline: none;
533
+ }
534
+ .copy-bot-btn {
535
+ /* top: 18px; */
536
+ bottom: 0;
537
+ }
538
+ .toggle-md-btn {
539
+ /* top: 0; */
540
+ bottom: 20px;
541
+ }
542
+ .copy-code-btn {
543
+ position: relative;
544
+ float: right;
545
+ font-size: 1em;
546
+ cursor: pointer;
547
+ }
548
+
549
+ .message-wrap>div img{
550
+ border-radius: 10px !important;
551
+ }
552
+
553
+ /* History message */
554
+ .wrapper>.wrap>.history-message {
555
+ padding: 10px !important;
556
+ }
557
+ .history-message {
558
+ /* padding: 0 !important; */
559
+ opacity: 80%;
560
+ display: flex;
561
+ flex-direction: column;
562
+ }
563
+ .history-message>.history-message {
564
+ padding: 0 !important;
565
+ }
566
+ .history-message>.message-wrap {
567
+ padding: 0 !important;
568
+ margin-bottom: 16px;
569
+ }
570
+ .history-message>.message {
571
+ margin-bottom: 16px;
572
+ }
573
+ .wrapper>.wrap>.history-message::after {
574
+ content: "";
575
+ display: block;
576
+ height: 2px;
577
+ background-color: var(--body-text-color-subdued);
578
+ margin-bottom: 10px;
579
+ margin-top: -10px;
580
+ clear: both;
581
+ }
582
+ .wrapper>.wrap>.history-message>:last-child::after {
583
+ content: "For viewing only";
584
+ display: block;
585
+ text-align: center;
586
+ color: var(--body-text-color-subdued);
587
+ font-size: 0.8em;
588
+ }
589
+
590
+ /* Table */
591
+ table {
592
+ margin: 1em 0;
593
+ border-collapse: collapse;
594
+ empty-cells: show;
595
+ }
596
+ td,th {
597
+ border: 1.2px solid var(--border-color-primary) !important;
598
+ padding: 0.2em;
599
+ }
600
+ thead {
601
+ background-color: rgba(175,184,193,0.2);
602
+ }
603
+ thead th {
604
+ padding: .5em .2em;
605
+ }
606
+ /* Inline code */
607
+ .message :not(pre) code {
608
+ display: inline;
609
+ white-space: break-spaces;
610
+ font-family: var(--font-mono);
611
+ border-radius: 6px;
612
+ margin: 0 2px 0 2px;
613
+ padding: .2em .4em .1em .4em;
614
+ background-color: rgba(175,184,193,0.2);
615
+ }
616
+ /* Code block */
617
+ .message pre,
618
+ .message pre[class*=language-] {
619
+ color: #fff;
620
+ overflow-x: auto;
621
+ overflow-y: hidden;
622
+ margin: .8em 1em 1em 0em !important;
623
+ padding: var(--spacing-xl) 1.2em !important;
624
+ border-radius: var(--radius-lg) !important;
625
+ }
626
+ .message pre code,
627
+ .message pre code[class*=language-] {
628
+ color: #fff;
629
+ padding: 0;
630
+ margin: 0;
631
+ background-color: unset;
632
+ text-shadow: none;
633
+ font-family: var(--font-mono);
634
+ }
635
+ /* Override Gradio's ugly copy button styles */
636
+ pre button[title="copy"] {
637
+ border-radius: 5px;
638
+ transition: background-color .2s ease;
639
+ }
640
+ pre button[title="copy"]:hover {
641
+ background-color: #333232;
642
+ }
643
+ pre button .check {
644
+ color: #fff !important;
645
+ background: var(--neutral-950) !important;
646
+ }
647
+
648
+ /* Override prism.css */
649
+ .language-css .token.string,
650
+ .style .token.string,
651
+ .token.entity,
652
+ .token.operator,
653
+ .token.url {
654
+ background: none !important;
655
+ }
assets/custom.js ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const MAX_HISTORY_LENGTH = 32;
2
+
3
+ var key_down_history = [];
4
+ var currentIndex = -1;
5
+ var user_input_ta;
6
+
7
+ var gradioContainer = null;
8
+ var user_input_ta = null;
9
+ var user_input_tb = null;
10
+ var userInfoDiv = null;
11
+ var appTitleDiv = null;
12
+ var chatbot = null;
13
+ var chatbotWrap = null;
14
+ var apSwitch = null;
15
+ var messageBotDivs = null;
16
+ var loginUserForm = null;
17
+ var logginUser = null;
18
+ var updateToast = null;
19
+ var sendBtn = null;
20
+ var cancelBtn = null;
21
+ var sliders = null;
22
+
23
+ var userLogged = false;
24
+ var usernameGotten = false;
25
+ var historyLoaded = false;
26
+ var updateInfoGotten = false;
27
+ var isLatestVersion = localStorage.getItem('isLatestVersion') || false;
28
+
29
+ var ga = document.getElementsByTagName("gradio-app");
30
+ var targetNode = ga[0];
31
+ var isInIframe = (window.self !== window.top);
32
+ var language = navigator.language.slice(0,2);
33
+ var currentTime = new Date().getTime();
34
+
35
+ var forView_i18n = {
36
+ 'zh': "For viewing only",
37
+ 'en': "For viewing only",
38
+ 'ru': "История прошлых сообщений",
39
+ 'ja': "For viewing only",
40
+ 'ko': "For viewing only",
41
+ 'fr': "For viewing only",
42
+ 'es': "For viewing only",
43
+ };
44
+
45
+ var deleteConfirm_i18n_pref = {
46
+ 'zh': "Are you sure you want to delete ",
47
+ 'en': "Are you sure you want to delete ",
48
+ 'ru': "Are you sure you want to delete ",
49
+ 'ja': "Are you sure you want to delete ",
50
+ 'ko': "Are you sure you want to delete ",
51
+ };
52
+ var deleteConfirm_i18n_suff = {
53
+ 'zh': "?",
54
+ 'en': "?",
55
+ 'ru': "?",
56
+ 'ja': "?",
57
+ 'ko': "?",
58
+ };
59
+ var deleteConfirm_msg_pref = "Are you sure you want to delete ";
60
+ var deleteConfirm_msg_suff = " ?";
61
+
62
+ var usingLatest_i18n = {
63
+ 'zh': "You are using the latest version!",
64
+ 'en': "You are using the latest version!",
65
+ 'ru': "Вы используете последнюю версию!",
66
+ 'ja': "You are using the latest version!",
67
+ 'ko': "You are using the latest version!",
68
+ };
69
+
70
+ // Is gradio page loaded? Can interact with elements?
71
+ function gradioLoaded(mutations) {
72
+ for (var i = 0; i < mutations.length; i++) {
73
+ if (mutations[i].addedNodes.length) {
74
+ loginUserForm = document.querySelector(".gradio-container > .main > .wrap > .panel > .form")
75
+ gradioContainer = document.querySelector(".gradio-container");
76
+ user_input_tb = document.getElementById('user_input_tb');
77
+ userInfoDiv = document.getElementById("user_info");
78
+ appTitleDiv = document.getElementById("app_title");
79
+ chatbot = document.querySelector('#chuanhu_chatbot');
80
+ chatbotWrap = document.querySelector('#chuanhu_chatbot > .wrapper > .wrap');
81
+ apSwitch = document.querySelector('.apSwitch input[type="checkbox"]');
82
+ updateToast = document.querySelector("#toast-update");
83
+ sendBtn = document.getElementById("submit_btn");
84
+ cancelBtn = document.getElementById("cancel_btn");
85
+ sliders = document.querySelectorAll('input[type="range"]');
86
+
87
+ if (loginUserForm) {
88
+ localStorage.setItem("userLogged", true);
89
+ userLogged = true;
90
+ }
91
+
92
+ if (gradioContainer && apSwitch) { // Is gradioContainer loaded?
93
+ adjustDarkMode();
94
+ }
95
+ if (user_input_tb) { // Is user_input_tb loaded?
96
+ selectHistory();
97
+ }
98
+ if (userInfoDiv && appTitleDiv) { // Are userInfoDiv and appTitleDiv loaded?
99
+ if (!usernameGotten) {
100
+ getUserInfo();
101
+ }
102
+ setTimeout(showOrHideUserInfo(), 2000);
103
+ }
104
+ if (chatbot) { // Is chatbot loaded?
105
+ setChatbotHeight();
106
+ }
107
+ if (chatbotWrap) {
108
+ if (!historyLoaded) {
109
+ loadHistoryHtml();
110
+ }
111
+ setChatbotScroll();
112
+ mObserver.observe(chatbotWrap, { attributes: true, childList: true, subtree: true, characterData: true});
113
+ }
114
+ if (sliders) {
115
+ setSlider();
116
+ }
117
+ if (updateToast) {
118
+ const lastCheckTime = localStorage.getItem('lastCheckTime') || 0;
119
+ const longTimeNoCheck = currentTime - lastCheckTime > 3 * 24 * 60 * 60 * 1000;
120
+ if (longTimeNoCheck && !updateInfoGotten && !isLatestVersion || isLatestVersion && !updateInfoGotten) {
121
+ updateLatestVersion();
122
+ }
123
+ }
124
+ if (cancelBtn) {
125
+ submitObserver.observe(cancelBtn, { attributes: true, characterData: true});
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ function webLocale() {
132
+ //console.log("webLocale", language);
133
+ if (forView_i18n.hasOwnProperty(language)) {
134
+ var forView = forView_i18n[language];
135
+ var forViewStyle = document.createElement('style');
136
+ forViewStyle.innerHTML = '.wrapper>.wrap>.history-message>:last-child::after { content: "' + forView + '"!important; }';
137
+ document.head.appendChild(forViewStyle);
138
+ }
139
+ if (deleteConfirm_i18n_pref.hasOwnProperty(language)) {
140
+ deleteConfirm_msg_pref = deleteConfirm_i18n_pref[language];
141
+ deleteConfirm_msg_suff = deleteConfirm_i18n_suff[language];
142
+ }
143
+ }
144
+
145
+ function showConfirmationDialog(a, file, c) {
146
+ if (file != "") {
147
+ var result = confirm(deleteConfirm_msg_pref + file + deleteConfirm_msg_suff);
148
+ if (result) {
149
+ return [a, file, c];
150
+ }
151
+ }
152
+ return [a, "CANCELED", c];
153
+ }
154
+
155
+ function selectHistory() {
156
+ user_input_ta = user_input_tb.querySelector("textarea");
157
+ if (user_input_ta) {
158
+ observer.disconnect(); // stop observing
159
+ disableSendBtn();
160
+ // listen to keydown event on textarea
161
+ user_input_ta.addEventListener("keydown", function (event) {
162
+ var value = user_input_ta.value.trim();
163
+ // check if pressed key is up/down arrow
164
+ if (event.code === 'ArrowUp' || event.code === 'ArrowDown') {
165
+ // if arrow pressed and input not empty and history doesn't contain value, do nothing
166
+ if (value && key_down_history.indexOf(value) === -1)
167
+ return;
168
+ // prevent default behavior of arrow press
169
+ event.preventDefault();
170
+ var length = key_down_history.length;
171
+ if (length === 0) {
172
+ currentIndex = -1; // if history empty, reset current selected record
173
+ return;
174
+ }
175
+ if (currentIndex === -1) {
176
+ currentIndex = length;
177
+ }
178
+ if (event.code === 'ArrowUp' && currentIndex > 0) {
179
+ currentIndex--;
180
+ user_input_ta.value = key_down_history[currentIndex];
181
+ } else if (event.code === 'ArrowDown' && currentIndex < length - 1) {
182
+ currentIndex++;
183
+ user_input_ta.value = key_down_history[currentIndex];
184
+ }
185
+ user_input_ta.selectionStart = user_input_ta.value.length;
186
+ user_input_ta.selectionEnd = user_input_ta.value.length;
187
+ const input_event = new InputEvent("input", { bubbles: true, cancelable: true });
188
+ user_input_ta.dispatchEvent(input_event);
189
+ } else if (event.code === "Enter") {
190
+ if (value) {
191
+ currentIndex = -1;
192
+ if (key_down_history.indexOf(value) === -1) {
193
+ key_down_history.push(value);
194
+ if (key_down_history.length > MAX_HISTORY_LENGTH) {
195
+ key_down_history.shift();
196
+ }
197
+ }
198
+ }
199
+ }
200
+ });
201
+ }
202
+ }
203
+
204
+ function disableSendBtn() {
205
+ sendBtn.disabled = user_input_ta.value.trim() === '';
206
+ user_input_ta.addEventListener('input', () => {
207
+ sendBtn.disabled = user_input_ta.value.trim() === '';
208
+ });
209
+ }
210
+
211
+ var username = null;
212
+ function getUserInfo() {
213
+ if (usernameGotten) {
214
+ return;
215
+ }
216
+ userLogged = localStorage.getItem('userLogged');
217
+ if (userLogged) {
218
+ username = userInfoDiv.innerText;
219
+ if (username) {
220
+ if (username.includes("getting user info...")) {
221
+ setTimeout(getUserInfo, 500);
222
+ return;
223
+ } else if (username === " ") {
224
+ localStorage.removeItem("username");
225
+ localStorage.removeItem("userLogged")
226
+ userLogged = false;
227
+ usernameGotten = true;
228
+ return;
229
+ } else {
230
+ username = username.match(/User:\s*(.*)/)[1] || username;
231
+ localStorage.setItem("username", username);
232
+ usernameGotten = true;
233
+ clearHistoryHtml();
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ function toggleUserInfoVisibility(shouldHide) {
240
+ if (userInfoDiv) {
241
+ if (shouldHide) {
242
+ userInfoDiv.classList.add("hideK");
243
+ } else {
244
+ userInfoDiv.classList.remove("hideK");
245
+ }
246
+ }
247
+ }
248
+ function showOrHideUserInfo() {
249
+ // bind mouse/touch events to show/hide user info
250
+ appTitleDiv.addEventListener("mouseenter", function () {
251
+ toggleUserInfoVisibility(false);
252
+ });
253
+ userInfoDiv.addEventListener("mouseenter", function () {
254
+ toggleUserInfoVisibility(false);
255
+ });
256
+ sendBtn.addEventListener("mouseenter", function () {
257
+ toggleUserInfoVisibility(false);
258
+ });
259
+
260
+ appTitleDiv.addEventListener("mouseleave", function () {
261
+ toggleUserInfoVisibility(true);
262
+ });
263
+ userInfoDiv.addEventListener("mouseleave", function () {
264
+ toggleUserInfoVisibility(true);
265
+ });
266
+ sendBtn.addEventListener("mouseleave", function () {
267
+ toggleUserInfoVisibility(true);
268
+ });
269
+
270
+ appTitleDiv.ontouchstart = function () {
271
+ toggleUserInfoVisibility(false);
272
+ };
273
+ userInfoDiv.ontouchstart = function () {
274
+ toggleUserInfoVisibility(false);
275
+ };
276
+ sendBtn.ontouchstart = function () {
277
+ toggleUserInfoVisibility(false);
278
+ };
279
+
280
+ appTitleDiv.ontouchend = function () {
281
+ setTimeout(function () {
282
+ toggleUserInfoVisibility(true);
283
+ }, 3000);
284
+ };
285
+ userInfoDiv.ontouchend = function () {
286
+ setTimeout(function () {
287
+ toggleUserInfoVisibility(true);
288
+ }, 3000);
289
+ };
290
+ sendBtn.ontouchend = function () {
291
+ setTimeout(function () {
292
+ toggleUserInfoVisibility(true);
293
+ }, 3000); // 1 sec delay to hide user info
294
+ };
295
+
296
+ // hide user info after 2 seconds
297
+ setTimeout(function () {
298
+ toggleUserInfoVisibility(true);
299
+ }, 2000);
300
+ }
301
+
302
+ function toggleDarkMode(isEnabled) {
303
+ if (isEnabled) {
304
+ document.body.classList.add("dark");
305
+ document.body.style.setProperty("background-color", "var(--neutral-950)", "important");
306
+ } else {
307
+ document.body.classList.remove("dark");
308
+ document.body.style.backgroundColor = "";
309
+ }
310
+ }
311
+ function adjustDarkMode() {
312
+ const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)");
313
+
314
+ // set initial state based on current color scheme or saved theme
315
+ let isDarkMode = localStorage.getItem('darkMode') === 'true' || darkModeQuery.matches;
316
+ apSwitch.checked = isDarkMode;
317
+ toggleDarkMode(isDarkMode);
318
+ // listen for changes to color scheme
319
+ darkModeQuery.addEventListener("change", (e) => {
320
+ isDarkMode = e.matches;
321
+ localStorage.setItem('darkMode', isDarkMode);
322
+ apSwitch.checked = isDarkMode;
323
+ toggleDarkMode(isDarkMode);
324
+ });
325
+ // apSwitch = document.querySelector(".apSwitch input[type="checkbox"]");
326
+ apSwitch.addEventListener("change", (e) => {
327
+ isDarkMode = e.target.checked;
328
+ localStorage.setItem('darkMode', isDarkMode);
329
+ toggleDarkMode(isDarkMode);
330
+ });
331
+ }
332
+
333
+ function setChatbotHeight() {
334
+ const screenWidth = window.innerWidth;
335
+ const statusDisplay = document.querySelector('#status_display');
336
+ const statusDisplayHeight = statusDisplay ? statusDisplay.offsetHeight : 0;
337
+ const vh = window.innerHeight * 0.01;
338
+ document.documentElement.style.setProperty('--vh', `${vh}px`);
339
+ if (isInIframe) {
340
+ chatbot.style.height = `700px`;
341
+ chatbotWrap.style.maxHeight = `calc(700px - var(--line-sm) * 1rem - 2 * var(--block-label-margin))`
342
+ } else {
343
+ if (screenWidth <= 320) {
344
+ chatbot.style.height = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 150}px)`;
345
+ chatbotWrap.style.maxHeight = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 150}px - var(--line-sm) * 1rem - 2 * var(--block-label-margin))`;
346
+ } else if (screenWidth <= 499) {
347
+ chatbot.style.height = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 100}px)`;
348
+ chatbotWrap.style.maxHeight = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 100}px - var(--line-sm) * 1rem - 2 * var(--block-label-margin))`;
349
+ } else {
350
+ chatbot.style.height = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 160}px)`;
351
+ chatbotWrap.style.maxHeight = `calc(var(--vh, 1vh) * 100 - ${statusDisplayHeight + 160}px - var(--line-sm) * 1rem - 2 * var(--block-label-margin))`;
352
+ }
353
+ }
354
+ }
355
+ function setChatbotScroll() {
356
+ var scrollHeight = chatbotWrap.scrollHeight;
357
+ chatbotWrap.scrollTo(0,scrollHeight)
358
+ }
359
+ var rangeInputs = null;
360
+ var numberInputs = null;
361
+ function setSlider() {
362
+ rangeInputs = document.querySelectorAll('input[type="range"]');
363
+ numberInputs = document.querySelectorAll('input[type="number"]')
364
+ setSliderRange();
365
+ rangeInputs.forEach(rangeInput => {
366
+ rangeInput.addEventListener('input', setSliderRange);
367
+ });
368
+ numberInputs.forEach(numberInput => {
369
+ numberInput.addEventListener('input', setSliderRange);
370
+ })
371
+ }
372
+ function setSliderRange() {
373
+ var range = document.querySelectorAll('input[type="range"]');
374
+ range.forEach(range => {
375
+ range.style.backgroundSize = (range.value - range.min) / (range.max - range.min) * 100 + '% 100%';
376
+ });
377
+ }
378
+
379
+ function addChuanhuButton(botElement) {
380
+ var rawMessage = null;
381
+ var mdMessage = null;
382
+ rawMessage = botElement.querySelector('.raw-message');
383
+ mdMessage = botElement.querySelector('.md-message');
384
+ if (!rawMessage) {
385
+ var buttons = botElement.querySelectorAll('button.chuanhu-btn');
386
+ for (var i = 0; i < buttons.length; i++) {
387
+ buttons[i].parentNode.removeChild(buttons[i]);
388
+ }
389
+ return;
390
+ }
391
+ var oldCopyButton = null;
392
+ var oldToggleButton = null;
393
+ oldCopyButton = botElement.querySelector('button.copy-bot-btn');
394
+ oldToggleButton = botElement.querySelector('button.toggle-md-btn');
395
+ if (oldCopyButton) oldCopyButton.remove();
396
+ if (oldToggleButton) oldToggleButton.remove();
397
+
398
+ // Copy bot button
399
+ var copyButton = document.createElement('button');
400
+ copyButton.classList.add('chuanhu-btn');
401
+ copyButton.classList.add('copy-bot-btn');
402
+ copyButton.setAttribute('aria-label', 'Copy');
403
+ copyButton.innerHTML = copyIcon;
404
+ copyButton.addEventListener('click', async () => {
405
+ const textToCopy = rawMessage.innerText;
406
+ try {
407
+ if ("clipboard" in navigator) {
408
+ await navigator.clipboard.writeText(textToCopy);
409
+ copyButton.innerHTML = copiedIcon;
410
+ setTimeout(() => {
411
+ copyButton.innerHTML = copyIcon;
412
+ }, 1500);
413
+ } else {
414
+ const textArea = document.createElement("textarea");
415
+ textArea.value = textToCopy;
416
+ document.body.appendChild(textArea);
417
+ textArea.select();
418
+ try {
419
+ document.execCommand('copy');
420
+ copyButton.innerHTML = copiedIcon;
421
+ setTimeout(() => {
422
+ copyButton.innerHTML = copyIcon;
423
+ }, 1500);
424
+ } catch (error) {
425
+ console.error("Error copying: ", error);
426
+ }
427
+ document.body.removeChild(textArea);
428
+ }
429
+ } catch (error) {
430
+ console.error("Error copying: ", error);
431
+ }
432
+ });
433
+ botElement.appendChild(copyButton);
434
+
435
+ // Toggle button
436
+ var toggleButton = document.createElement('button');
437
+ toggleButton.classList.add('chuanhu-btn');
438
+ toggleButton.classList.add('toggle-md-btn');
439
+ toggleButton.setAttribute('aria-label', 'Toggle');
440
+ var renderMarkdown = mdMessage.classList.contains('hideM');
441
+ toggleButton.innerHTML = renderMarkdown ? mdIcon : rawIcon;
442
+ toggleButton.addEventListener('click', () => {
443
+ renderMarkdown = mdMessage.classList.contains('hideM');
444
+ if (renderMarkdown){
445
+ renderMarkdownText(botElement);
446
+ toggleButton.innerHTML=rawIcon;
447
+ } else {
448
+ removeMarkdownText(botElement);
449
+ toggleButton.innerHTML=mdIcon;
450
+ }
451
+ });
452
+ botElement.insertBefore(toggleButton, copyButton);
453
+ }
454
+
455
+ function renderMarkdownText(message) {
456
+ var mdDiv = message.querySelector('.md-message');
457
+ if (mdDiv) mdDiv.classList.remove('hideM');
458
+ var rawDiv = message.querySelector('.raw-message');
459
+ if (rawDiv) rawDiv.classList.add('hideM');
460
+ }
461
+ function removeMarkdownText(message) {
462
+ var rawDiv = message.querySelector('.raw-message');
463
+ if (rawDiv) rawDiv.classList.remove('hideM');
464
+ var mdDiv = message.querySelector('.md-message');
465
+ if (mdDiv) mdDiv.classList.add('hideM');
466
+ }
467
+
468
+ let timeoutId;
469
+ let isThrottled = false;
470
+ var mmutation
471
+ // Observe changes inside DOM
472
+ var mObserver = new MutationObserver(function (mutationsList) {
473
+ for (mmutation of mutationsList) {
474
+ if (mmutation.type === 'childList') {
475
+ for (var node of mmutation.addedNodes) {
476
+ if (node.nodeType === 1 && node.classList.contains('message')) {
477
+ saveHistoryHtml();
478
+ disableSendBtn();
479
+ document.querySelectorAll('#chuanhu_chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
480
+ }
481
+ }
482
+ for (var node of mmutation.removedNodes) {
483
+ if (node.nodeType === 1 && node.classList.contains('message')) {
484
+ saveHistoryHtml();
485
+ disableSendBtn();
486
+ document.querySelectorAll('#chuanhu_chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
487
+ }
488
+ }
489
+ } else if (mmutation.type === 'attributes') {
490
+ if (isThrottled) break; // avoid re-rendering too much
491
+ isThrottled = true;
492
+ clearTimeout(timeoutId);
493
+ timeoutId = setTimeout(() => {
494
+ isThrottled = false;
495
+ document.querySelectorAll('#chuanhu_chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
496
+ saveHistoryHtml();
497
+ disableSendBtn();
498
+ }, 1500);
499
+ }
500
+ }
501
+ });
502
+ // mObserver.observe(targetNode, { attributes: true, childList: true, subtree: true, characterData: true});
503
+
504
+ var submitObserver = new MutationObserver(function (mutationsList) {
505
+ document.querySelectorAll('#chuanhu_chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
506
+ saveHistoryHtml();
507
+ });
508
+
509
+ var loadhistorytime = 0; // for debugging
510
+ function saveHistoryHtml() {
511
+ var historyHtml = document.querySelector('#chuanhu_chatbot>.wrapper>.wrap');
512
+ if (!historyHtml) return; // no history, do nothing
513
+ localStorage.setItem('chatHistory', historyHtml.innerHTML);
514
+ // console.log("History saved")
515
+ historyLoaded = false;
516
+ }
517
+ function loadHistoryHtml() {
518
+ var historyHtml = localStorage.getItem('chatHistory');
519
+ if (!historyHtml) {
520
+ historyLoaded = true;
521
+ return; // no history, do nothing
522
+ }
523
+ userLogged = localStorage.getItem('userLogged');
524
+ if (userLogged){
525
+ historyLoaded = true;
526
+ return; // user logged in, do nothing
527
+ }
528
+ if (!historyLoaded) {
529
+ var tempDiv = document.createElement('div');
530
+ tempDiv.innerHTML = historyHtml;
531
+ var buttons = tempDiv.querySelectorAll('button.chuanhu-btn');
532
+ var gradioCopyButtons = tempDiv.querySelectorAll('button.copy_code_button');
533
+ for (var i = 0; i < buttons.length; i++) {
534
+ buttons[i].parentNode.removeChild(buttons[i]);
535
+ }
536
+ for (var i = 0; i < gradioCopyButtons.length; i++) {
537
+ gradioCopyButtons[i].parentNode.removeChild(gradioCopyButtons[i]);
538
+ }
539
+ var fakeHistory = document.createElement('div');
540
+ fakeHistory.classList.add('history-message');
541
+ fakeHistory.innerHTML = tempDiv.innerHTML;
542
+ webLocale();
543
+ chatbotWrap.insertBefore(fakeHistory, chatbotWrap.firstChild);
544
+ // var fakeHistory = document.createElement('div');
545
+ // fakeHistory.classList.add('history-message');
546
+ // fakeHistory.innerHTML = historyHtml;
547
+ // chatbotWrap.insertBefore(fakeHistory, chatbotWrap.firstChild);
548
+ historyLoaded = true;
549
+ console.log("History loaded");
550
+ loadhistorytime += 1; // for debugging
551
+ } else {
552
+ historyLoaded = false;
553
+ }
554
+ }
555
+ function clearHistoryHtml() {
556
+ localStorage.removeItem("chatHistory");
557
+ historyMessages = chatbotWrap.querySelector('.history-message');
558
+ if (historyMessages) {
559
+ chatbotWrap.removeChild(historyMessages);
560
+ console.log("History cleared");
561
+ }
562
+ }
563
+
564
+ var showingUpdateInfo = false;
565
+ async function getLatestRelease() {
566
+ try {
567
+ const response = await fetch('https://api.github.com/repos/gaizhenbiao/chuanhuchatgpt/releases/latest');
568
+ if (!response.ok) {
569
+ console.log(`Error: ${response.status} - ${response.statusText}`);
570
+ updateInfoGotten = true;
571
+ return null;
572
+ }
573
+ const data = await response.json();
574
+ updateInfoGotten = true;
575
+ return data;
576
+ } catch (error) {
577
+ console.log(`Error: ${error}`);
578
+ updateInfoGotten = true;
579
+ return null;
580
+ }
581
+ }
582
+ async function updateLatestVersion() {
583
+ const currentVersionElement = document.getElementById('current-version');
584
+ const latestVersionElement = document.getElementById('latest-version-title');
585
+ const releaseNoteElement = document.getElementById('release-note-content');
586
+ const currentVersion = currentVersionElement.textContent;
587
+ const versionTime = document.getElementById('version-time').innerText;
588
+ const localVersionTime = versionTime !== "unknown" ? (new Date(versionTime)).getTime() : 0;
589
+ updateInfoGotten = true; // only execute once regardless of success to avoid exceeding API limit...
590
+ try {
591
+ const data = await getLatestRelease();
592
+ const releaseNote = data.body;
593
+ if (releaseNote) {
594
+ releaseNoteElement.innerHTML = marked.parse(releaseNote);
595
+ }
596
+ const latestVersion = data.tag_name;
597
+ const latestVersionTime = (new Date(data.created_at)).getTime();
598
+ if (latestVersionTime) {
599
+ if (localVersionTime < latestVersionTime) {
600
+ latestVersionElement.textContent = latestVersion;
601
+ console.log(`New version ${latestVersion} found!`);
602
+ if (!isInIframe) {openUpdateToast();}
603
+ } else {
604
+ noUpdate();
605
+ }
606
+ currentTime = new Date().getTime();
607
+ localStorage.setItem('lastCheckTime', currentTime);
608
+ }
609
+ } catch (error) {
610
+ console.error(error);
611
+ }
612
+ }
613
+ function getUpdate() {
614
+ window.open('https://github.com/gaizhenbiao/chuanhuchatgpt/releases/latest', '_blank');
615
+ closeUpdateToast();
616
+ }
617
+ function cancelUpdate() {
618
+ closeUpdateToast();
619
+ }
620
+ function openUpdateToast() {
621
+ showingUpdateInfo = true;
622
+ setUpdateWindowHeight();
623
+ }
624
+ function closeUpdateToast() {
625
+ updateToast.style.setProperty('top', '-500px');
626
+ showingUpdateInfo = false;
627
+ }
628
+ function manualCheckUpdate() {
629
+ openUpdateToast();
630
+ updateLatestVersion();
631
+ currentTime = new Date().getTime();
632
+ localStorage.setItem('lastCheckTime', currentTime);
633
+ }
634
+ function noUpdate() {
635
+ localStorage.setItem('isLatestVersion', 'true');
636
+ isLatestVersion = true;
637
+ const versionInfoElement = document.getElementById('version-info-title');
638
+ const releaseNoteWrap = document.getElementById('release-note-wrap');
639
+ const gotoUpdateBtn = document.getElementById('goto-update-btn');
640
+ const closeUpdateBtn = document.getElementById('close-update-btn');
641
+
642
+ versionInfoElement.textContent = usingLatest_i18n.hasOwnProperty(language) ? usingLatest_i18n[language] : usingLatest_i18n['ru'];
643
+ releaseNoteWrap.style.setProperty('display', 'none');
644
+ gotoUpdateBtn.classList.add('hideK');
645
+ closeUpdateBtn.classList.remove('hideK');
646
+ }
647
+ function setUpdateWindowHeight() {
648
+ if (!showingUpdateInfo) {return;}
649
+ const scrollPosition = window.scrollY;
650
+ // const originalTop = updateToast.style.getPropertyValue('top');
651
+ const resultTop = scrollPosition - 20 + 'px';
652
+ updateToast.style.setProperty('top', resultTop);
653
+ }
654
+
655
+ // Observe changes in page
656
+ var observer = new MutationObserver(function (mutations) {
657
+ gradioLoaded(mutations);
658
+ });
659
+ observer.observe(targetNode, { childList: true, subtree: true });
660
+
661
+ // Observe changes in page
662
+ window.addEventListener("DOMContentLoaded", function () {
663
+ isInIframe = (window.self !== window.top);
664
+ historyLoaded = false;
665
+ });
666
+ window.addEventListener('resize', setChatbotHeight);
667
+ window.addEventListener('scroll', function(){setChatbotHeight();setUpdateWindowHeight();});
668
+ window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", adjustDarkMode);
669
+
670
+ // console surprise
671
+ var styleTitle1 = `
672
+ font-size: 16px;
673
+ font-family: ui-monospace,monospace;
674
+ color: rgb(244,167,89);
675
+ `
676
+ var styleDesc1 = `
677
+ font-size: 12px;
678
+ font-family: ui-monospace,monospace;
679
+ `
680
+ function makeML(str) {
681
+ let l = new String(str)
682
+ l = l.substring(l.indexOf("/*") + 3, l.lastIndexOf("*/"))
683
+ return l
684
+ }
685
+ let ChuanhuInfo = function () {
686
+ /*
687
+ ________ __ ________ __
688
+ / ____/ /_ __ ______ _____ / /_ __ __ / ____/ /_ ____ _/ /_
689
+ / / / __ \/ / / / __ `/ __ \/ __ \/ / / / / / / __ \/ __ `/ __/
690
+ / /___/ / / / /_/ / /_/ / / / / / / / /_/ / / /___/ / / / /_/ / /_
691
+ \____/_/ /_/\__,_/\__,_/_/ /_/_/ /_/\__,_/ \____/_/ /_/\__,_/\__/
692
+
693
+ Chuanhu Chat - Graphical interface for ChatGPT API and many LLMs
694
+ */
695
+ }
696
+ let description = `
697
+ `
698
+ console.log(`%c${makeML(ChuanhuInfo)}`,styleTitle1)
699
+ console.log(`%c${description}`, styleDesc1)
700
+
701
+ // svg icon codes
702
+ const copyIcon = '<span><svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height=".8em" width=".8em" xmlns="http://www.w3.org/2000/svg"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg></span>';
703
+ const copiedIcon = '<span><svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height=".8em" width=".8em" xmlns="http://www.w3.org/2000/svg"><polyline points="20 6 9 17 4 12"></polyline></svg></span>';
704
+ const mdIcon = '<span><svg stroke="currentColor" fill="none" stroke-width="1" viewBox="0 0 14 18" stroke-linecap="round" stroke-linejoin="round" height=".8em" width=".8em" xmlns="http://www.w3.org/2000/svg"><g transform-origin="center" transform="scale(0.85)"><path d="M1.5,0 L12.5,0 C13.3284271,-1.52179594e-16 14,0.671572875 14,1.5 L14,16.5 C14,17.3284271 13.3284271,18 12.5,18 L1.5,18 C0.671572875,18 1.01453063e-16,17.3284271 0,16.5 L0,1.5 C-1.01453063e-16,0.671572875 0.671572875,1.52179594e-16 1.5,0 Z" stroke-width="1.8"></path><line x1="3.5" y1="3.5" x2="10.5" y2="3.5"></line><line x1="3.5" y1="6.5" x2="8" y2="6.5"></line></g><path d="M4,9 L10,9 C10.5522847,9 11,9.44771525 11,10 L11,13.5 C11,14.0522847 10.5522847,14.5 10,14.5 L4,14.5 C3.44771525,14.5 3,14.0522847 3,13.5 L3,10 C3,9.44771525 3.44771525,9 4,9 Z" stroke="none" fill="currentColor"></path></svg></span>';
705
+ const rawIcon = '<span><svg stroke="currentColor" fill="none" stroke-width="1.8" viewBox="0 0 18 14" stroke-linecap="round" stroke-linejoin="round" height=".8em" width=".8em" xmlns="http://www.w3.org/2000/svg"><g transform-origin="center" transform="scale(0.85)"><polyline points="4 3 0 7 4 11"></polyline><polyline points="14 3 18 7 14 11"></polyline><line x1="12" y1="0" x2="6" y2="14"></line></g></svg></span>';
assets/external-scripts.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+
2
+ // external javascript here
assets/favicon.ico ADDED
assets/html/appearance_switcher.html ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <div class="switch_checkbox" id="apSwitch">
2
+ <label class="apSwitch">
3
+ <input type="checkbox" id="apSwitch_checkbox" data-testid="checkbox" />
4
+ <span class="apSwitch_span">{label}</span>
5
+ </label>
6
+ </div>
assets/html/billing_info.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ <b>{label}</b>
2
+ <div class="progress-bar">
3
+ <div class="progress" style="width: {usage_percent}%;">
4
+ <span class="progress-text">{usage_percent}%</span>
5
+ </div>
6
+ </div>
7
+ <div style="display: flex; justify-content: space-between;">
8
+ <span>${rounded_usage}</span><span>${usage_limit}</span>
9
+ </div>
assets/html/footer.html ADDED
@@ -0,0 +1 @@
 
 
1
+ <div class="versions">{versions}</div>
assets/html/update.html ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div id="toast-update">
2
+ <div id="check-chuanhu-update">
3
+ <p style="display:none">
4
+ <span id="current-version">{current_version}</span>
5
+ <span id="version-time">{version_time}</span>
6
+ </p>
7
+ <p id="version-info-title">
8
+ Latest Version: <a href="https://github.com/gaizhenbiao/chuanhuchatgpt/releases/latest" target="_blank"
9
+ id="latest-version-title" style="text-decoration: none;">getting latest version...</a>
10
+ </p>
11
+ <div id="release-note-wrap">
12
+ <div class="release-note-content" id="release-note-content">
13
+ Getting Release Note...
14
+ </div>
15
+ </div>
16
+ <div id="goto-update-btn" class="btn-update-group">
17
+ <button class="btn-update lg secondary svelte-1ipelgc" id="cancel-button" onclick="cancelUpdate()">{cancel_btn}</button>
18
+ <button class="btn-update lg primary svelte-1ipelgc" id="update-button" onclick="getUpdate()">{update_btn}</button>
19
+ </div>
20
+ <div id="close-update-btn" class="btn-update-group hideK">
21
+ <button class="btn-update lg secondary svelte-1jrzxu" id="update-button" onclick="getUpdate()">{seenew_btn}</button>
22
+ <button class="btn-update lg primary svelte-1jrzxu" id="cancel-button" onclick="cancelUpdate()">{ok_btn}</button>
23
+ </div>
24
+ </div>
25
+ </div>
autoinstall_linux.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Обновить систему
4
+ sudo apt-get update -y
5
+
6
+ # Установить python3, pip, git и зависимости
7
+ sudo apt-get install -y python3-full python3-venv python3-pip python-is-python3 git build-essential libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-dev
8
+
9
+ # Клонировать репозиторий
10
+ git clone https://github.com/Em1tSan/NeuroGPT.git
11
+ cd NeuroGPT
12
+
13
+ # Обновить репозиторий
14
+ git checkout main
15
+ git fetch --all
16
+ git reset --hard origin/main
17
+ git pull
18
+
19
+ # Проверка версии Python
20
+ version=$(python3 --version)
21
+ version=${version:7}
22
+ if [[ "$version" < "3.9.0" ]]; then
23
+ echo "Your version of Python ${version} is not supported. Please install Python 3.10.X"
24
+ exit 1
25
+ elif [[ "$version" > "3.11.14" ]]; then
26
+ echo "Your version of Python ${version} is not supported. Please install Python 3.10.X"
27
+ exit 1
28
+ fi
29
+
30
+ # Создание и активация виртуальной среды
31
+ python3 -m venv venv
32
+ . venv/bin/activate
33
+
34
+ # Установка необходимых пакетов
35
+ python3 -m pip install --upgrade pip
36
+ python3 -m pip install -U setuptools
37
+ python3 -m pip install -r requirements.txt
38
+
39
+ # Проверка и загрузка моделей Spacy при необходимости
40
+ if [ ! -d "venv/lib/python3.10/site-packages/en_core_web_sm" ]; then
41
+ echo "English language model not found, downloading..."
42
+ python3 -m spacy download en_core_web_sm
43
+ fi
44
+
45
+ if [ ! -d "venv/lib/python3.10/site-packages/zh_core_web_sm" ]; then
46
+ echo "Chinese language model not found, downloading..."
47
+ python3 -m spacy download zh_core_web_sm
48
+ fi
49
+
50
+ if [ ! -d "venv/lib/python3.10/site-packages/ru_core_news_sm" ]; then
51
+ echo "Russian language model not found, downloading..."
52
+ python3 -m spacy download ru_core_news_sm
53
+ fi
54
+
55
+ echo "Completed."
56
+
57
+ # Определение языка операционной системы и запуск соответствующего скрипта
58
+ language=$(locale | grep LANG= | cut -d "=" -f2 | cut -d "_" -f1)
59
+ if [ "$language" = "ru" ]; then
60
+ python3 webui_ru.py
61
+ else
62
+ python3 webui_en.py
63
+ fi
backend/auto_proxy.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import requests
3
+ import time
4
+ import threading
5
+ import socket
6
+
7
+
8
+ def fetch_proxies():
9
+ """Fetch a list of proxy servers from proxyscrape.com.
10
+
11
+ Returns:
12
+ list: A list of proxy servers in the format "IP:Port".
13
+ """
14
+ url = "https://www.proxy-list.download/api/v1/get?type=https"
15
+ response = requests.get(url)
16
+ if response.status_code == 200:
17
+ return response.text.split("\r\n")[:-1]
18
+ print(f"Error fetching proxies: {response.status_code}")
19
+ return []
20
+
21
+
22
+ def test_proxy(proxy, prompt, timeout):
23
+ """Test the given proxy server with a specified prompt and timeout.
24
+
25
+ Args:
26
+ proxy (str): The proxy server in the format "IP:Port".
27
+ prompt (str): The test prompt to be used for testing.
28
+ timeout (int): The maximum time in seconds allowed for the test.
29
+ """
30
+ try:
31
+ # Split IP and Port
32
+ ip, port = proxy.split(':')
33
+
34
+ # Create a socket object
35
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36
+
37
+ # Start the timer
38
+ start_time = time.time()
39
+
40
+ # Connect to the proxy server
41
+ sock.connect((ip, int(port)))
42
+
43
+ # Stop the timer and calculate the elapsed time
44
+ end_time = time.time()
45
+ elapsed_time = end_time - start_time
46
+
47
+ # Print the elapsed time
48
+ #print(f"Elapsed time: {elapsed_time} seconds")
49
+
50
+ # Close the socket
51
+ sock.close()
52
+
53
+ # Check if the elapsed time is below the timeout
54
+ if elapsed_time < timeout:
55
+ print(f"proxy: {proxy} ✅ | Elapsed time: {elapsed_time} seconds")
56
+ add_working_proxy(proxy)
57
+ except Exception as e:
58
+ pass
59
+
60
+
61
+ def add_working_proxy(proxy):
62
+ """Add a working proxy server to the global working_proxies list.
63
+
64
+ Args:
65
+ proxy (str): The proxy server in the format "IP:Port".
66
+ """
67
+ global working_proxies
68
+ working_proxies.append(proxy)
69
+
70
+
71
+ def remove_proxy(proxy):
72
+ """Remove a proxy server from the global working_proxies list.
73
+
74
+ Args:
75
+ proxy (str): The proxy server in the format "IP:Port".
76
+ """
77
+ global working_proxies
78
+ if proxy in working_proxies:
79
+ working_proxies.remove(proxy)
80
+
81
+
82
+ def get_working_proxies(prompt, timeout=5):
83
+ """Fetch and test proxy servers, adding working proxies to the global working_proxies list.
84
+
85
+ Args:
86
+ prompt (str): The test prompt to be used for testing.
87
+ timeout (int, optional): The maximum time in seconds allowed for testing. Defaults to 5.
88
+ """
89
+ proxy_list = fetch_proxies()
90
+ threads = []
91
+
92
+ for proxy in proxy_list:
93
+ thread = threading.Thread(target=test_proxy, args=(
94
+ proxy, prompt, timeout))
95
+ threads.append(thread)
96
+ thread.start()
97
+
98
+ for t in threads:
99
+ t.join(timeout)
100
+
101
+
102
+ def update_working_proxies():
103
+ """Continuously update the global working_proxies list with working proxy servers."""
104
+ global working_proxies
105
+ test_prompt = "What is the capital of France?"
106
+
107
+ while True:
108
+ working_proxies = [] # Clear the list before updating
109
+ get_working_proxies(test_prompt)
110
+ print('proxies updated')
111
+ time.sleep(1800) # Update proxies list every 30 minutes
112
+
113
+
114
+ def get_random_proxy():
115
+ """Get a random working proxy server from the global working_proxies list.
116
+
117
+ Returns:
118
+ str: A random working proxy server in the format "IP:Port".
119
+ """
120
+ global working_proxies
121
+ return random.choice(working_proxies)
backend/backend.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import random
5
+ import string
6
+ import socket
7
+ import nest_asyncio
8
+
9
+ import requests
10
+ from typing import Any
11
+
12
+ from flask import Flask, request, jsonify, Response
13
+ from flask_cors import CORS
14
+ import logging
15
+ from .embedding_processing import embedding_processing
16
+
17
+ import g4f
18
+ from g4f import ChatCompletion, Provider, BaseProvider, models
19
+ from g4f.models import ModelUtils
20
+
21
+ nest_asyncio.apply()
22
+
23
+ app = Flask(__name__)
24
+ CORS(app)
25
+
26
+ LOG = logging.getLogger(__name__)
27
+ embedding_proc = embedding_processing()
28
+
29
+ @app.route("/chat/completions", methods=['POST'])
30
+ @app.route("/v1/chat/completions", methods=['POST'])
31
+ @app.route("/", methods=['POST'])
32
+ def chat_completions():
33
+ request_data = request.get_json()
34
+ model = request_data.get('model', 'gpt-3.5-turbo').replace("neuro-", "")
35
+ messages = request_data.get('messages')
36
+ stream = request_data.get('stream', False)
37
+ streaming_ = request_data.get('stream', False)
38
+ temperature = request_data.get('temperature', 1.0)
39
+ top_p = request_data.get('top_p', 1.0)
40
+ max_tokens = request_data.get('max_tokens', 1024)
41
+
42
+ response = ChatCompletion.create(model=model, stream=stream, messages=messages, temperature=temperature, top_p=top_p, max_tokens=max_tokens, system_prompt="")
43
+
44
+ completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=28))
45
+ completion_timestamp = int(time.time())
46
+
47
+ if not streaming_:
48
+ completion_timestamp = int(time.time())
49
+ completion_id = ''.join(random.choices(
50
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', k=28))
51
+
52
+ return {
53
+ "id": f"chatcmpl-{completion_id}",
54
+ "object": "chat.completion",
55
+ "created": completion_timestamp,
56
+ "model": model,
57
+ "choices": [
58
+ {
59
+ "index": 0,
60
+ "message": {
61
+ "role": "assistant",
62
+ "content": response,
63
+ },
64
+ "finish_reason": "stop",
65
+ }
66
+ ],
67
+ "usage": {
68
+ "prompt_tokens": None,
69
+ "completion_tokens": None,
70
+ "total_tokens": None,
71
+ },
72
+ }
73
+
74
+ def streaming():
75
+ for chunk in response:
76
+ completion_data = {
77
+ 'id': f'chatcmpl-{completion_id}',
78
+ 'object': 'chat.completion.chunk',
79
+ 'created': completion_timestamp,
80
+ 'model': model,
81
+ 'choices': [
82
+ {
83
+ 'index': 0,
84
+ 'delta': {
85
+ 'content': chunk,
86
+ },
87
+ 'finish_reason': None,
88
+ }
89
+ ],
90
+ }
91
+
92
+ content = json.dumps(completion_data, separators=(',', ':'))
93
+ yield f'data: {content}\n\n'
94
+ time.sleep(0.05)
95
+
96
+ end_completion_data: dict[str, Any] = {
97
+ 'id': f'chatcmpl-{completion_id}',
98
+ 'object': 'chat.completion.chunk',
99
+ 'created': completion_timestamp,
100
+ 'model': model,
101
+ 'choices': [
102
+ {
103
+ 'index': 0,
104
+ 'delta': {},
105
+ 'finish_reason': 'stop',
106
+ }
107
+ ],
108
+ }
109
+ content = json.dumps(end_completion_data, separators=(',', ':'))
110
+ yield f'data: {content}\n\n'
111
+
112
+ return app.response_class(streaming(), mimetype='text/event-stream')
113
+
114
+ @app.route("/engines/text-embedding-ada-002/embeddings", methods=["POST"])
115
+ @app.route("/engines/text-similarity-davinci-001/embeddings", methods=["POST"])
116
+ @app.route('/v1/embeddings', methods=['POST'])
117
+ @app.route('/embeddings', methods=['POST'])
118
+ def create_embedding():
119
+ j_input = request.get_json()
120
+ #model = embedding_processing()
121
+ embedding = embedding_proc.embedding(text_list=j_input['input'])
122
+ log_event()
123
+ return jsonify(
124
+ embedding
125
+ )
126
+
127
+ def log_event():
128
+ LOG.info('served')
129
+
130
+ @app.route("/v1/dashboard/billing/subscription", methods=['GET'])
131
+ @app.route("/dashboard/billing/subscription", methods=['GET'])
132
+ def billing_subscription():
133
+ return jsonify({
134
+ "object": "billing_subscription",
135
+ "has_payment_method": True,
136
+ "canceled": False,
137
+ "canceled_at": None,
138
+ "delinquent": None,
139
+ "access_until": 2556028800,
140
+ "soft_limit": 6944500,
141
+ "hard_limit": 166666666,
142
+ "system_hard_limit": 166666666,
143
+ "soft_limit_usd": 416.67,
144
+ "hard_limit_usd": 9999.99996,
145
+ "system_hard_limit_usd": 9999.99996,
146
+ "plan": {
147
+ "title": "Pay-as-you-go",
148
+ "id": "payg"
149
+ },
150
+ "primary": True,
151
+ "account_name": "OpenAI",
152
+ "po_number": None,
153
+ "billing_email": None,
154
+ "tax_ids": None,
155
+ "billing_address": {
156
+ "city": "New York",
157
+ "line1": "OpenAI",
158
+ "country": "US",
159
+ "postal_code": "NY10031"
160
+ },
161
+ "business_address": None
162
+ }
163
+ )
164
+
165
+
166
+ @app.route("/v1/dashboard/billing/usage", methods=['GET'])
167
+ @app.route("/dashboard/billing/usage", methods=['GET'])
168
+ def billing_usage():
169
+ return jsonify({
170
+ "object": "list",
171
+ "daily_costs": [
172
+ {
173
+ "timestamp": time.time(),
174
+ "line_items": [
175
+ {
176
+ "name": "GPT-4",
177
+ "cost": 0.0
178
+ },
179
+ {
180
+ "name": "Chat models",
181
+ "cost": 1.01
182
+ },
183
+ {
184
+ "name": "InstructGPT",
185
+ "cost": 0.0
186
+ },
187
+ {
188
+ "name": "Fine-tuning models",
189
+ "cost": 0.0
190
+ },
191
+ {
192
+ "name": "Embedding models",
193
+ "cost": 0.0
194
+ },
195
+ {
196
+ "name": "Image models",
197
+ "cost": 16.0
198
+ },
199
+ {
200
+ "name": "Audio models",
201
+ "cost": 0.0
202
+ }
203
+ ]
204
+ }
205
+ ],
206
+ "total_usage": 1.01
207
+ }
208
+ )
209
+
210
+ @app.route("/v1/models", methods=['GET'])
211
+ @app.route("/models", methods=['GET'])
212
+ def models():
213
+ import g4f.models
214
+ model = {"data":[]}
215
+ for i in g4f.models.ModelUtils.convert:
216
+ model['data'].append({
217
+ "id": i,
218
+ "object": "model",
219
+ "owned_by": g4f.models.ModelUtils.convert[i].base_provider,
220
+ "tokens": 99999,
221
+ "fallbacks": None,
222
+ "endpoints": [
223
+ "/v1/chat/completions"
224
+ ],
225
+ "limits": None,
226
+ "permission": []
227
+ })
228
+ return jsonify(model)
229
+
230
+ @app.route("/v1/providers", methods=['GET'])
231
+ @app.route("/providers", methods=['GET'])
232
+ def providers():
233
+ files = os.listdir("g4f/Provider/Providers")
234
+ files = [f for f in files if os.path.isfile(os.path.join("g4f/Provider/Providers", f))]
235
+ files.sort(key=str.lower)
236
+ providers_data = {"data":[]}
237
+ for file in files:
238
+ if file.endswith(".py"):
239
+ name = file[:-3]
240
+ try:
241
+ p = getattr(g4f.Provider,name)
242
+ providers_data["data"].append({
243
+ "provider": str(name),
244
+ "model": list(p.model),
245
+ "url": str(p.url),
246
+ "working": bool(p.working),
247
+ "supports_stream": bool(p.supports_stream)
248
+ })
249
+ except:
250
+ pass
251
+ return jsonify(providers_data)
252
+
253
+
backend/backend_old_async.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import json
4
+ import random
5
+ import string
6
+ import asyncio
7
+ import async_timeout
8
+ import aiohttp, aiofiles
9
+ import requests
10
+ import pytz
11
+ import logging
12
+ from datetime import datetime
13
+ from fastapi import FastAPI, Request
14
+ from fastapi.middleware.gzip import GZipMiddleware
15
+ from fastapi.responses import JSONResponse, StreamingResponse
16
+ from starlette.middleware.cors import CORSMiddleware
17
+ from typing import Any
18
+ import g4f
19
+ from g4f import ChatCompletion, Provider, BaseProvider
20
+ from g4f.models import ModelUtils
21
+ from cachetools import LRUCache
22
+
23
+ import aiofiles
24
+ import async_timeout
25
+
26
+ from fp.fp import FreeProxy
27
+ from embedding_processing import embedding_processing
28
+ import concurrent.futures
29
+
30
+ app = FastAPI()
31
+ embedding_proc = embedding_processing()
32
+ LOG = logging.getLogger(__name__)
33
+
34
+ app.add_middleware(GZipMiddleware)
35
+ app.add_middleware(
36
+ CORSMiddleware,
37
+ allow_origins=["*"],
38
+ allow_methods=["*"],
39
+ allow_headers=["*"],
40
+ )
41
+
42
+ def get_proxy():
43
+ proxy = FreeProxy(rand=True, timeout=1).get()
44
+ return proxy
45
+
46
+
47
+ @app.post("/chat/completions")
48
+ @app.post("/v1/chat/completions")
49
+ async def chat_completions(request: Request):
50
+ req_data = await request.json()
51
+ stream = req_data.get('stream', False)
52
+ model = req_data.get('model', 'gpt-3.5-turbo')
53
+ messages = req_data.get('messages')
54
+ temperature = req_data.get('temperature', 1.0)
55
+ top_p = req_data.get('top_p', 1.0)
56
+ max_tokens = req_data.get('max_tokens', 4096)
57
+
58
+ response = ChatCompletion.create(model=model, stream=stream, messages=messages, temperature=temperature, top_p=top_p, max_tokens=max_tokens, system_prompt="")
59
+
60
+ completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=28))
61
+ completion_timestamp = int(time.time())
62
+
63
+ if not stream:
64
+ return {
65
+ "id": f"chatcmpl-{completion_id}",
66
+ "object": "chat.completion",
67
+ "created": completion_timestamp,
68
+ "model": model,
69
+ "choices": [
70
+ {
71
+ "index": 0,
72
+ "message": {
73
+ "role": "assistant",
74
+ "content": response,
75
+ },
76
+ "finish_reason": "stop",
77
+ }
78
+ ],
79
+ "usage": {
80
+ "prompt_tokens": None,
81
+ "completion_tokens": None,
82
+ "total_tokens": None,
83
+ },
84
+ }
85
+
86
+ def streaming():
87
+ for chunk in response:
88
+ completion_data = {
89
+ "id": f"chatcmpl-{completion_id}",
90
+ "object": "chat.completion.chunk",
91
+ "created": completion_timestamp,
92
+ "model": model,
93
+ "choices": [
94
+ {
95
+ "index": 0,
96
+ "delta": {
97
+ "content": chunk,
98
+ },
99
+ "finish_reason": None,
100
+ }
101
+ ],
102
+ }
103
+
104
+ content = json.dumps(completion_data, separators=(",", ":"))
105
+ yield f"data: {content}\n\n"
106
+ time.sleep(0.1)
107
+
108
+ end_completion_data: dict[str, Any] = {
109
+ "id": f"chatcmpl-{completion_id}",
110
+ "object": "chat.completion.chunk",
111
+ "created": completion_timestamp,
112
+ "model": model,
113
+ "choices": [
114
+ {
115
+ "index": 0,
116
+ "delta": {},
117
+ "finish_reason": "stop",
118
+ }
119
+ ],
120
+ }
121
+ content = json.dumps(end_completion_data, separators=(",", ":"))
122
+ yield f"data: {content}\n\n"
123
+
124
+ return StreamingResponse(streaming(), media_type='text/event-stream')
125
+
126
+ @app.post('/v1/embeddings')
127
+ async def create_embedding(request: Request):
128
+ j_input = await request.json()
129
+ #model = embedding_processing()
130
+ embedding = embedding_proc.embedding(text_list=j_input['input'])
131
+ await log_event()
132
+ return JSONResponse(
133
+ embedding
134
+ )
135
+
136
+ async def log_event():
137
+ LOG.info('served')
138
+
139
+ @app.post("/v1/completions")
140
+ async def completions(request: Request):
141
+ req_data = await request.json()
142
+ model = req_data.get('model', 'text-davinci-003')
143
+ prompt = req_data.get('prompt')
144
+ messages = req_data.get('messages')
145
+ temperature = req_data.get('temperature', 1.0)
146
+ top_p = req_data.get('top_p', 1.0)
147
+ max_tokens = req_data.get('max_tokens', 4096)
148
+
149
+ response = g4f.Completion.create(model='text-davinci-003', prompt=prompt, temperature=temperature, top_p=top_p, max_tokens=max_tokens,)
150
+
151
+ completion_id = "".join(random.choices(string.ascii_letters + string.digits, k=24))
152
+ completion_timestamp = int(time.time())
153
+
154
+ return {
155
+ "id": f"cmpl-{completion_id}",
156
+ "object": "text_completion",
157
+ "created": completion_timestamp,
158
+ "model": "text-davinci-003",
159
+ "choices": [
160
+ {
161
+ "text": response,
162
+ "index": 0,
163
+ "logprobs": None,
164
+ "finish_reason": "length"
165
+ }
166
+ ],
167
+ "usage": {
168
+ "prompt_tokens": None,
169
+ "completion_tokens": None,
170
+ "total_tokens": None
171
+ }
172
+ }
173
+
174
+ @app.get("/v1/dashboard/billing/subscription")
175
+ @app.get("/dashboard/billing/subscription")
176
+ async def billing_subscription():
177
+ return JSONResponse({
178
+ "object": "billing_subscription",
179
+ "has_payment_method": True,
180
+ "canceled": False,
181
+ "canceled_at": None,
182
+ "delinquent": None,
183
+ "access_until": 2556028800,
184
+ "soft_limit": 6944500,
185
+ "hard_limit": 166666666,
186
+ "system_hard_limit": 166666666,
187
+ "soft_limit_usd": 416.67,
188
+ "hard_limit_usd": 9999.99996,
189
+ "system_hard_limit_usd": 9999.99996,
190
+ "plan": {
191
+ "title": "Pay-as-you-go",
192
+ "id": "payg"
193
+ },
194
+ "primary": True,
195
+ "account_name": "OpenAI",
196
+ "po_number": None,
197
+ "billing_email": None,
198
+ "tax_ids": None,
199
+ "billing_address": {
200
+ "city": "New York",
201
+ "line1": "OpenAI",
202
+ "country": "US",
203
+ "postal_code": "NY10031"
204
+ },
205
+ "business_address": None
206
+ })
207
+
208
+ @app.get("/v1/dashboard/billing/usage")
209
+ @app.get("/dashboard/billing/usage")
210
+ async def billing_usage():
211
+ return JSONResponse({
212
+ "object": "list",
213
+ "daily_costs": [
214
+ {
215
+ "timestamp": time.time(),
216
+ "line_items": [
217
+ {
218
+ "name": "GPT-4",
219
+ "cost": 0.0
220
+ },
221
+ {
222
+ "name": "Chat models",
223
+ "cost": 1.01
224
+ },
225
+ {
226
+ "name": "InstructGPT",
227
+ "cost": 0.0
228
+ },
229
+ {
230
+ "name": "Fine-tuning models",
231
+ "cost": 0.0
232
+ },
233
+ {
234
+ "name": "Embedding models",
235
+ "cost": 0.0
236
+ },
237
+ {
238
+ "name": "Image models",
239
+ "cost": 16.0
240
+ },
241
+ {
242
+ "name": "Audio models",
243
+ "cost": 0.0
244
+ }
245
+ ]
246
+ }
247
+ ],
248
+ "total_usage": 1.01
249
+ })
250
+
251
+ @app.get("/v1/models")
252
+ @app.get("/models")
253
+ async def get_models():
254
+ models_data = {"data": []}
255
+ for model_name, model in ModelUtils.convert.items():
256
+ models_data['data'].append({
257
+ "id": model_name,
258
+ "object": "model",
259
+ "owned_by": model.base_provider,
260
+ "tokens": 99999,
261
+ "fallbacks": None,
262
+ "endpoints": [
263
+ "/v1/chat/completions"
264
+ ],
265
+ "limits": None,
266
+ "permission": []
267
+ })
268
+ return JSONResponse(models_data)
269
+
270
+ @app.get("/v1/providers")
271
+ @app.get("/providers")
272
+ async def get_providers():
273
+ providers_data = {"data": []}
274
+ for provider_name in dir(Provider):
275
+ if not provider_name.startswith('__'):
276
+ try:
277
+ provider = getattr(Provider, provider_name)
278
+ providers_data["data"].append({
279
+ "provider": provider_name,
280
+ "model": list(provider.model),
281
+ "url": provider.url,
282
+ "working": bool(provider.working),
283
+ "supports_stream": bool(provider.supports_stream)
284
+ })
285
+ except:
286
+ pass
287
+ return JSONResponse(providers_data)
288
+
289
+ def process_provider(provider_name, model_name):
290
+ try:
291
+ p = getattr(g4f.Provider, provider_name)
292
+ provider_status = {
293
+ "provider": provider_name,
294
+ "model": model_name,
295
+ "url": p.url,
296
+ "status": ""
297
+ }
298
+
299
+ # Проверяем только модель 'gpt-3.5-turbo' для провайдеров Wewordle и Qidinam
300
+ if provider_name in ['Wewordle', 'Qidinam', 'DeepAi', 'GetGpt', 'Yqcloud'] and model_name != 'gpt-3.5-turbo':
301
+ provider_status['status'] = 'Inactive'
302
+ #print(f"{provider_name} with {model_name} skipped")
303
+ return provider_status
304
+
305
+ try:
306
+ response = ChatCompletion.create(model=model_name, provider=p,
307
+ messages=[{"role": "user", "content": "Say 'Hello World!'"}], stream=False)
308
+ if any(word in response for word in ['Hello World', 'Hello', 'hello', 'world']):
309
+ provider_status['status'] = 'Active'
310
+ #print(f"{provider_name} with {model_name} say: {response}")
311
+ else:
312
+ provider_status['status'] = 'Inactive'
313
+ #print(f"{provider_name} with {model_name} say: Inactive")
314
+ except Exception as e:
315
+ provider_status['status'] = 'Inactive'
316
+ # print(f"{provider_name} with {model_name} say: Error")
317
+
318
+ return provider_status
319
+ except:
320
+ return None
321
+
322
+ async def run_check_script():
323
+ session = aiohttp.ClientSession()
324
+ while True:
325
+ models = [model for model in g4f.models.ModelUtils.convert if model.startswith('gpt-') or model.startswith('claude') or model.startswith('text-')]
326
+ providers = [provider for provider in dir(g4f.Provider) if not provider.startswith('__')]
327
+
328
+ status = {'data': []}
329
+ with concurrent.futures.ThreadPoolExecutor() as executor:
330
+ futures = []
331
+ for provider_name in providers:
332
+ for model_name in models:
333
+ future = executor.submit(process_provider, provider_name, model_name)
334
+ futures.append(future)
335
+
336
+ for future in concurrent.futures.as_completed(futures):
337
+ result = future.result()
338
+ if result is not None and result['status'] == 'Active':
339
+ status['data'].append(result)
340
+
341
+ print(status)
342
+ status['key'] = "test"
343
+ tz = pytz.timezone('Asia/Shanghai')
344
+ now = datetime.now(tz)
345
+ print(now)
346
+ status['time'] = now.strftime("%Y-%m-%d %H:%M:%S")
347
+
348
+ if status['data']:
349
+ # Здесь мы используем aiofiles для асинхронного записывания в файл
350
+ async with aiofiles.open('status.json', 'w') as f:
351
+ await f.write(json.dumps(status))
352
+
353
+ # Pause for 5 minutes before starting the next cycle
354
+ time.sleep(360)
355
+
356
+ # Запуск асинхронных задач
357
+ async def run_tasks():
358
+ while True:
359
+ await asyncio.gather(run_check_script())
360
+ await asyncio.sleep(300)
361
+
362
+ # Запуск приложения
363
+ def main():
364
+ loop = asyncio.get_event_loop()
365
+ loop.run_until_complete(run_tasks())
366
+ loop.close()
367
+
368
+ if __name__ == "__main__":
369
+ main()
backend/check.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import g4f
3
+ import json
4
+ import time
5
+ import pytz
6
+ from datetime import datetime
7
+ import concurrent.futures
8
+ import asyncio
9
+ from g4f import ChatCompletion
10
+ from fp.fp import FreeProxy
11
+ import threading
12
+ import socket
13
+ from auto_proxy import get_random_proxy, update_working_proxies
14
+
15
+ def process_provider(provider_name, model_name):
16
+ try:
17
+ p = getattr(g4f.Provider, provider_name)
18
+ provider_status = {
19
+ "provider": provider_name,
20
+ "model": model_name,
21
+ "url": p.url,
22
+ "status": ""
23
+ }
24
+
25
+ # Проверяем только модель 'gpt-3.5-turbo' для провайдеров Wewordle и Qidinam
26
+ if provider_name in ['Wewordle', 'Qidinam', 'DeepAi', 'GetGpt', 'Yqcloud', 'WewordleApple'] and model_name != 'gpt-3.5-turbo':
27
+ provider_status['status'] = 'Inactive'
28
+ print(f"{provider_name} with {model_name} skipped")
29
+ return provider_status
30
+
31
+ try:
32
+ proxy = get_random_proxy().decode("utf-8")
33
+ formatted_proxy = f'https://{proxy}'
34
+
35
+ response = ChatCompletion.create(model=model_name, provider=p,
36
+ messages=[{"role": "user", "content": "Say 'Hello World!'"}], stream=False)
37
+ if any(word in response for word in ['Hello World', 'Hello', 'hello', 'world']):
38
+ provider_status['status'] = 'Active'
39
+ print(f"{provider_name} with {model_name} say: {response}")
40
+ else:
41
+ provider_status['status'] = 'Inactive'
42
+ print(f"{provider_name} with {model_name} say: Inactive")
43
+ except Exception as e:
44
+ provider_status['status'] = 'Inactive'
45
+ print(f"{provider_name} with {model_name} say: Error")
46
+
47
+ return provider_status
48
+ except:
49
+ return None
50
+
51
+ def main():
52
+ while True:
53
+ models = [model for model in g4f.models.ModelUtils.convert if model.startswith('gpt-') or model.startswith('claude') or model.startswith('text-')]
54
+ providers = [provider for provider in dir(g4f.Provider) if not provider.startswith('__')]
55
+
56
+ status = {'data': []}
57
+ with concurrent.futures.ThreadPoolExecutor() as executor:
58
+ futures = []
59
+ for provider_name in providers:
60
+ for model_name in models:
61
+ future = executor.submit(process_provider, provider_name, model_name)
62
+ futures.append(future)
63
+
64
+ for future in concurrent.futures.as_completed(futures):
65
+ result = future.result()
66
+ if result is not None and result['status'] == 'Active':
67
+ status['data'].append(result)
68
+
69
+ print(status)
70
+ status['key'] = "test"
71
+ tz = pytz.timezone('Asia/Shanghai')
72
+ now = datetime.now(tz)
73
+ print(now)
74
+ status['time'] = now.strftime("%Y-%m-%d %H:%M:%S")
75
+
76
+ # Save the status data to a JSON file only if there are active providers
77
+ if status['data']:
78
+ with open('status.json', 'w') as f:
79
+ json.dump(status, f)
80
+
81
+ # Pause for 10 minutes before starting the next cycle
82
+ time.sleep(600)
83
+
84
+ if __name__ == "__main__":
85
+ main()
backend/config.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ app = {
2
+ 'host': '0.0.0.0',
3
+ 'port': 1337,
4
+ 'debug': True
5
+ }
6
+
7
+ request = {
8
+ 'timeout': 60
9
+ }
backend/embedding_processing.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spacy
2
+ import numpy as np
3
+ import os
4
+ from zhconv import convert
5
+ import re
6
+ import random
7
+
8
+ # добавьте специфическую для русского языка модель
9
+ import ru_core_news_sm
10
+
11
+ def detect_lang(text):
12
+ # 定义语言占比字典
13
+ lang_dict = {'zh-cn': 0, 'zh-tw': 0, 'en': 0, 'ru': 0, 'other': 0} # добавьте русский язык
14
+ # 随机抽样最多十个字符
15
+ sample = random.sample(text, min(10, len(text)))
16
+ # 计算每种语言的字符占比
17
+ for char in sample:
18
+ if re.search(r'[\u4e00-\u9fa5]', char):
19
+ lang_dict['zh-cn'] += 1
20
+ elif re.search(r'[\u4e00-\u9fff]', char):
21
+ lang_dict['zh-tw'] += 1
22
+ elif re.search(r'[a-zA-Z]', char):
23
+ lang_dict['en'] += 1
24
+ elif re.search(r'[а-яА-Я]', char): # добавьте соответствующий диапазон для русских букв
25
+ lang_dict['ru'] += 1
26
+ else:
27
+ lang_dict['other'] += 1
28
+ # 返回占比最高的语言
29
+ return max(lang_dict, key=lang_dict.get)
30
+
31
+ class embedding_processing:
32
+
33
+ def __init__(self, model_path='./model'):
34
+ self.en_model = spacy.load('en_core_web_sm')
35
+ self.zh_model = spacy.load('zh_core_web_sm')
36
+ self.ru_model = ru_core_news_sm.load() # добавьте модель для русского языка
37
+
38
+ def model(self,text):
39
+ lang = detect_lang(text)
40
+ if lang == "zh-tw":
41
+ ans_cn = self.zh_model(convert(text)).vector.tolist()
42
+ else:
43
+ ans_cn = self.zh_model(text).vector.tolist()
44
+ ans = self.en_model(text).vector.tolist()
45
+ return ans_cn+ans
46
+
47
+ def embedding(self, text_list):
48
+ embeddings_list = [self.model(text) for text in text_list]
49
+ response_embedding = self.transform_embedding_to_dict(embeddings_list,text_list)
50
+ return response_embedding
51
+
52
+ def transform_embedding_to_dict(self, embedding_list, text_list, model_name="text-embedding-ada-002"):
53
+ prompt_tokens = sum(len(text) for text in text_list)
54
+ total_tokens = sum(len(embedding) for embedding in embedding_list)
55
+
56
+ transformed_data = {
57
+ "data": [
58
+ {
59
+ "embedding": embedding,
60
+ "index": index,
61
+ "object": "embedding"
62
+ }
63
+ for index, embedding in enumerate(embedding_list)
64
+ ],
65
+ "model": model_name,
66
+ "object": "list",
67
+ "usage": {
68
+ "prompt_tokens": prompt_tokens,
69
+ "total_tokens": total_tokens
70
+ }
71
+ }
72
+ return transformed_data
configs/ds_config_chatbot.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": false
4
+ },
5
+ "bf16": {
6
+ "enabled": true
7
+ },
8
+ "comms_logger": {
9
+ "enabled": false,
10
+ "verbose": false,
11
+ "prof_all": false,
12
+ "debug": false
13
+ },
14
+ "steps_per_print": 20000000000000000,
15
+ "train_micro_batch_size_per_gpu": 1,
16
+ "wall_clock_breakdown": false
17
+ }
docker-compose/.env ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ LANG=ru
2
+ # Paste ur email below
3
+ EMAIL=acme@example.com
4
+ TRAEFIK_USER=admin
5
+ CERT_RESOLVER=letsencrypt
6
+ # To change password use " htpasswd -nBC 10 admin " (or whatever username u want) and paste below the part after :
7
+ TRAEFIK_PASSWORD_HASH=
8
+ OPENAI_API_KEY=
9
+ DOMAIN=
docker-compose/docker-compose.traefik.yml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.7"
2
+ services:
3
+
4
+ traefik:
5
+ image: traefik:2.4.8
6
+ container_name: proxy
7
+ hostname: proxy
8
+ command:
9
+ - --entrypoints.http.address=:80
10
+ - --entrypoints.https.address=:443
11
+ - --providers.docker=true
12
+ - --api=false
13
+ - --log.level=DEBUG
14
+ - --certificatesresolvers.letsencrypt.acme.httpchallenge=true
15
+ - --certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=http
16
+ - --certificatesresolvers.letsencrypt.acme.email=${EMAIL}
17
+ - --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
18
+ networks:
19
+ - ngptnet
20
+ labels:
21
+ - traefik.enable=true
22
+ - traefik.docker.network=ngptnet
23
+ - traefik.http.routers.to-https.rule=HostRegexp(`{host:.+}`)
24
+ - traefik.http.routers.to-https.entrypoints=http
25
+ - traefik.http.routers.to-https.middlewares=to-https
26
+ - traefik.http.middlewares.to-https.redirectscheme.scheme=https
27
+ - traefik.http.middlewares.basicauth.basicauth.users=${TRAEFIK_USER}:${TRAEFIK_PASSWORD_HASH}
28
+ ports:
29
+ - 80:80
30
+ - 443:443
31
+ volumes:
32
+ - acmes:/letsencrypt
33
+ - /var/run/docker.sock:/var/run/docker.sock:ro
34
+
35
+ neurogengpt:
36
+ image: neurogen/neurogengpt:latest
37
+ build:
38
+ context: ../
39
+ dockerfile: Dockerfile
40
+ container_name: neurogengpt
41
+ hostname: neurogengpt
42
+ environment:
43
+ - SUBF=/sub
44
+ env_file:
45
+ - .env
46
+ networks:
47
+ - ngptnet
48
+ labels:
49
+ - traefik.enable=true
50
+ - traefik.docker.network=ngptnet
51
+ # WebUI config
52
+ - traefik.http.routers.ngpt-webui.rule=Host(`${DOMAIN}`)
53
+ - traefik.http.routers.ngpt-webui.entrypoints=https
54
+ - traefik.http.routers.ngpt-webui.tls=true
55
+ - traefik.http.routers.ngpt-webui.tls.certresolver=${CERT_RESOLVER}
56
+ - traefik.http.routers.ngpt-webui.service=ngpt-webui
57
+ - traefik.http.services.ngpt-webui.loadbalancer.server.port=7860
58
+ - traefik.http.routers.ngpt-webui.middlewares=basicauth
59
+ # API config
60
+ - traefik.http.routers.ngpt-api.rule=Host(`${DOMAIN}`) && PathPrefix(`/api`)
61
+ - traefik.http.routers.ngpt-api.middlewares=api-stripprefix
62
+ - traefik.http.middlewares.api-stripprefix.stripprefix.prefixes=/api
63
+ - traefik.http.routers.ngpt-api.entrypoints=https
64
+ - traefik.http.routers.ngpt-api.service=ngpt-api
65
+ - traefik.http.services.ngpt-api.loadbalancer.server.port=1337
66
+ volumes:
67
+ - ../config.json:/app/config.json
68
+
69
+ volumes:
70
+ acmes:
71
+
72
+ networks:
73
+ ngptnet:
docker-compose/docker-compose.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: "3.10"
2
+
3
+ services:
4
+ neurogengpt:
5
+ build:
6
+ context: ../
7
+ dockerfile: Dockerfile
8
+ ports:
9
+ - "7860:7860"
10
+ - "1337:1337"
11
+ volumes:
12
+ - ../config.json:/app/config.json
13
+ environment:
14
+ - SUBF=/sub
15
+ env_file:
16
+ - .env
dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stage 1: Build
2
+
3
+ FROM python:3.10-slim-buster as builder
4
+
5
+ WORKDIR /app
6
+
7
+ RUN apt-get update && apt-get install -y --no-install-recommends build-essential git
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir --user -r requirements.txt
10
+
11
+ FROM python:3.10-slim-buster
12
+
13
+ WORKDIR /app
14
+
15
+ COPY --from=builder /root/.local /root/.local
16
+ ENV PATH=/root/.local/bin:$PATH
17
+ COPY . .
18
+ RUN python -m spacy download ru_core_news_sm && \
19
+ python -m spacy download en_core_web_sm && \
20
+ python -m spacy download zh_core_web_sm
21
+ RUN chmod +x entrypoint.sh
22
+
23
+ EXPOSE 7860
24
+ EXPOSE 1337
25
+
26
+ ENV LANG=ru
27
+
28
+ CMD ["./entrypoint.sh"]
endpoint.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import socket
2
+ import nest_asyncio
3
+ from backend.backend import app
4
+ from waitress import serve
5
+
6
+ nest_asyncio.apply()
7
+
8
+ site_config = {
9
+ 'host': '0.0.0.0',
10
+ 'port': 1337,
11
+ 'debug': False
12
+ }
13
+
14
+ if __name__ == "__main__":
15
+ hostname = socket.gethostname()
16
+ ip_address = socket.gethostbyname(hostname)
17
+
18
+ print(f"Running on http://127.0.0.1:{site_config['port']}")
19
+ print(f"Running on http://{ip_address}:{site_config['port']}")
20
+
21
+ serve(app, host='0.0.0.0', port=site_config['port'],threads=4)
entrypoint.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ LANG_VALUE="$LANG"
3
+
4
+ if [[ "$LANG_VALUE" == "en" ]]; then
5
+ echo "Running $LANG version"
6
+ python webui_en.py
7
+ elif [[ "$LANG_VALUE" == "ru" ]]; then
8
+ echo "Запускается $LANG версия"
9
+ python webui_ru.py
10
+ else
11
+ echo "Недопустимое значение переменной окружения LANG. Поддерживаемые значения: en, ru"
12
+ exit 1
13
+ fi
g4f/Provider/AItianhu.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from ..typing import AsyncResult, Messages
6
+ from ..requests import StreamSession
7
+ from .base_provider import AsyncGeneratorProvider, format_prompt, get_cookies
8
+
9
+
10
+ class AItianhu(AsyncGeneratorProvider):
11
+ url = "https://www.aitianhu.com"
12
+ working = True
13
+ supports_gpt_35_turbo = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ cookies: dict = None,
22
+ timeout: int = 120,
23
+ **kwargs
24
+ ) -> AsyncResult:
25
+ if not cookies:
26
+ cookies = get_cookies("www.aitianhu.com")
27
+ data = {
28
+ "prompt": format_prompt(messages),
29
+ "options": {},
30
+ "systemMessage": "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully.",
31
+ "temperature": 0.8,
32
+ "top_p": 1,
33
+ **kwargs
34
+ }
35
+ headers = {
36
+ "Authority": cls.url,
37
+ "Accept": "application/json, text/plain, */*",
38
+ "Origin": cls.url,
39
+ "Referer": f"{cls.url}/"
40
+ }
41
+ async with StreamSession(
42
+ headers=headers,
43
+ cookies=cookies,
44
+ timeout=timeout,
45
+ proxies={"https": proxy},
46
+ impersonate="chrome107",
47
+ verify=False
48
+ ) as session:
49
+ async with session.post(f"{cls.url}/api/chat-process", json=data) as response:
50
+ response.raise_for_status()
51
+ async for line in response.iter_lines():
52
+ if line == b"<script>":
53
+ raise RuntimeError("Solve challenge and pass cookies")
54
+ if b"platform's risk control" in line:
55
+ raise RuntimeError("Platform's Risk Control")
56
+ line = json.loads(line)
57
+ if "detail" in line:
58
+ content = line["detail"]["choices"][0]["delta"].get("content")
59
+ if content:
60
+ yield content
61
+ else:
62
+ raise RuntimeError(f"Response: {line}")
63
+
64
+
65
+ @classmethod
66
+ @property
67
+ def params(cls):
68
+ params = [
69
+ ("model", "str"),
70
+ ("messages", "list[dict[str, str]]"),
71
+ ("stream", "bool"),
72
+ ("proxy", "str"),
73
+ ("temperature", "float"),
74
+ ("top_p", "int"),
75
+ ]
76
+ param = ", ".join([": ".join(p) for p in params])
77
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
g4f/Provider/AItianhuSpace.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random, json
4
+
5
+ from ..typing import AsyncResult, Messages
6
+ from ..requests import StreamSession
7
+ from .base_provider import AsyncGeneratorProvider, format_prompt, get_cookies
8
+
9
+ domains = {
10
+ "gpt-3.5-turbo": "aitianhu.space",
11
+ "gpt-4": "aitianhu.website",
12
+ }
13
+
14
+ class AItianhuSpace(AsyncGeneratorProvider):
15
+ url = "https://chat3.aiyunos.top/"
16
+ working = True
17
+ supports_gpt_35_turbo = True
18
+
19
+ @classmethod
20
+ async def create_async_generator(
21
+ cls,
22
+ model: str,
23
+ messages: Messages,
24
+ proxy: str = None,
25
+ domain: str = None,
26
+ cookies: dict = None,
27
+ timeout: int = 120,
28
+ **kwargs
29
+ ) -> AsyncResult:
30
+ if not model:
31
+ model = "gpt-3.5-turbo"
32
+ elif not model in domains:
33
+ raise ValueError(f"Model are not supported: {model}")
34
+ if not domain:
35
+ chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
36
+ rand = ''.join(random.choice(chars) for _ in range(6))
37
+ domain = f"{rand}.{domains[model]}"
38
+ if not cookies:
39
+ cookies = get_cookies(domain)
40
+
41
+ url = f'https://{domain}'
42
+ async with StreamSession(
43
+ proxies={"https": proxy},
44
+ cookies=cookies,
45
+ timeout=timeout,
46
+ impersonate="chrome110",
47
+ verify=False
48
+ ) as session:
49
+ data = {
50
+ "prompt": format_prompt(messages),
51
+ "options": {},
52
+ "systemMessage": "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully.",
53
+ "temperature": 0.8,
54
+ "top_p": 1,
55
+ **kwargs
56
+ }
57
+ headers = {
58
+ "Authority": url,
59
+ "Accept": "application/json, text/plain, */*",
60
+ "Origin": url,
61
+ "Referer": f"{url}/"
62
+ }
63
+ async with session.post(f"{url}/api/chat-process", json=data, headers=headers) as response:
64
+ response.raise_for_status()
65
+ async for line in response.iter_lines():
66
+ if line == b"<script>":
67
+ raise RuntimeError("Solve challenge and pass cookies and a fixed domain")
68
+ if b"platform's risk control" in line:
69
+ raise RuntimeError("Platform's Risk Control")
70
+ line = json.loads(line)
71
+ if "detail" in line:
72
+ content = line["detail"]["choices"][0]["delta"].get("content")
73
+ if content:
74
+ yield content
75
+ elif "message" in line and "AI-4接口非常昂贵" in line["message"]:
76
+ raise RuntimeError("Rate limit for GPT 4 reached")
77
+ else:
78
+ raise RuntimeError(f"Response: {line}")
79
+
80
+
81
+ @classmethod
82
+ @property
83
+ def params(cls):
84
+ params = [
85
+ ("model", "str"),
86
+ ("messages", "list[dict[str, str]]"),
87
+ ("stream", "bool"),
88
+ ("temperature", "float"),
89
+ ("top_p", "int"),
90
+ ]
91
+ param = ", ".join([": ".join(p) for p in params])
92
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
g4f/Provider/Acytoo.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+
5
+ from ..typing import AsyncResult, Messages
6
+ from .base_provider import AsyncGeneratorProvider
7
+
8
+
9
+ class Acytoo(AsyncGeneratorProvider):
10
+ url = 'https://chat.acytoo.com'
11
+ working = True
12
+ supports_gpt_35_turbo = True
13
+
14
+ @classmethod
15
+ async def create_async_generator(
16
+ cls,
17
+ model: str,
18
+ messages: Messages,
19
+ proxy: str = None,
20
+ **kwargs
21
+ ) -> AsyncResult:
22
+ async with ClientSession(
23
+ headers=_create_header()
24
+ ) as session:
25
+ async with session.post(
26
+ f'{cls.url}/api/completions',
27
+ proxy=proxy,
28
+ json=_create_payload(messages, **kwargs)
29
+ ) as response:
30
+ response.raise_for_status()
31
+ async for stream in response.content.iter_any():
32
+ if stream:
33
+ yield stream.decode()
34
+
35
+
36
+ def _create_header():
37
+ return {
38
+ 'accept': '*/*',
39
+ 'content-type': 'application/json',
40
+ }
41
+
42
+
43
+ def _create_payload(messages: Messages, temperature: float = 0.5, **kwargs):
44
+ return {
45
+ 'key' : '',
46
+ 'model' : 'gpt-3.5-turbo',
47
+ 'messages' : messages,
48
+ 'temperature' : temperature,
49
+ 'password' : ''
50
+ }
g4f/Provider/AiAsk.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+ from ..typing import AsyncResult, Messages
5
+ from .base_provider import AsyncGeneratorProvider
6
+
7
+ class AiAsk(AsyncGeneratorProvider):
8
+ url = "https://e.aiask.me"
9
+ supports_gpt_35_turbo = True
10
+ working = True
11
+
12
+ @classmethod
13
+ async def create_async_generator(
14
+ cls,
15
+ model: str,
16
+ messages: Messages,
17
+ proxy: str = None,
18
+ **kwargs
19
+ ) -> AsyncResult:
20
+ headers = {
21
+ "accept": "application/json, text/plain, */*",
22
+ "origin": cls.url,
23
+ "referer": f"{cls.url}/chat",
24
+ }
25
+ async with ClientSession(headers=headers) as session:
26
+ data = {
27
+ "continuous": True,
28
+ "id": "fRMSQtuHl91A4De9cCvKD",
29
+ "list": messages,
30
+ "models": "0",
31
+ "prompt": "",
32
+ "temperature": kwargs.get("temperature", 0.5),
33
+ "title": "",
34
+ }
35
+ buffer = ""
36
+ rate_limit = "您的免费额度不够使用这个模型啦,请点击右上角登录继续使用!"
37
+ async with session.post(f"{cls.url}/v1/chat/gpt/", json=data, proxy=proxy) as response:
38
+ response.raise_for_status()
39
+ async for chunk in response.content.iter_any():
40
+ buffer += chunk.decode()
41
+ if not rate_limit.startswith(buffer):
42
+ yield buffer
43
+ buffer = ""
44
+ elif buffer == rate_limit:
45
+ raise RuntimeError("Rate limit reached")
g4f/Provider/Aibn.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import hashlib
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from ..requests import StreamSession
8
+ from .base_provider import AsyncGeneratorProvider
9
+
10
+
11
+ class Aibn(AsyncGeneratorProvider):
12
+ url = "https://aibn.cc"
13
+ supports_gpt_35_turbo = True
14
+ working = True
15
+
16
+ @classmethod
17
+ async def create_async_generator(
18
+ cls,
19
+ model: str,
20
+ messages: Messages,
21
+ proxy: str = None,
22
+ timeout: int = 120,
23
+ **kwargs
24
+ ) -> AsyncResult:
25
+ async with StreamSession(
26
+ impersonate="chrome107",
27
+ proxies={"https": proxy},
28
+ timeout=timeout
29
+ ) as session:
30
+ timestamp = int(time.time())
31
+ data = {
32
+ "messages": messages,
33
+ "pass": None,
34
+ "sign": generate_signature(timestamp, messages[-1]["content"]),
35
+ "time": timestamp
36
+ }
37
+ async with session.post(f"{cls.url}/api/generate", json=data) as response:
38
+ response.raise_for_status()
39
+ async for chunk in response.iter_content():
40
+ yield chunk.decode()
41
+
42
+ @classmethod
43
+ @property
44
+ def params(cls):
45
+ params = [
46
+ ("model", "str"),
47
+ ("messages", "list[dict[str, str]]"),
48
+ ("stream", "bool"),
49
+ ("temperature", "float"),
50
+ ]
51
+ param = ", ".join([": ".join(p) for p in params])
52
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
53
+
54
+
55
+ def generate_signature(timestamp: int, message: str, secret: str = "undefined"):
56
+ data = f"{timestamp}:{message}:{secret}"
57
+ return hashlib.sha256(data.encode()).hexdigest()
g4f/Provider/Aichat.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+
5
+ from ..typing import Messages
6
+ from .base_provider import AsyncProvider, format_prompt
7
+
8
+
9
+ class Aichat(AsyncProvider):
10
+ url = "https://chat-gpt.org/chat"
11
+ working = True
12
+ supports_gpt_35_turbo = True
13
+
14
+ @staticmethod
15
+ async def create_async(
16
+ model: str,
17
+ messages: Messages,
18
+ proxy: str = None,
19
+ **kwargs
20
+ ) -> str:
21
+ headers = {
22
+ "authority": "chat-gpt.org",
23
+ "accept": "*/*",
24
+ "cache-control": "no-cache",
25
+ "content-type": "application/json",
26
+ "origin": "https://chat-gpt.org",
27
+ "pragma": "no-cache",
28
+ "referer": "https://chat-gpt.org/chat",
29
+ "sec-ch-ua-mobile": "?0",
30
+ "sec-ch-ua-platform": '"macOS"',
31
+ "sec-fetch-dest": "empty",
32
+ "sec-fetch-mode": "cors",
33
+ "sec-fetch-site": "same-origin",
34
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
35
+ }
36
+ async with ClientSession(
37
+ headers=headers
38
+ ) as session:
39
+ json_data = {
40
+ "message": format_prompt(messages),
41
+ "temperature": kwargs.get('temperature', 0.5),
42
+ "presence_penalty": 0,
43
+ "top_p": kwargs.get('top_p', 1),
44
+ "frequency_penalty": 0,
45
+ }
46
+ async with session.post(
47
+ "https://chat-gpt.org/api/text",
48
+ proxy=proxy,
49
+ json=json_data
50
+ ) as response:
51
+ response.raise_for_status()
52
+ result = await response.json()
53
+ if not result['response']:
54
+ raise Exception(f"Error Response: {result}")
55
+ return result["message"]
g4f/Provider/Ails.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import time
5
+ import uuid
6
+ import json
7
+ from datetime import datetime
8
+ from aiohttp import ClientSession
9
+
10
+ from ..typing import SHA256, AsyncResult, Messages
11
+ from .base_provider import AsyncGeneratorProvider
12
+
13
+
14
+ class Ails(AsyncGeneratorProvider):
15
+ url: str = "https://ai.ls"
16
+ working = True
17
+ supports_gpt_35_turbo = True
18
+
19
+ @staticmethod
20
+ async def create_async_generator(
21
+ model: str,
22
+ messages: Messages,
23
+ stream: bool,
24
+ proxy: str = None,
25
+ **kwargs
26
+ ) -> AsyncResult:
27
+ headers = {
28
+ "authority": "api.caipacity.com",
29
+ "accept": "*/*",
30
+ "accept-language": "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
31
+ "authorization": "Bearer free",
32
+ "client-id": str(uuid.uuid4()),
33
+ "client-v": "0.1.278",
34
+ "content-type": "application/json",
35
+ "origin": "https://ai.ls",
36
+ "referer": "https://ai.ls/",
37
+ "sec-ch-ua": '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
38
+ "sec-ch-ua-mobile": "?0",
39
+ "sec-ch-ua-platform": '"Windows"',
40
+ "sec-fetch-dest": "empty",
41
+ "sec-fetch-mode": "cors",
42
+ "sec-fetch-site": "cross-site",
43
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
44
+ "from-url": "https://ai.ls/?chat=1"
45
+ }
46
+ async with ClientSession(
47
+ headers=headers
48
+ ) as session:
49
+ timestamp = _format_timestamp(int(time.time() * 1000))
50
+ json_data = {
51
+ "model": "gpt-3.5-turbo",
52
+ "temperature": kwargs.get("temperature", 0.6),
53
+ "stream": True,
54
+ "messages": messages,
55
+ "d": datetime.now().strftime("%Y-%m-%d"),
56
+ "t": timestamp,
57
+ "s": _hash({"t": timestamp, "m": messages[-1]["content"]}),
58
+ }
59
+ async with session.post(
60
+ "https://api.caipacity.com/v1/chat/completions",
61
+ proxy=proxy,
62
+ json=json_data
63
+ ) as response:
64
+ response.raise_for_status()
65
+ start = "data: "
66
+ async for line in response.content:
67
+ line = line.decode('utf-8')
68
+ if line.startswith(start) and line != "data: [DONE]":
69
+ line = line[len(start):-1]
70
+ line = json.loads(line)
71
+ token = line["choices"][0]["delta"].get("content")
72
+ if token:
73
+ if "ai.ls" in token or "ai.ci" in token:
74
+ raise Exception("Response Error: " + token)
75
+ yield token
76
+
77
+
78
+ @classmethod
79
+ @property
80
+ def params(cls):
81
+ params = [
82
+ ("model", "str"),
83
+ ("messages", "list[dict[str, str]]"),
84
+ ("stream", "bool"),
85
+ ("temperature", "float"),
86
+ ]
87
+ param = ", ".join([": ".join(p) for p in params])
88
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
89
+
90
+
91
+ def _hash(json_data: dict[str, str]) -> SHA256:
92
+ base_string: str = "%s:%s:%s:%s" % (
93
+ json_data["t"],
94
+ json_data["m"],
95
+ "WI,2rU#_r:r~aF4aJ36[.Z(/8Rv93Rf",
96
+ len(json_data["m"]),
97
+ )
98
+
99
+ return SHA256(hashlib.sha256(base_string.encode()).hexdigest())
100
+
101
+
102
+ def _format_timestamp(timestamp: int) -> str:
103
+ e = timestamp
104
+ n = e % 10
105
+ r = n + 1 if n % 2 == 0 else n
106
+ return str(e - n + r)
g4f/Provider/Aivvm.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import requests
3
+
4
+ from .base_provider import BaseProvider
5
+ from ..typing import CreateResult
6
+ from json import dumps
7
+
8
+ # to recreate this easily, send a post request to https://chat.aivvm.com/api/models
9
+ models = {
10
+ 'gpt-3.5-turbo': {'id': 'gpt-3.5-turbo', 'name': 'GPT-3.5'},
11
+ 'gpt-3.5-turbo-0613': {'id': 'gpt-3.5-turbo-0613', 'name': 'GPT-3.5-0613'},
12
+ 'gpt-3.5-turbo-16k': {'id': 'gpt-3.5-turbo-16k', 'name': 'GPT-3.5-16K'},
13
+ 'gpt-3.5-turbo-16k-0613': {'id': 'gpt-3.5-turbo-16k-0613', 'name': 'GPT-3.5-16K-0613'},
14
+ 'gpt-4': {'id': 'gpt-4', 'name': 'GPT-4'},
15
+ 'gpt-4-0613': {'id': 'gpt-4-0613', 'name': 'GPT-4-0613'},
16
+ 'gpt-4-32k': {'id': 'gpt-4-32k', 'name': 'GPT-4-32K'},
17
+ 'gpt-4-32k-0613': {'id': 'gpt-4-32k-0613', 'name': 'GPT-4-32K-0613'},
18
+ }
19
+
20
+ class Aivvm(BaseProvider):
21
+ url = 'https://chat.aivvm.com'
22
+ supports_stream = True
23
+ working = False
24
+ supports_gpt_35_turbo = True
25
+ supports_gpt_4 = True
26
+
27
+ @classmethod
28
+ def create_completion(cls,
29
+ model: str,
30
+ messages: list[dict[str, str]],
31
+ stream: bool,
32
+ **kwargs
33
+ ) -> CreateResult:
34
+ if not model:
35
+ model = "gpt-3.5-turbo"
36
+ elif model not in models:
37
+ raise ValueError(f"Model is not supported: {model}")
38
+
39
+ json_data = {
40
+ "model" : models[model],
41
+ "messages" : messages,
42
+ "key" : "",
43
+ "prompt" : kwargs.get("system_message", "You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using markdown."),
44
+ "temperature" : kwargs.get("temperature", 0.7)
45
+ }
46
+
47
+ data = dumps(json_data)
48
+
49
+ headers = {
50
+ "accept" : "text/event-stream",
51
+ "accept-language" : "en-US,en;q=0.9",
52
+ "content-type" : "application/json",
53
+ "content-length" : str(len(data)),
54
+ "sec-ch-ua" : "\"Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
55
+ "sec-ch-ua-mobile" : "?0",
56
+ "sec-ch-ua-platform": "\"Windows\"",
57
+ "sec-fetch-dest" : "empty",
58
+ "sec-fetch-mode" : "cors",
59
+ "sec-fetch-site" : "same-origin",
60
+ "sec-gpc" : "1",
61
+ "referrer" : "https://chat.aivvm.com/",
62
+ "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
63
+ }
64
+
65
+ response = requests.post("https://chat.aivvm.com/api/chat", headers=headers, data=data, stream=True)
66
+ response.raise_for_status()
67
+
68
+ for chunk in response.iter_content(chunk_size=4096):
69
+ try:
70
+ yield chunk.decode("utf-8")
71
+ except UnicodeDecodeError:
72
+ yield chunk.decode("unicode-escape")
73
+
74
+ @classmethod
75
+ @property
76
+ def params(cls):
77
+ params = [
78
+ ('model', 'str'),
79
+ ('messages', 'list[dict[str, str]]'),
80
+ ('stream', 'bool'),
81
+ ('temperature', 'float'),
82
+ ]
83
+ param = ', '.join([': '.join(p) for p in params])
84
+ return f'g4f.provider.{cls.__name__} supports: ({param})'
g4f/Provider/Bing.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ import json
5
+ import os
6
+ import uuid
7
+ import urllib.parse
8
+ from aiohttp import ClientSession, ClientTimeout
9
+ from ..typing import AsyncResult, Messages
10
+ from .base_provider import AsyncGeneratorProvider
11
+
12
+ class Tones():
13
+ creative = "Creative"
14
+ balanced = "Balanced"
15
+ precise = "Precise"
16
+
17
+ default_cookies = {
18
+ 'SRCHD' : 'AF=NOFORM',
19
+ 'PPLState' : '1',
20
+ 'KievRPSSecAuth': '',
21
+ 'SUID' : '',
22
+ 'SRCHUSR' : '',
23
+ 'SRCHHPGUSR' : '',
24
+ }
25
+
26
+ class Bing(AsyncGeneratorProvider):
27
+ url = "https://bing.com/chat"
28
+ working = True
29
+ supports_gpt_4 = True
30
+
31
+ @staticmethod
32
+ def create_async_generator(
33
+ model: str,
34
+ messages: Messages,
35
+ proxy: str = None,
36
+ cookies: dict = None,
37
+ tone: str = Tones.creative,
38
+ **kwargs
39
+ ) -> AsyncResult:
40
+ if len(messages) < 2:
41
+ prompt = messages[0]["content"]
42
+ context = None
43
+ else:
44
+ prompt = messages[-1]["content"]
45
+ context = create_context(messages[:-1])
46
+
47
+ if not cookies or "SRCHD" not in cookies:
48
+ cookies = default_cookies
49
+ return stream_generate(prompt, tone, context, proxy, cookies)
50
+
51
+ def create_context(messages: Messages):
52
+ context = "".join(f"[{message['role']}](#message)\n{message['content']}\n\n" for message in messages)
53
+
54
+ return context
55
+
56
+ class Conversation():
57
+ def __init__(self, conversationId: str, clientId: str, conversationSignature: str) -> None:
58
+ self.conversationId = conversationId
59
+ self.clientId = clientId
60
+ self.conversationSignature = conversationSignature
61
+
62
+ async def create_conversation(session: ClientSession, proxy: str = None) -> Conversation:
63
+ url = 'https://www.bing.com/turing/conversation/create?bundleVersion=1.1150.3'
64
+
65
+ async with await session.get(url, proxy=proxy) as response:
66
+ data = await response.json()
67
+
68
+ conversationId = data.get('conversationId')
69
+ clientId = data.get('clientId')
70
+ conversationSignature = response.headers.get('X-Sydney-Encryptedconversationsignature')
71
+
72
+ if not conversationId or not clientId or not conversationSignature:
73
+ raise Exception('Failed to create conversation.')
74
+
75
+ return Conversation(conversationId, clientId, conversationSignature)
76
+
77
+ async def list_conversations(session: ClientSession) -> list:
78
+ url = "https://www.bing.com/turing/conversation/chats"
79
+ async with session.get(url) as response:
80
+ response = await response.json()
81
+ return response["chats"]
82
+
83
+ async def delete_conversation(session: ClientSession, conversation: Conversation, proxy: str = None) -> list:
84
+ url = "https://sydney.bing.com/sydney/DeleteSingleConversation"
85
+ json = {
86
+ "conversationId": conversation.conversationId,
87
+ "conversationSignature": conversation.conversationSignature,
88
+ "participant": {"id": conversation.clientId},
89
+ "source": "cib",
90
+ "optionsSets": ["autosave"]
91
+ }
92
+ async with session.post(url, json=json, proxy=proxy) as response:
93
+ response = await response.json()
94
+ return response["result"]["value"] == "Success"
95
+
96
+ class Defaults:
97
+ delimiter = "\x1e"
98
+ ip_address = f"13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
99
+
100
+ allowedMessageTypes = [
101
+ "Chat",
102
+ "Disengaged",
103
+ "AdsQuery",
104
+ "SemanticSerp",
105
+ "GenerateContentQuery",
106
+ "SearchQuery",
107
+ "ActionRequest",
108
+ "Context",
109
+ "Progress",
110
+ "AdsQuery",
111
+ "SemanticSerp",
112
+ ]
113
+
114
+ sliceIds = [
115
+ "winmuid3tf",
116
+ "osbsdusgreccf",
117
+ "ttstmout",
118
+ "crchatrev",
119
+ "winlongmsgtf",
120
+ "ctrlworkpay",
121
+ "norespwtf",
122
+ "tempcacheread",
123
+ "temptacache",
124
+ "505scss0",
125
+ "508jbcars0",
126
+ "515enbotdets0",
127
+ "5082tsports",
128
+ "515vaoprvs",
129
+ "424dagslnv1s0",
130
+ "kcimgattcf",
131
+ "427startpms0",
132
+ ]
133
+
134
+ location = {
135
+ "locale": "en-US",
136
+ "market": "en-US",
137
+ "region": "US",
138
+ "locationHints": [
139
+ {
140
+ "country": "United States",
141
+ "state": "California",
142
+ "city": "Los Angeles",
143
+ "timezoneoffset": 8,
144
+ "countryConfidence": 8,
145
+ "Center": {"Latitude": 34.0536909, "Longitude": -118.242766},
146
+ "RegionType": 2,
147
+ "SourceType": 1,
148
+ }
149
+ ],
150
+ }
151
+
152
+ headers = {
153
+ 'accept': '*/*',
154
+ 'accept-language': 'en-US,en;q=0.9',
155
+ 'cache-control': 'max-age=0',
156
+ 'sec-ch-ua': '"Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"',
157
+ 'sec-ch-ua-arch': '"x86"',
158
+ 'sec-ch-ua-bitness': '"64"',
159
+ 'sec-ch-ua-full-version': '"110.0.1587.69"',
160
+ 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
161
+ 'sec-ch-ua-mobile': '?0',
162
+ 'sec-ch-ua-model': '""',
163
+ 'sec-ch-ua-platform': '"Windows"',
164
+ 'sec-ch-ua-platform-version': '"15.0.0"',
165
+ 'sec-fetch-dest': 'document',
166
+ 'sec-fetch-mode': 'navigate',
167
+ 'sec-fetch-site': 'none',
168
+ 'sec-fetch-user': '?1',
169
+ 'upgrade-insecure-requests': '1',
170
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.69',
171
+ 'x-edge-shopping-flag': '1',
172
+ 'x-forwarded-for': ip_address,
173
+ }
174
+
175
+ optionsSets = [
176
+ 'saharasugg',
177
+ 'enablenewsfc',
178
+ 'clgalileo',
179
+ 'gencontentv3',
180
+ "nlu_direct_response_filter",
181
+ "deepleo",
182
+ "disable_emoji_spoken_text",
183
+ "responsible_ai_policy_235",
184
+ "enablemm",
185
+ "h3precise"
186
+ "dtappid",
187
+ "cricinfo",
188
+ "cricinfov2",
189
+ "dv3sugg",
190
+ "nojbfedge"
191
+ ]
192
+
193
+ def format_message(msg: dict) -> str:
194
+ return json.dumps(msg, ensure_ascii=False) + Defaults.delimiter
195
+
196
+ def create_message(conversation: Conversation, prompt: str, tone: str, context: str=None) -> str:
197
+ request_id = str(uuid.uuid4())
198
+ struct = {
199
+ 'arguments': [
200
+ {
201
+ 'source': 'cib',
202
+ 'optionsSets': Defaults.optionsSets,
203
+ 'allowedMessageTypes': Defaults.allowedMessageTypes,
204
+ 'sliceIds': Defaults.sliceIds,
205
+ 'traceId': os.urandom(16).hex(),
206
+ 'isStartOfSession': True,
207
+ 'requestId': request_id,
208
+ 'message': Defaults.location | {
209
+ 'author': 'user',
210
+ 'inputMethod': 'Keyboard',
211
+ 'text': prompt,
212
+ 'messageType': 'Chat',
213
+ 'requestId': request_id,
214
+ 'messageId': request_id,
215
+ },
216
+ 'tone': tone,
217
+ 'spokenTextMode': 'None',
218
+ 'conversationId': conversation.conversationId,
219
+ 'participant': {
220
+ 'id': conversation.clientId
221
+ },
222
+ }
223
+ ],
224
+ 'invocationId': '1',
225
+ 'target': 'chat',
226
+ 'type': 4
227
+ }
228
+
229
+ if context:
230
+ struct['arguments'][0]['previousMessages'] = [{
231
+ "author": "user",
232
+ "description": context,
233
+ "contextType": "WebPage",
234
+ "messageType": "Context",
235
+ "messageId": "discover-web--page-ping-mriduna-----"
236
+ }]
237
+ return format_message(struct)
238
+
239
+ async def stream_generate(
240
+ prompt: str,
241
+ tone: str,
242
+ context: str = None,
243
+ proxy: str = None,
244
+ cookies: dict = None
245
+ ):
246
+ async with ClientSession(
247
+ timeout=ClientTimeout(total=900),
248
+ cookies=cookies,
249
+ headers=Defaults.headers,
250
+ ) as session:
251
+ conversation = await create_conversation(session, proxy)
252
+ try:
253
+ async with session.ws_connect(
254
+ f'wss://sydney.bing.com/sydney/ChatHub',
255
+ autoping=False,
256
+ params={'sec_access_token': conversation.conversationSignature},
257
+ proxy=proxy
258
+ ) as wss:
259
+
260
+ await wss.send_str(format_message({'protocol': 'json', 'version': 1}))
261
+ await wss.receive(timeout=900)
262
+ await wss.send_str(create_message(conversation, prompt, tone, context))
263
+
264
+ response_txt = ''
265
+ returned_text = ''
266
+ final = False
267
+
268
+ while not final:
269
+ msg = await wss.receive(timeout=900)
270
+ objects = msg.data.split(Defaults.delimiter)
271
+ for obj in objects:
272
+ if obj is None or not obj:
273
+ continue
274
+
275
+ response = json.loads(obj)
276
+ if response.get('type') == 1 and response['arguments'][0].get('messages'):
277
+ message = response['arguments'][0]['messages'][0]
278
+ if (message['contentOrigin'] != 'Apology'):
279
+ if 'adaptiveCards' in message:
280
+ card = message['adaptiveCards'][0]['body'][0]
281
+ if "text" in card:
282
+ response_txt = card.get('text')
283
+ if message.get('messageType'):
284
+ inline_txt = card['inlines'][0].get('text')
285
+ response_txt += inline_txt + '\n'
286
+ elif message.get('contentType') == "IMAGE":
287
+ query = urllib.parse.quote(message.get('text'))
288
+ url = f"\nhttps://www.bing.com/images/create?q={query}"
289
+ response_txt += url
290
+ final = True
291
+ if response_txt.startswith(returned_text):
292
+ new = response_txt[len(returned_text):]
293
+ if new != "\n":
294
+ yield new
295
+ returned_text = response_txt
296
+ elif response.get('type') == 2:
297
+ result = response['item']['result']
298
+ if result.get('error'):
299
+ raise Exception(f"{result['value']}: {result['message']}")
300
+ return
301
+ finally:
302
+ await delete_conversation(session, conversation, proxy)
g4f/Provider/ChatBase.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+
5
+ from ..typing import AsyncResult, Messages
6
+ from .base_provider import AsyncGeneratorProvider
7
+
8
+
9
+ class ChatBase(AsyncGeneratorProvider):
10
+ url = "https://www.chatbase.co"
11
+ supports_gpt_35_turbo = True
12
+ supports_gpt_4 = True
13
+ working = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ **kwargs
22
+ ) -> AsyncResult:
23
+ if model == "gpt-4":
24
+ chat_id = "quran---tafseer-saadi-pdf-wbgknt7zn"
25
+ elif model == "gpt-3.5-turbo" or not model:
26
+ chat_id = "chatbase--1--pdf-p680fxvnm"
27
+ else:
28
+ raise ValueError(f"Model are not supported: {model}")
29
+ headers = {
30
+ "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
31
+ "Accept" : "*/*",
32
+ "Accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
33
+ "Origin" : cls.url,
34
+ "Referer" : cls.url + "/",
35
+ "Sec-Fetch-Dest" : "empty",
36
+ "Sec-Fetch-Mode" : "cors",
37
+ "Sec-Fetch-Site" : "same-origin",
38
+ }
39
+ async with ClientSession(
40
+ headers=headers
41
+ ) as session:
42
+ data = {
43
+ "messages": messages,
44
+ "captchaCode": "hadsa",
45
+ "chatId": chat_id,
46
+ "conversationId": f"kcXpqEnqUie3dnJlsRi_O-{chat_id}"
47
+ }
48
+ async with session.post("https://www.chatbase.co/api/fe/chat", json=data, proxy=proxy) as response:
49
+ response.raise_for_status()
50
+ async for stream in response.content.iter_any():
51
+ yield stream.decode()
52
+
53
+
54
+ @classmethod
55
+ @property
56
+ def params(cls):
57
+ params = [
58
+ ("model", "str"),
59
+ ("messages", "list[dict[str, str]]"),
60
+ ("stream", "bool"),
61
+ ]
62
+ param = ", ".join([": ".join(p) for p in params])
63
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
g4f/Provider/ChatForAi.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ..typing import AsyncResult, Messages
4
+ from ..requests import StreamSession
5
+ from .base_provider import AsyncGeneratorProvider
6
+
7
+
8
+ class ChatForAi(AsyncGeneratorProvider):
9
+ url = "https://chatforai.com"
10
+ supports_gpt_35_turbo = True
11
+ working = True
12
+
13
+ @classmethod
14
+ async def create_async_generator(
15
+ cls,
16
+ model: str,
17
+ messages: Messages,
18
+ proxy: str = None,
19
+ timeout: int = 120,
20
+ **kwargs
21
+ ) -> AsyncResult:
22
+ async with StreamSession(impersonate="chrome107", proxies={"https": proxy}, timeout=timeout) as session:
23
+ prompt = messages[-1]["content"]
24
+ data = {
25
+ "conversationId": "temp",
26
+ "conversationType": "chat_continuous",
27
+ "botId": "chat_continuous",
28
+ "globalSettings":{
29
+ "baseUrl": "https://api.openai.com",
30
+ "model": model if model else "gpt-3.5-turbo",
31
+ "messageHistorySize": 5,
32
+ "temperature": 0.7,
33
+ "top_p": 1,
34
+ **kwargs
35
+ },
36
+ "botSettings": {},
37
+ "prompt": prompt,
38
+ "messages": messages,
39
+ }
40
+ async with session.post(f"{cls.url}/api/handle/provider-openai", json=data) as response:
41
+ response.raise_for_status()
42
+ async for chunk in response.iter_content():
43
+ yield chunk.decode()
44
+
45
+ @classmethod
46
+ @property
47
+ def params(cls):
48
+ params = [
49
+ ("model", "str"),
50
+ ("messages", "list[dict[str, str]]"),
51
+ ("stream", "bool"),
52
+ ]
53
+ param = ", ".join([": ".join(p) for p in params])
54
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
g4f/Provider/Chatgpt4Online.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from aiohttp import ClientSession
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from .base_provider import AsyncGeneratorProvider
8
+
9
+
10
+ class Chatgpt4Online(AsyncGeneratorProvider):
11
+ url = "https://chatgpt4online.org"
12
+ supports_gpt_35_turbo = True
13
+ working = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ **kwargs
22
+ ) -> AsyncResult:
23
+ async with ClientSession() as session:
24
+ data = {
25
+ "botId": "default",
26
+ "customId": None,
27
+ "session": "N/A",
28
+ "chatId": "",
29
+ "contextId": 58,
30
+ "messages": messages,
31
+ "newMessage": messages[-1]["content"],
32
+ "stream": True
33
+ }
34
+ async with session.post(cls.url + "/wp-json/mwai-ui/v1/chats/submit", json=data, proxy=proxy) as response:
35
+ response.raise_for_status()
36
+ async for line in response.content:
37
+ if line.startswith(b"data: "):
38
+ line = json.loads(line[6:])
39
+ if line["type"] == "live":
40
+ yield line["data"]
g4f/Provider/ChatgptAi.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from aiohttp import ClientSession
5
+
6
+ from ..typing import Messages
7
+ from .base_provider import AsyncProvider, format_prompt
8
+
9
+
10
+ class ChatgptAi(AsyncProvider):
11
+ url: str = "https://chatgpt.ai/"
12
+ working = True
13
+ supports_gpt_35_turbo = True
14
+ _nonce = None
15
+ _post_id = None
16
+ _bot_id = None
17
+
18
+ @classmethod
19
+ async def create_async(
20
+ cls,
21
+ model: str,
22
+ messages: Messages,
23
+ proxy: str = None,
24
+ **kwargs
25
+ ) -> str:
26
+ headers = {
27
+ "authority" : "chatgpt.ai",
28
+ "accept" : "*/*",
29
+ "accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
30
+ "cache-control" : "no-cache",
31
+ "origin" : "https://chatgpt.ai",
32
+ "pragma" : "no-cache",
33
+ "referer" : cls.url,
34
+ "sec-ch-ua" : '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
35
+ "sec-ch-ua-mobile" : "?0",
36
+ "sec-ch-ua-platform" : '"Windows"',
37
+ "sec-fetch-dest" : "empty",
38
+ "sec-fetch-mode" : "cors",
39
+ "sec-fetch-site" : "same-origin",
40
+ "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
41
+ }
42
+ async with ClientSession(
43
+ headers=headers
44
+ ) as session:
45
+ if not cls._nonce:
46
+ async with session.get(cls.url, proxy=proxy) as response:
47
+ response.raise_for_status()
48
+ text = await response.text()
49
+ result = re.search(r'data-nonce="(.*?)"', text)
50
+ if result:
51
+ cls._nonce = result.group(1)
52
+ result = re.search(r'data-post-id="(.*?)"', text)
53
+ if result:
54
+ cls._post_id = result.group(1)
55
+ result = re.search(r'data-bot-id="(.*?)"', text)
56
+ if result:
57
+ cls._bot_id = result.group(1)
58
+ if not cls._nonce or not cls._post_id or not cls._bot_id:
59
+ raise RuntimeError("Nonce, post-id or bot-id not found")
60
+
61
+ data = {
62
+ "_wpnonce": cls._nonce,
63
+ "post_id": cls._post_id,
64
+ "url": "https://chatgpt.ai",
65
+ "action": "wpaicg_chat_shortcode_message",
66
+ "message": format_prompt(messages),
67
+ "bot_id": cls._bot_id
68
+ }
69
+ async with session.post(
70
+ "https://chatgpt.ai/wp-admin/admin-ajax.php",
71
+ proxy=proxy,
72
+ data=data
73
+ ) as response:
74
+ response.raise_for_status()
75
+ return (await response.json())["data"]
g4f/Provider/ChatgptDemo.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import time, json, re
4
+ from aiohttp import ClientSession
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from .base_provider import AsyncGeneratorProvider
8
+ from .helper import format_prompt
9
+
10
+ class ChatgptDemo(AsyncGeneratorProvider):
11
+ url = "https://chat.chatgptdemo.net"
12
+ supports_gpt_35_turbo = True
13
+ working = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ **kwargs
22
+ ) -> AsyncResult:
23
+ headers = {
24
+ "authority": "chat.chatgptdemo.net",
25
+ "accept-language": "de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US",
26
+ "origin": "https://chat.chatgptdemo.net",
27
+ "referer": "https://chat.chatgptdemo.net/",
28
+ "sec-ch-ua": '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
29
+ "sec-ch-ua-mobile": "?0",
30
+ "sec-ch-ua-platform": '"Linux"',
31
+ "sec-fetch-dest": "empty",
32
+ "sec-fetch-mode": "cors",
33
+ "sec-fetch-site": "same-origin",
34
+ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
35
+ }
36
+ async with ClientSession(headers=headers) as session:
37
+ async with session.get(f"{cls.url}/", proxy=proxy) as response:
38
+ response.raise_for_status()
39
+ response = await response.text()
40
+ result = re.search(r'<div id="USERID" style="display: none">(.*?)<\/div>', response)
41
+ if not result:
42
+ raise RuntimeError("No user id found")
43
+ user_id = result.group(1)
44
+ async with session.post(f"{cls.url}/new_chat", json={"user_id": user_id}, proxy=proxy) as response:
45
+ response.raise_for_status()
46
+ chat_id = (await response.json())["id_"]
47
+ if not chat_id:
48
+ raise RuntimeError("Could not create new chat")
49
+ data = {
50
+ "question": format_prompt(messages),
51
+ "chat_id": chat_id,
52
+ "timestamp": int(time.time()*1000),
53
+ }
54
+ async with session.post(f"{cls.url}/chat_api_stream", json=data, proxy=proxy) as response:
55
+ response.raise_for_status()
56
+ async for line in response.content:
57
+ if line.startswith(b"data: "):
58
+ line = json.loads(line[6:-1])
59
+ chunk = line["choices"][0]["delta"].get("content")
60
+ if chunk:
61
+ yield chunk
g4f/Provider/ChatgptDuo.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ..typing import Messages
4
+ from curl_cffi.requests import AsyncSession
5
+ from .base_provider import AsyncProvider, format_prompt
6
+
7
+
8
+ class ChatgptDuo(AsyncProvider):
9
+ url = "https://chatgptduo.com"
10
+ supports_gpt_35_turbo = True
11
+ working = True
12
+
13
+ @classmethod
14
+ async def create_async(
15
+ cls,
16
+ model: str,
17
+ messages: Messages,
18
+ proxy: str = None,
19
+ timeout: int = 120,
20
+ **kwargs
21
+ ) -> str:
22
+ async with AsyncSession(
23
+ impersonate="chrome107",
24
+ proxies={"https": proxy},
25
+ timeout=timeout
26
+ ) as session:
27
+ prompt = format_prompt(messages),
28
+ data = {
29
+ "prompt": prompt,
30
+ "search": prompt,
31
+ "purpose": "ask",
32
+ }
33
+ response = await session.post(f"{cls.url}/", data=data)
34
+ response.raise_for_status()
35
+ data = response.json()
36
+
37
+ cls._sources = [{
38
+ "title": source["title"],
39
+ "url": source["link"],
40
+ "snippet": source["snippet"]
41
+ } for source in data["results"]]
42
+
43
+ return data["answer"]
44
+
45
+ @classmethod
46
+ def get_sources(cls):
47
+ return cls._sources
48
+
49
+ @classmethod
50
+ @property
51
+ def params(cls):
52
+ params = [
53
+ ("model", "str"),
54
+ ("messages", "list[dict[str, str]]"),
55
+ ("stream", "bool"),
56
+ ]
57
+ param = ", ".join([": ".join(p) for p in params])
58
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
g4f/Provider/ChatgptX.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import json
5
+
6
+ from aiohttp import ClientSession
7
+ from ..typing import AsyncResult, Messages
8
+ from .base_provider import AsyncGeneratorProvider
9
+ from .helper import format_prompt
10
+
11
+
12
+ class ChatgptX(AsyncGeneratorProvider):
13
+ url = "https://chatgptx.de"
14
+ supports_gpt_35_turbo = True
15
+ working = True
16
+
17
+ @classmethod
18
+ async def create_async_generator(
19
+ cls,
20
+ model: str,
21
+ messages: Messages,
22
+ proxy: str = None,
23
+ **kwargs
24
+ ) -> AsyncResult:
25
+ headers = {
26
+ 'accept-language': 'de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US',
27
+ 'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
28
+ 'sec-ch-ua-mobile': '?0',
29
+ 'sec-ch-ua-platform': 'Linux',
30
+ 'sec-fetch-dest': 'empty',
31
+ 'sec-fetch-mode': 'cors',
32
+ 'sec-fetch-site': 'same-origin',
33
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
34
+ }
35
+ async with ClientSession(headers=headers) as session:
36
+ async with session.get(f"{cls.url}/", proxy=proxy) as response:
37
+ response = await response.text()
38
+ result = re.search(r'<meta name="csrf-token" content="(.*?)"', response)
39
+ if result:
40
+ csrf_token = result.group(1)
41
+ result = re.search(r"openconversions\('(.*?)'\)", response)
42
+ if result:
43
+ chat_id = result.group(1)
44
+ result = re.search(r'<input type="hidden" id="user_id" value="(.*?)"', response)
45
+ if result:
46
+ user_id = result.group(1)
47
+
48
+ if not csrf_token or not chat_id or not user_id:
49
+ raise RuntimeError("Missing csrf_token, chat_id or user_id")
50
+
51
+ data = {
52
+ '_token': csrf_token,
53
+ 'user_id': user_id,
54
+ 'chats_id': chat_id,
55
+ 'prompt': format_prompt(messages),
56
+ 'current_model': "gpt3"
57
+ }
58
+ headers = {
59
+ 'authority': 'chatgptx.de',
60
+ 'accept': 'application/json, text/javascript, */*; q=0.01',
61
+ 'origin': cls.url,
62
+ 'referer': f'{cls.url}/',
63
+ 'x-csrf-token': csrf_token,
64
+ 'x-requested-with': 'XMLHttpRequest'
65
+ }
66
+ async with session.post(cls.url + '/sendchat', data=data, headers=headers, proxy=proxy) as response:
67
+ response.raise_for_status()
68
+ chat = await response.json()
69
+ if "response" not in chat or not chat["response"]:
70
+ raise RuntimeError(f'Response: {chat}')
71
+ headers = {
72
+ 'authority': 'chatgptx.de',
73
+ 'accept': 'text/event-stream',
74
+ 'referer': f'{cls.url}/',
75
+ 'x-csrf-token': csrf_token,
76
+ 'x-requested-with': 'XMLHttpRequest'
77
+ }
78
+ data = {
79
+ "user_id": user_id,
80
+ "chats_id": chat_id,
81
+ "prompt": format_prompt(messages),
82
+ "current_model": "gpt3",
83
+ "conversions_id": chat["conversions_id"],
84
+ "ass_conversions_id": chat["ass_conversions_id"],
85
+ }
86
+ async with session.get(f'{cls.url}/chats_stream', params=data, headers=headers, proxy=proxy) as response:
87
+ response.raise_for_status()
88
+ async for line in response.content:
89
+ if line.startswith(b"data: "):
90
+ row = line[6:-1]
91
+ if row == b"[DONE]":
92
+ break
93
+ try:
94
+ content = json.loads(row)["choices"][0]["delta"].get("content")
95
+ except:
96
+ raise RuntimeError(f"Broken line: {line.decode()}")
97
+ if content:
98
+ yield content
g4f/Provider/Cromicle.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+ from hashlib import sha256
5
+ from ..typing import AsyncResult, Messages, Dict
6
+
7
+ from .base_provider import AsyncGeneratorProvider
8
+ from .helper import format_prompt
9
+
10
+
11
+ class Cromicle(AsyncGeneratorProvider):
12
+ url: str = 'https://cromicle.top'
13
+ working: bool = True
14
+ supports_gpt_35_turbo: bool = True
15
+
16
+ @classmethod
17
+ async def create_async_generator(
18
+ cls,
19
+ model: str,
20
+ messages: Messages,
21
+ proxy: str = None,
22
+ **kwargs
23
+ ) -> AsyncResult:
24
+ async with ClientSession(
25
+ headers=_create_header()
26
+ ) as session:
27
+ async with session.post(
28
+ f'{cls.url}/chat',
29
+ proxy=proxy,
30
+ json=_create_payload(format_prompt(messages))
31
+ ) as response:
32
+ response.raise_for_status()
33
+ async for stream in response.content.iter_any():
34
+ if stream:
35
+ yield stream.decode()
36
+
37
+
38
+ def _create_header() -> Dict[str, str]:
39
+ return {
40
+ 'accept': '*/*',
41
+ 'content-type': 'application/json',
42
+ }
43
+
44
+
45
+ def _create_payload(message: str) -> Dict[str, str]:
46
+ return {
47
+ 'message': message,
48
+ 'token': 'abc',
49
+ 'hash': sha256('abc'.encode() + message.encode()).hexdigest()
50
+ }
g4f/Provider/FreeGpt.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import time, hashlib, random
4
+
5
+ from ..typing import AsyncResult, Messages
6
+ from ..requests import StreamSession
7
+ from .base_provider import AsyncGeneratorProvider
8
+
9
+ domains = [
10
+ 'https://k.aifree.site',
11
+ 'https://p.aifree.site'
12
+ ]
13
+
14
+ class FreeGpt(AsyncGeneratorProvider):
15
+ url = "https://freegpts1.aifree.site/"
16
+ supports_gpt_35_turbo = True
17
+ working = True
18
+
19
+ @classmethod
20
+ async def create_async_generator(
21
+ cls,
22
+ model: str,
23
+ messages: Messages,
24
+ proxy: str = None,
25
+ timeout: int = 120,
26
+ **kwargs
27
+ ) -> AsyncResult:
28
+ async with StreamSession(
29
+ impersonate="chrome107",
30
+ timeout=timeout,
31
+ proxies={"https": proxy}
32
+ ) as session:
33
+ prompt = messages[-1]["content"]
34
+ timestamp = int(time.time())
35
+ data = {
36
+ "messages": messages,
37
+ "time": timestamp,
38
+ "pass": None,
39
+ "sign": generate_signature(timestamp, prompt)
40
+ }
41
+ url = random.choice(domains)
42
+ async with session.post(f"{url}/api/generate", json=data) as response:
43
+ response.raise_for_status()
44
+ async for chunk in response.iter_content():
45
+ yield chunk.decode()
46
+
47
+ @classmethod
48
+ @property
49
+ def params(cls):
50
+ params = [
51
+ ("model", "str"),
52
+ ("messages", "list[dict[str, str]]"),
53
+ ("stream", "bool"),
54
+ ]
55
+ param = ", ".join([": ".join(p) for p in params])
56
+ return f"g4f.provider.{cls.__name__} supports: ({param})"
57
+
58
+ def generate_signature(timestamp: int, message: str, secret: str = ""):
59
+ data = f"{timestamp}:{message}:{secret}"
60
+ return hashlib.sha256(data.encode()).hexdigest()
g4f/Provider/GPTalk.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import secrets, time, json
4
+ from aiohttp import ClientSession
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from .base_provider import AsyncGeneratorProvider
8
+ from .helper import format_prompt
9
+
10
+
11
+ class GPTalk(AsyncGeneratorProvider):
12
+ url = "https://gptalk.net"
13
+ supports_gpt_35_turbo = True
14
+ working = True
15
+ _auth = None
16
+
17
+ @classmethod
18
+ async def create_async_generator(
19
+ cls,
20
+ model: str,
21
+ messages: Messages,
22
+ proxy: str = None,
23
+ **kwargs
24
+ ) -> AsyncResult:
25
+ if not model:
26
+ model = "gpt-3.5-turbo"
27
+ timestamp = int(time.time())
28
+ headers = {
29
+ 'authority': 'gptalk.net',
30
+ 'accept': '*/*',
31
+ 'accept-language': 'de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6,nl;q=0.5,zh-CN;q=0.4,zh-TW;q=0.3,zh;q=0.2',
32
+ 'content-type': 'application/json',
33
+ 'origin': 'https://gptalk.net',
34
+ 'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
35
+ 'sec-ch-ua-mobile': '?0',
36
+ 'sec-ch-ua-platform': '"Linux"',
37
+ 'sec-fetch-dest': 'empty',
38
+ 'sec-fetch-mode': 'cors',
39
+ 'sec-fetch-site': 'same-origin',
40
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
41
+ 'x-auth-appid': '2229',
42
+ 'x-auth-openid': '',
43
+ 'x-auth-platform': '',
44
+ 'x-auth-timestamp': f"{timestamp}",
45
+ }
46
+ async with ClientSession(headers=headers) as session:
47
+ if not cls._auth or cls._auth["expires_at"] < timestamp:
48
+ data = {
49
+ "fingerprint": secrets.token_hex(16).zfill(32),
50
+ "platform": "fingerprint"
51
+ }
52
+ async with session.post(cls.url + "/api/chatgpt/user/login", json=data, proxy=proxy) as response:
53
+ response.raise_for_status()
54
+ cls._auth = (await response.json())["data"]
55
+ data = {
56
+ "content": format_prompt(messages),
57
+ "accept": "stream",
58
+ "from": 1,
59
+ "model": model,
60
+ "is_mobile": 0,
61
+ "user_agent": headers["user-agent"],
62
+ "is_open_ctx": 0,
63
+ "prompt": "",
64
+ "roid": 111,
65
+ "temperature": 0,
66
+ "ctx_msg_count": 3,
67
+ "created_at": timestamp
68
+ }
69
+ headers = {
70
+ 'authorization': f'Bearer {cls._auth["token"]}',
71
+ }
72
+ async with session.post(cls.url + "/api/chatgpt/chatapi/text", json=data, headers=headers, proxy=proxy) as response:
73
+ response.raise_for_status()
74
+ token = (await response.json())["data"]["token"]
75
+ last_message = ""
76
+ async with session.get(cls.url + "/api/chatgpt/chatapi/stream", params={"token": token}, proxy=proxy) as response:
77
+ response.raise_for_status()
78
+ async for line in response.content:
79
+ if line.startswith(b"data: "):
80
+ if line.startswith(b"data: [DONE]"):
81
+ break
82
+ message = json.loads(line[6:-1])["content"]
83
+ yield message[len(last_message):]
84
+ last_message = message
g4f/Provider/GptForLove.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+ import execjs, os, json
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from .base_provider import AsyncGeneratorProvider
8
+ from .helper import format_prompt
9
+
10
+ class GptForLove(AsyncGeneratorProvider):
11
+ url = "https://ai18.gptforlove.com"
12
+ supports_gpt_35_turbo = True
13
+ working = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ **kwargs
22
+ ) -> AsyncResult:
23
+ if not model:
24
+ model = "gpt-3.5-turbo"
25
+ headers = {
26
+ "authority": "api.gptplus.one",
27
+ "accept": "application/json, text/plain, */*",
28
+ "accept-language": "de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6,nl;q=0.5,zh-CN;q=0.4,zh-TW;q=0.3,zh;q=0.2",
29
+ "content-type": "application/json",
30
+ "origin": cls.url,
31
+ "referer": f"{cls.url}/",
32
+ "sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
33
+ "sec-ch-ua-mobile": "?0",
34
+ "sec-ch-ua-platform": "Linux",
35
+ "sec-fetch-dest": "empty",
36
+ "sec-fetch-mode": "cors",
37
+ "sec-fetch-site": "cross-site",
38
+ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
39
+ }
40
+ async with ClientSession(headers=headers) as session:
41
+ prompt = format_prompt(messages)
42
+ data = {
43
+ "prompt": prompt,
44
+ "options": {},
45
+ "systemMessage": "You are ChatGPT, the version is GPT3.5, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using markdown.",
46
+ "temperature": 0.8,
47
+ "top_p": 1,
48
+ "secret": get_secret(),
49
+ **kwargs
50
+ }
51
+ async with session.post("https://api.gptplus.one/chat-process", json=data, proxy=proxy) as response:
52
+ response.raise_for_status()
53
+ async for line in response.content:
54
+ try:
55
+ line = json.loads(line)
56
+ except:
57
+ raise RuntimeError(f"Broken line: {line}")
58
+ if "detail" in line:
59
+ content = line["detail"]["choices"][0]["delta"].get("content")
60
+ if content:
61
+ yield content
62
+ elif "10分钟内提问超过了5次" in line:
63
+ raise RuntimeError("Rate limit reached")
64
+ else:
65
+ raise RuntimeError(f"Response: {line}")
66
+
67
+
68
+ def get_secret() -> str:
69
+ dir = os.path.dirname(__file__)
70
+ dir += '/npm/node_modules/crypto-js'
71
+ source = """
72
+ CryptoJS = require('{dir}/crypto-js')
73
+ var k = '14487141bvirvvG'
74
+ , e = Math.floor(new Date().getTime() / 1e3);
75
+ var t = CryptoJS.enc.Utf8.parse(e)
76
+ , o = CryptoJS.AES.encrypt(t, k, {
77
+ mode: CryptoJS.mode.ECB,
78
+ padding: CryptoJS.pad.Pkcs7
79
+ });
80
+ return o.toString()
81
+ """
82
+ source = source.replace('{dir}', dir)
83
+ return execjs.compile(source).call('')
g4f/Provider/GptGo.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from aiohttp import ClientSession
4
+ import json
5
+
6
+ from ..typing import AsyncResult, Messages
7
+ from .base_provider import AsyncGeneratorProvider, format_prompt
8
+
9
+
10
+ class GptGo(AsyncGeneratorProvider):
11
+ url = "https://gptgo.ai"
12
+ supports_gpt_35_turbo = True
13
+ working = True
14
+
15
+ @classmethod
16
+ async def create_async_generator(
17
+ cls,
18
+ model: str,
19
+ messages: Messages,
20
+ proxy: str = None,
21
+ **kwargs
22
+ ) -> AsyncResult:
23
+ headers = {
24
+ "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
25
+ "Accept" : "*/*",
26
+ "Accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
27
+ "Origin" : cls.url,
28
+ "Referer" : cls.url + "/",
29
+ "Sec-Fetch-Dest" : "empty",
30
+ "Sec-Fetch-Mode" : "cors",
31
+ "Sec-Fetch-Site" : "same-origin",
32
+ }
33
+ async with ClientSession(
34
+ headers=headers
35
+ ) as session:
36
+ async with session.get(
37
+ "https://gptgo.ai/action_get_token.php",
38
+ params={
39
+ "q": format_prompt(messages),
40
+ "hlgpt": "default",
41
+ "hl": "en"
42
+ },
43
+ proxy=proxy
44
+ ) as response:
45
+ response.raise_for_status()
46
+ token = (await response.json(content_type=None))["token"]
47
+
48
+ async with session.get(
49
+ "https://gptgo.ai/action_ai_gpt.php",
50
+ params={
51
+ "token": token,
52
+ },
53
+ proxy=proxy
54
+ ) as response:
55
+ response.raise_for_status()
56
+ start = "data: "
57
+ async for line in response.content:
58
+ line = line.decode()
59
+ if line.startswith("data: "):
60
+ if line.startswith("data: [DONE]"):
61
+ break
62
+ line = json.loads(line[len(start):-1])
63
+ if line["choices"][0]["finish_reason"] == "stop":
64
+ break
65
+ content = line["choices"][0]["delta"].get("content")
66
+ if content:
67
+ yield content
68
+
69
+
70
+ @classmethod
71
+ @property
72
+ def params(cls):
73
+ params = [
74
+ ("model", "str"),
75
+ ("messages", "list[dict[str, str]]"),
76
+ ("stream", "bool"),
77
+ ("proxy", "str"),
78
+ ("temperature", "float"),
79
+ ]
80
+ param = ", ".join([": ".join(p) for p in params])
81
+ return f"g4f.provider.{cls.__name__} supports: ({param})"