jsr90 sheonhan commited on
Commit
8bed0a4
·
0 Parent(s):

Duplicate from HuggingFaceH4/starchat-playground

Browse files

Co-authored-by: Sheon Han <[email protected]>

Files changed (9) hide show
  1. .gitattributes +35 -0
  2. .gitignore +162 -0
  3. LICENSE +203 -0
  4. README.md +14 -0
  5. app.py +371 -0
  6. dialogues.py +241 -0
  7. requirements.txt +2 -0
  8. share_btn.py +111 -0
  9. thumbnail.png +0 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ StarCoderBanner.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+
162
+ data/
LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2023- The Hugging Face team. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2023 Hugging Face
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: StarChat Playground
3
+ emoji: ⭐️💬
4
+ colorFrom: pink
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 3.33.1
8
+ app_file: app.py
9
+ pinned: true
10
+ license: mit
11
+ duplicated_from: HuggingFaceH4/starchat-playground
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+ import re
4
+ from io import StringIO
5
+
6
+ import gradio as gr
7
+ import pandas as pd
8
+ from huggingface_hub import upload_file
9
+ from text_generation import Client
10
+
11
+ from dialogues import DialogueTemplate
12
+ from share_btn import (community_icon_html, loading_icon_html, share_btn_css,
13
+ share_js)
14
+
15
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
16
+ API_TOKEN = os.environ.get("API_TOKEN", None)
17
+ DIALOGUES_DATASET = "HuggingFaceH4/starchat_playground_dialogues"
18
+
19
+ model2endpoint = {
20
+ "starchat-alpha": "https://api-inference.huggingface.co/models/HuggingFaceH4/starcoderbase-finetuned-oasst1",
21
+ "starchat-beta": "https://ddimh86h0wqthbhy.us-east-1.aws.endpoints.huggingface.cloud",
22
+ }
23
+ model_names = list(model2endpoint.keys())
24
+
25
+
26
+ def save_inputs_and_outputs(now, inputs, outputs, generate_kwargs, model):
27
+ buffer = StringIO()
28
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
29
+ file_name = f"prompts_{timestamp}.jsonl"
30
+ data = {"model": model, "inputs": inputs, "outputs": outputs, "generate_kwargs": generate_kwargs}
31
+ pd.DataFrame([data]).to_json(buffer, orient="records", lines=True)
32
+
33
+ # Push to Hub
34
+ upload_file(
35
+ path_in_repo=f"{now.date()}/{now.hour}/{file_name}",
36
+ path_or_fileobj=buffer.getvalue().encode(),
37
+ repo_id=DIALOGUES_DATASET,
38
+ token=HF_TOKEN,
39
+ repo_type="dataset",
40
+ )
41
+
42
+ # Clean and rerun
43
+ buffer.close()
44
+
45
+
46
+ def get_total_inputs(inputs, chatbot, preprompt, user_name, assistant_name, sep):
47
+ past = []
48
+ for data in chatbot:
49
+ user_data, model_data = data
50
+
51
+ if not user_data.startswith(user_name):
52
+ user_data = user_name + user_data
53
+ if not model_data.startswith(sep + assistant_name):
54
+ model_data = sep + assistant_name + model_data
55
+
56
+ past.append(user_data + model_data.rstrip() + sep)
57
+
58
+ if not inputs.startswith(user_name):
59
+ inputs = user_name + inputs
60
+
61
+ total_inputs = preprompt + "".join(past) + inputs + sep + assistant_name.rstrip()
62
+
63
+ return total_inputs
64
+
65
+
66
+ def wrap_html_code(text):
67
+ pattern = r"<.*?>"
68
+ matches = re.findall(pattern, text)
69
+ if len(matches) > 0:
70
+ return f"```{text}```"
71
+ else:
72
+ return text
73
+
74
+
75
+ def has_no_history(chatbot, history):
76
+ return not chatbot and not history
77
+
78
+
79
+ def generate(
80
+ model_name,
81
+ system_message,
82
+ user_message,
83
+ chatbot,
84
+ history,
85
+ temperature,
86
+ top_k,
87
+ top_p,
88
+ max_new_tokens,
89
+ repetition_penalty,
90
+ do_save=True,
91
+ ):
92
+ client = Client(
93
+ model2endpoint[model_name],
94
+ headers={"Authorization": f"Bearer {API_TOKEN}"},
95
+ )
96
+ # Don't return meaningless message when the input is empty
97
+ if not user_message:
98
+ print("Empty input")
99
+
100
+ history.append(user_message)
101
+
102
+ past_messages = []
103
+ for data in chatbot:
104
+ user_data, model_data = data
105
+
106
+ past_messages.extend(
107
+ [{"role": "user", "content": user_data}, {"role": "assistant", "content": model_data.rstrip()}]
108
+ )
109
+
110
+ if len(past_messages) < 1:
111
+ dialogue_template = DialogueTemplate(
112
+ system=system_message, messages=[{"role": "user", "content": user_message}]
113
+ )
114
+ prompt = dialogue_template.get_inference_prompt()
115
+ else:
116
+ dialogue_template = DialogueTemplate(
117
+ system=system_message, messages=past_messages + [{"role": "user", "content": user_message}]
118
+ )
119
+ prompt = dialogue_template.get_inference_prompt()
120
+
121
+ generate_kwargs = {
122
+ "temperature": temperature,
123
+ "top_k": top_k,
124
+ "top_p": top_p,
125
+ "max_new_tokens": max_new_tokens,
126
+ }
127
+
128
+ temperature = float(temperature)
129
+ if temperature < 1e-2:
130
+ temperature = 1e-2
131
+ top_p = float(top_p)
132
+
133
+ generate_kwargs = dict(
134
+ temperature=temperature,
135
+ max_new_tokens=max_new_tokens,
136
+ top_p=top_p,
137
+ repetition_penalty=repetition_penalty,
138
+ do_sample=True,
139
+ truncate=999,
140
+ seed=42,
141
+ stop_sequences=["<|end|>"],
142
+ )
143
+
144
+ stream = client.generate_stream(
145
+ prompt,
146
+ **generate_kwargs,
147
+ )
148
+
149
+ output = ""
150
+ for idx, response in enumerate(stream):
151
+ if response.token.special:
152
+ continue
153
+ output += response.token.text
154
+ if idx == 0:
155
+ history.append(" " + output)
156
+ else:
157
+ history[-1] = output
158
+
159
+ chat = [
160
+ (wrap_html_code(history[i].strip()), wrap_html_code(history[i + 1].strip()))
161
+ for i in range(0, len(history) - 1, 2)
162
+ ]
163
+
164
+ # chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)]
165
+
166
+ yield chat, history, user_message, ""
167
+
168
+ if HF_TOKEN and do_save:
169
+ try:
170
+ now = datetime.datetime.now()
171
+ current_time = now.strftime("%Y-%m-%d %H:%M:%S")
172
+ print(f"[{current_time}] Pushing prompt and completion to the Hub")
173
+ save_inputs_and_outputs(now, prompt, output, generate_kwargs, model_name)
174
+ except Exception as e:
175
+ print(e)
176
+
177
+ return chat, history, user_message, ""
178
+
179
+
180
+ examples = [
181
+ "How can I write a Python function to generate the nth Fibonacci number?",
182
+ "How do I get the current date using shell commands? Explain how it works.",
183
+ "What's the meaning of life?",
184
+ "Write a function in Javascript to reverse words in a given string.",
185
+ "Give the following data {'Name':['Tom', 'Brad', 'Kyle', 'Jerry'], 'Age':[20, 21, 19, 18], 'Height' : [6.1, 5.9, 6.0, 6.1]}. Can you plot one graph with two subplots as columns. The first is a bar graph showing the height of each person. The second is a bargraph showing the age of each person? Draw the graph in seaborn talk mode.",
186
+ "Create a regex to extract dates from logs",
187
+ "How to decode JSON into a typescript object",
188
+ "Write a list into a jsonlines file and save locally",
189
+ ]
190
+
191
+
192
+ def clear_chat():
193
+ return [], []
194
+
195
+
196
+ def process_example(args):
197
+ for [x, y] in generate(args):
198
+ pass
199
+ return [x, y]
200
+
201
+
202
+ title = """<h1 align="center">⭐ StarChat Playground 💬</h1>"""
203
+ custom_css = """
204
+ #banner-image {
205
+ display: block;
206
+ margin-left: auto;
207
+ margin-right: auto;
208
+ }
209
+
210
+ #chat-message {
211
+ font-size: 14px;
212
+ min-height: 300px;
213
+ }
214
+ """
215
+
216
+ with gr.Blocks(analytics_enabled=False, css=custom_css) as demo:
217
+ gr.HTML(title)
218
+
219
+ with gr.Row():
220
+ with gr.Column():
221
+ gr.Image("thumbnail.png", elem_id="banner-image", show_label=False)
222
+ with gr.Column():
223
+ gr.Markdown(
224
+ """
225
+ 💻 This demo showcases a series of **[StarChat](https://huggingface.co/models?search=huggingfaceh4/starchat)** language models, which are fine-tuned versions of the StarCoder family to act as helpful coding assistants. The base model has 16B parameters and was pretrained on one trillion tokens sourced from 80+ programming languages, GitHub issues, Git commits, and Jupyter notebooks (all permissively licensed).
226
+
227
+ 📝 For more details, check out our [blog post](https://huggingface.co/blog/starchat-alpha).
228
+
229
+ ⚠️ **Intended Use**: this app and its [supporting models](https://huggingface.co/models?search=huggingfaceh4/starchat) are provided as educational tools to explain large language model fine-tuning; not to serve as replacement for human expertise.
230
+
231
+ ⚠️ **Known Failure Modes**: the alpha and beta version of **StarChat** have not been aligned to human preferences with techniques like RLHF, so they can produce problematic outputs (especially when prompted to do so). Since the base model was pretrained on a large corpus of code, it may produce code snippets that are syntactically valid but semantically incorrect. For example, it may produce code that does not compile or that produces incorrect results. It may also produce code that is vulnerable to security exploits. We have observed the model also has a tendency to produce false URLs which should be carefully inspected before clicking. For more details on the model's limitations in terms of factuality and biases, see the [model card](https://huggingface.co/HuggingFaceH4/starchat-alpha#bias-risks-and-limitations).
232
+
233
+ ⚠️ **Data Collection**: by default, we are collecting the prompts entered in this app to further improve and evaluate the models. Do **NOT** share any personal or sensitive information while using the app! You can opt out of this data collection by removing the checkbox below.
234
+ """
235
+ )
236
+
237
+ with gr.Row():
238
+ do_save = gr.Checkbox(
239
+ value=True,
240
+ label="Store data",
241
+ info="You agree to the storage of your prompt and generated text for research and development purposes:",
242
+ )
243
+
244
+ with gr.Row():
245
+ selected_model = gr.Radio(choices=model_names, value=model_names[1], label="Select a model")
246
+
247
+ with gr.Accordion(label="System Prompt", open=False, elem_id="parameters-accordion"):
248
+ system_message = gr.Textbox(
249
+ elem_id="system-message",
250
+ placeholder="Below is a conversation between a human user and a helpful AI coding assistant.",
251
+ show_label=False,
252
+ )
253
+ with gr.Row():
254
+ with gr.Box():
255
+ output = gr.Markdown()
256
+ chatbot = gr.Chatbot(elem_id="chat-message", label="Chat")
257
+
258
+ with gr.Row():
259
+ with gr.Column(scale=3):
260
+ user_message = gr.Textbox(placeholder="Enter your message here", show_label=False, elem_id="q-input")
261
+ with gr.Row():
262
+ send_button = gr.Button("Send", elem_id="send-btn", visible=True)
263
+
264
+ # regenerate_button = gr.Button("Regenerate", elem_id="send-btn", visible=True)
265
+
266
+ clear_chat_button = gr.Button("Clear chat", elem_id="clear-btn", visible=True)
267
+
268
+ with gr.Accordion(label="Parameters", open=False, elem_id="parameters-accordion"):
269
+ temperature = gr.Slider(
270
+ label="Temperature",
271
+ value=0.2,
272
+ minimum=0.0,
273
+ maximum=1.0,
274
+ step=0.1,
275
+ interactive=True,
276
+ info="Higher values produce more diverse outputs",
277
+ )
278
+ top_k = gr.Slider(
279
+ label="Top-k",
280
+ value=50,
281
+ minimum=0.0,
282
+ maximum=100,
283
+ step=1,
284
+ interactive=True,
285
+ info="Sample from a shortlist of top-k tokens",
286
+ )
287
+ top_p = gr.Slider(
288
+ label="Top-p (nucleus sampling)",
289
+ value=0.95,
290
+ minimum=0.0,
291
+ maximum=1,
292
+ step=0.05,
293
+ interactive=True,
294
+ info="Higher values sample more low-probability tokens",
295
+ )
296
+ max_new_tokens = gr.Slider(
297
+ label="Max new tokens",
298
+ value=512,
299
+ minimum=0,
300
+ maximum=1024,
301
+ step=4,
302
+ interactive=True,
303
+ info="The maximum numbers of new tokens",
304
+ )
305
+ repetition_penalty = gr.Slider(
306
+ label="Repetition Penalty",
307
+ value=1.2,
308
+ minimum=0.0,
309
+ maximum=10,
310
+ step=0.1,
311
+ interactive=True,
312
+ info="The parameter for repetition penalty. 1.0 means no penalty.",
313
+ )
314
+ # with gr.Group(elem_id="share-btn-container"):
315
+ # community_icon = gr.HTML(community_icon_html, visible=True)
316
+ # loading_icon = gr.HTML(loading_icon_html, visible=True)
317
+ # share_button = gr.Button("Share to community", elem_id="share-btn", visible=True)
318
+ with gr.Row():
319
+ gr.Examples(
320
+ examples=examples,
321
+ inputs=[user_message],
322
+ cache_examples=False,
323
+ fn=process_example,
324
+ outputs=[output],
325
+ )
326
+
327
+ history = gr.State([])
328
+ # To clear out "message" input textbox and use this to regenerate message
329
+ last_user_message = gr.State("")
330
+
331
+ user_message.submit(
332
+ generate,
333
+ inputs=[
334
+ selected_model,
335
+ system_message,
336
+ user_message,
337
+ chatbot,
338
+ history,
339
+ temperature,
340
+ top_k,
341
+ top_p,
342
+ max_new_tokens,
343
+ repetition_penalty,
344
+ do_save,
345
+ ],
346
+ outputs=[chatbot, history, last_user_message, user_message],
347
+ )
348
+
349
+ send_button.click(
350
+ generate,
351
+ inputs=[
352
+ selected_model,
353
+ system_message,
354
+ user_message,
355
+ chatbot,
356
+ history,
357
+ temperature,
358
+ top_k,
359
+ top_p,
360
+ max_new_tokens,
361
+ repetition_penalty,
362
+ do_save,
363
+ ],
364
+ outputs=[chatbot, history, last_user_message, user_message],
365
+ )
366
+
367
+ clear_chat_button.click(clear_chat, outputs=[chatbot, history])
368
+ selected_model.change(clear_chat, outputs=[chatbot, history])
369
+ # share_button.click(None, [], [], _js=share_js)
370
+
371
+ demo.queue(concurrency_count=16).launch(debug=True)
dialogues.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ from dataclasses import asdict, dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Optional, Type, TypeVar, Union
21
+
22
+ from huggingface_hub import ModelHubMixin, hf_hub_download
23
+
24
+ # Generic variable that is either ModelHubMixin or a subclass thereof
25
+ T = TypeVar("T", bound="ModelHubMixin")
26
+
27
+ TEMPLATE_FILENAME = "dialogue_template.json"
28
+ IGNORE_INDEX = -100
29
+
30
+
31
+ @dataclass
32
+ class DialogueTemplate(ModelHubMixin):
33
+ """Converts all turns of a dialogue between a user and assistant to a standardized format.
34
+
35
+ Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py)
36
+ """
37
+
38
+ system: str
39
+ messages: List[Dict[str, str]] = None
40
+ system_token: str = "<|system|>"
41
+ user_token: str = "<|user|>"
42
+ assistant_token: str = "<|assistant|>"
43
+ end_token: str = "<|end|>"
44
+
45
+ def get_training_prompt(self) -> str:
46
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
47
+ if self.messages is None:
48
+ raise ValueError("Dialogue template must have at least one message.")
49
+ for message in self.messages:
50
+ if message["role"] == "user":
51
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
52
+ else:
53
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
54
+ return prompt
55
+
56
+ def get_inference_prompt(self) -> str:
57
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
58
+ if self.messages is None:
59
+ raise ValueError("Dialogue template must have at least one message.")
60
+ for message in self.messages:
61
+ if message["role"] == "user":
62
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
63
+ else:
64
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
65
+ prompt += self.assistant_token
66
+ return prompt
67
+
68
+ def get_dialogue(self):
69
+ """Helper function to format the messages as an easy-to-read dialogue."""
70
+ prompt = ""
71
+ if self.messages is None:
72
+ raise ValueError("Dialogue template must have at least one message.")
73
+ for message in self.messages:
74
+ if message["role"] == "user":
75
+ prompt += "\n\nHuman: " + message["content"]
76
+ else:
77
+ prompt += "\n\nAssistant: " + message["content"]
78
+ return prompt
79
+
80
+ def get_special_tokens(self) -> List[str]:
81
+ return [self.system_token, self.user_token, self.assistant_token, self.end_token]
82
+
83
+ def copy(self):
84
+ return DialogueTemplate(
85
+ system=self.system,
86
+ messages=self.messages,
87
+ system_token=self.system_token,
88
+ user_token=self.user_token,
89
+ assistant_token=self.assistant_token,
90
+ end_token=self.end_token,
91
+ )
92
+
93
+ def to_dict(self) -> Dict[str, Any]:
94
+ return {k: v for k, v in asdict(self).items()}
95
+
96
+ @classmethod
97
+ def from_dict(cls, data):
98
+ return DialogueTemplate(
99
+ system=data["system"] if "system" in data else "",
100
+ messages=data["messages"] if "messages" in data else None,
101
+ system_token=data["system_token"] if "system_token" in data else "<|system|>",
102
+ user_token=data["user_token"] if "user_token" in data else "<|user|>",
103
+ assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>",
104
+ end_token=data["end_token"] if "end_token" in data else "<|end|>",
105
+ )
106
+
107
+ def _save_pretrained(self, save_directory: Union[str, Path]) -> None:
108
+ save_directory = Path(save_directory)
109
+ save_directory.mkdir(exist_ok=True)
110
+ with open(save_directory / "dialogue_template.json", "w") as f:
111
+ json.dump(self.to_dict(), f, indent=2)
112
+
113
+ @classmethod
114
+ def _from_pretrained(
115
+ cls: Type[T],
116
+ *,
117
+ model_id: str,
118
+ revision: Optional[str],
119
+ cache_dir: Optional[Union[str, Path]],
120
+ force_download: bool,
121
+ proxies: Optional[Dict],
122
+ resume_download: bool,
123
+ local_files_only: bool,
124
+ token: Optional[Union[str, bool]],
125
+ **model_kwargs,
126
+ ) -> T:
127
+ """Loads the dialogue template from a local directory or the Huggingface Hub.
128
+
129
+ Args:
130
+ model_id (`str`):
131
+ ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
132
+ revision (`str`, *optional*):
133
+ Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
134
+ latest commit on `main` branch.
135
+ force_download (`bool`, *optional*, defaults to `False`):
136
+ Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
137
+ the existing cache.
138
+ resume_download (`bool`, *optional*, defaults to `False`):
139
+ Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
140
+ proxies (`Dict[str, str]`, *optional*):
141
+ A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
142
+ 'http://hostname': 'foo.bar:4012'}`).
143
+ token (`str` or `bool`, *optional*):
144
+ The token to use as HTTP bearer authorization for remote files. By default, it will use the token
145
+ cached when running `huggingface-cli login`.
146
+ cache_dir (`str`, `Path`, *optional*):
147
+ Path to the folder where cached files are stored.
148
+ local_files_only (`bool`, *optional*, defaults to `False`):
149
+ If `True`, avoid downloading the file and return the path to the local cached file if it exists.
150
+ model_kwargs:
151
+ Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
152
+ """
153
+ if os.path.isdir(model_id): # Can either be a local directory
154
+ print("Loading dialogue template from local directory")
155
+ template_file = os.path.join(model_id, TEMPLATE_FILENAME)
156
+ else: # Or a template on the Hub
157
+ template_file = hf_hub_download( # Download from the hub, passing same input args
158
+ repo_id=model_id,
159
+ filename=TEMPLATE_FILENAME,
160
+ revision=revision,
161
+ cache_dir=cache_dir,
162
+ force_download=force_download,
163
+ proxies=proxies,
164
+ resume_download=resume_download,
165
+ token=token,
166
+ local_files_only=local_files_only,
167
+ )
168
+
169
+ # Load template
170
+ with open(template_file, "r") as f:
171
+ data = json.load(f)
172
+ return cls.from_dict(data=data)
173
+
174
+
175
+ # A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt
176
+ default_template = DialogueTemplate(
177
+ system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.",
178
+ )
179
+
180
+ # OpenAI and OpenAssistant train on few to no system messages.
181
+ # TODO: consider defining this as the `default` template
182
+ no_system_template = DialogueTemplate(
183
+ system="",
184
+ )
185
+
186
+ alpaca_template = DialogueTemplate(
187
+ system="Below is an instruction that describes a task. Write a response that appropriately completes the request.",
188
+ user_token="### Instruction:",
189
+ assistant_token="### Response:",
190
+ )
191
+
192
+ SUPPORTED_DIALOGUE_TEMPLATES = {
193
+ "default": default_template,
194
+ "no_system": no_system_template,
195
+ "alpaca": alpaca_template,
196
+ }
197
+
198
+
199
+ def get_dialogue_template(template: str) -> DialogueTemplate:
200
+ if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys():
201
+ raise ValueError(f"Template {template} is not supported!")
202
+ return SUPPORTED_DIALOGUE_TEMPLATES[template].copy()
203
+
204
+
205
+ def prepare_dialogue(example, dialogue_template, is_train=True):
206
+ """Format example to single- or multi-turn dialogue."""
207
+ # TODO: make this simpler by just ensuring every dataset has a messages column
208
+ if "messages" in example.keys() and example["messages"] is not None:
209
+ dialogue_template.messages = example["messages"]
210
+ elif all(k in example.keys() for k in ("prompt", "completion")):
211
+ # Construct single-turn dialogue from prompt and completion
212
+ dialogue_template.messages = [
213
+ {"role": "user", "content": example["prompt"]},
214
+ {"role": "assistant", "content": example["completion"]},
215
+ ]
216
+ elif "prompt" in example.keys():
217
+ # Construct single-turn dialogue from prompt (inference only)
218
+ dialogue_template.messages = [
219
+ {"role": "user", "content": example["prompt"]},
220
+ ]
221
+ else:
222
+ raise ValueError(
223
+ f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}"
224
+ )
225
+ if is_train:
226
+ example["text"] = dialogue_template.get_training_prompt()
227
+ else:
228
+ example["text"] = dialogue_template.get_inference_prompt()
229
+ return example
230
+
231
+
232
+ def mask_user_labels(tokenizer, dialogue_template, labels):
233
+ """Masks the user turns of a dialogue from the loss"""
234
+ user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token)
235
+ assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token)
236
+ for idx, label_id in enumerate(labels):
237
+ if label_id == user_token_id:
238
+ current_idx = idx
239
+ while labels[current_idx] != assistant_token_id and current_idx < len(labels):
240
+ labels[current_idx] = IGNORE_INDEX
241
+ current_idx += 1
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ huggingface_hub
2
+ text-generation
share_btn.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ async function getInputImgFile(imgEl){
27
+ const res = await fetch(imgEl.src);
28
+ const blob = await res.blob();
29
+ const imgId = Date.now() % 200;
30
+ const isPng = imgEl.src.startsWith(`data:image/png`);
31
+ if(isPng){
32
+ const fileName = `sd-perception-${{imgId}}.png`;
33
+ return new File([blob], fileName, { type: 'image/png' });
34
+ }else{
35
+ const fileName = `sd-perception-${{imgId}}.jpg`;
36
+ return new File([blob], fileName, { type: 'image/jpeg' });
37
+ }
38
+ }
39
+
40
+ // const gradioEl = document.querySelector('body > gradio-app');
41
+ const gradioEl = document.querySelector("gradio-app");
42
+ const inputTxt = gradioEl.querySelector('#q-input textarea').value;
43
+ const outputTxt = gradioEl.querySelector('#q-output').outerHTML;
44
+
45
+ const titleLength = 150;
46
+ let titleTxt = inputTxt;
47
+ if(titleTxt.length > titleLength){
48
+ titleTxt = titleTxt.slice(0, titleLength) + ' ...';
49
+ }
50
+
51
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
52
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
53
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
54
+
55
+ if(!inputTxt || !outputTxt){
56
+ return;
57
+ };
58
+
59
+ shareBtnEl.style.pointerEvents = 'none';
60
+ shareIconEl.style.display = 'none';
61
+ loadingIconEl.style.removeProperty('display');
62
+
63
+ const descriptionMd = `### Question:
64
+ ${inputTxt}
65
+
66
+ ### Answer:
67
+
68
+ ${outputTxt}`;
69
+
70
+ const params = {
71
+ title: titleTxt,
72
+ description: descriptionMd,
73
+ };
74
+
75
+ const paramsStr = Object.entries(params)
76
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
77
+ .join('&');
78
+
79
+ window.open(`https://huggingface.co/spaces/HuggingFaceH4/star-chat-demo/discussions/new?${paramsStr}`, '_blank');
80
+
81
+ shareBtnEl.style.removeProperty('pointer-events');
82
+ shareIconEl.style.removeProperty('display');
83
+ loadingIconEl.style.display = 'none';
84
+ }"""
85
+
86
+ share_btn_css = """
87
+ a {text-decoration-line: underline; font-weight: 600;}
88
+ .animate-spin {
89
+ animation: spin 1s linear infinite;
90
+ }
91
+ @keyframes spin {
92
+ from { transform: rotate(0deg); }
93
+ to { transform: rotate(360deg); }
94
+ }
95
+ #share-btn-container {
96
+ display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
97
+ }
98
+ #share-btn {
99
+ all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
100
+ }
101
+ #share-btn * {
102
+ all: unset;
103
+ }
104
+ #share-btn-container div:nth-child(-n+2){
105
+ width: auto !important;
106
+ min-height: 0px !important;
107
+ }
108
+ #share-btn-container .wrap {
109
+ display: none !important;
110
+ }
111
+ """
thumbnail.png ADDED