pseudotensor commited on
Commit
dcd2001
1 Parent(s): 54f4f91

Update with h2oGPT hash e4482a4c59016517cd0d5513bc15b78b46f4598a

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
app.py CHANGED
@@ -1 +1 @@
1
- generate.py
 
1
+ gen.py
gen.py ADDED
The diff for this file is too large to render. See raw diff
 
gradio_utils/__pycache__/css.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
gradio_utils/__pycache__/grclient.cpython-310.pyc ADDED
Binary file (2.69 kB). View file
 
gradio_utils/__pycache__/prompt_form.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
gradio_utils/css.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def get_css(kwargs) -> str:
2
+ if kwargs['h2ocolors']:
3
+ css_code = """footer {visibility: hidden;}
4
+ body{background:linear-gradient(#f5f5f5,#e5e5e5);}
5
+ body.dark{background:linear-gradient(#000000,#0d0d0d);}
6
+ """
7
+ else:
8
+ css_code = """footer {visibility: hidden}"""
9
+
10
+ css_code += make_css_base()
11
+ return css_code
12
+
13
+
14
+ def make_css_base() -> str:
15
+ return """
16
+ @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap');
17
+
18
+ body.dark{#warning {background-color: #555555};}
19
+
20
+ #small_btn {
21
+ margin: 0.6em 0em 0.55em 0;
22
+ max-width: 20em;
23
+ min-width: 5em !important;
24
+ height: 5em;
25
+ font-size: 14px !important;
26
+ }
27
+
28
+ #prompt-form {
29
+ border: 1px solid var(--primary-500) !important;
30
+ }
31
+
32
+ #prompt-form.block {
33
+ border-radius: var(--block-radius) !important;
34
+ }
35
+
36
+ #prompt-form textarea {
37
+ border: 1px solid rgb(209, 213, 219);
38
+ }
39
+
40
+ #prompt-form label > div {
41
+ margin-top: 4px;
42
+ }
43
+
44
+ button.primary:hover {
45
+ background-color: var(--primary-600) !important;
46
+ transition: .2s;
47
+ }
48
+
49
+ #prompt-form-area {
50
+ margin-bottom: 2.5rem;
51
+ }
52
+ .chatsmall chatbot {font-size: 10px !important}
53
+ """
gradio_utils/grclient.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback
2
+ from typing import Callable
3
+ import os
4
+
5
+ from gradio_client.client import Job
6
+
7
+ os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
8
+
9
+ from gradio_client import Client
10
+
11
+
12
+ class GradioClient(Client):
13
+ """
14
+ Parent class of gradio client
15
+ To handle automatically refreshing client if detect gradio server changed
16
+ """
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ self.args = args
20
+ self.kwargs = kwargs
21
+ super().__init__(*args, **kwargs)
22
+ self.server_hash = self.get_server_hash()
23
+
24
+ def get_server_hash(self):
25
+ """
26
+ Get server hash using super without any refresh action triggered
27
+ Returns: git hash of gradio server
28
+ """
29
+ return super().submit(api_name='/system_hash').result()
30
+
31
+ def refresh_client_if_should(self):
32
+ # get current hash in order to update api_name -> fn_index map in case gradio server changed
33
+ # FIXME: Could add cli api as hash
34
+ server_hash = self.get_server_hash()
35
+ if self.server_hash != server_hash:
36
+ self.refresh_client()
37
+ self.server_hash = server_hash
38
+ else:
39
+ self.reset_session()
40
+
41
+ def refresh_client(self):
42
+ """
43
+ Ensure every client call is independent
44
+ Also ensure map between api_name and fn_index is updated in case server changed (e.g. restarted with new code)
45
+ Returns:
46
+ """
47
+ # need session hash to be new every time, to avoid "generator already executing"
48
+ self.reset_session()
49
+
50
+ client = Client(*self.args, **self.kwargs)
51
+ for k, v in client.__dict__.items():
52
+ setattr(self, k, v)
53
+
54
+ def submit(
55
+ self,
56
+ *args,
57
+ api_name: str | None = None,
58
+ fn_index: int | None = None,
59
+ result_callbacks: Callable | list[Callable] | None = None,
60
+ ) -> Job:
61
+ # Note predict calls submit
62
+ try:
63
+ self.refresh_client_if_should()
64
+ job = super().submit(*args, api_name=api_name, fn_index=fn_index)
65
+ except Exception as e:
66
+ print("Hit e=%s" % str(e), flush=True)
67
+ # force reconfig in case only that
68
+ self.refresh_client()
69
+ job = super().submit(*args, api_name=api_name, fn_index=fn_index)
70
+
71
+ # see if immediately failed
72
+ e = job.future._exception
73
+ if e is not None:
74
+ print("GR job failed: %s %s" % (str(e), ''.join(traceback.format_tb(e.__traceback__))), flush=True)
75
+ # force reconfig in case only that
76
+ self.refresh_client()
77
+ job = super().submit(*args, api_name=api_name, fn_index=fn_index)
78
+ e2 = job.future._exception
79
+ if e2 is not None:
80
+ print("GR job failed again: %s\n%s" % (str(e2), ''.join(traceback.format_tb(e2.__traceback__))), flush=True)
81
+
82
+ return job
gradio_utils/prompt_form.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+
4
+ import gradio as gr
5
+
6
+ from enums import LangChainMode
7
+
8
+
9
+ def make_chatbots(output_label0, output_label0_model2, **kwargs):
10
+ text_outputs = []
11
+ chat_kwargs = []
12
+ for model_state_lock in kwargs['model_states']:
13
+ if os.environ.get('DEBUG_MODEL_LOCK'):
14
+ model_name = model_state_lock["base_model"] + " : " + model_state_lock["inference_server"]
15
+ else:
16
+ model_name = model_state_lock["base_model"]
17
+ output_label = f'h2oGPT [{model_name}]'
18
+ min_width = 250 if kwargs['gradio_size'] in ['small', 'large', 'medium'] else 160
19
+ chat_kwargs.append(dict(label=output_label, visible=kwargs['model_lock'], elem_classes='chatsmall',
20
+ height=kwargs['height'] or 400, min_width=min_width))
21
+
22
+ if kwargs['model_lock_columns'] == -1:
23
+ kwargs['model_lock_columns'] = len(kwargs['model_states'])
24
+ if kwargs['model_lock_columns'] is None:
25
+ kwargs['model_lock_columns'] = 3
26
+
27
+ ncols = kwargs['model_lock_columns']
28
+ if kwargs['model_states'] == 0:
29
+ nrows = 0
30
+ else:
31
+ nrows = math.ceil(len(kwargs['model_states']) / kwargs['model_lock_columns'])
32
+
33
+ if kwargs['model_lock_columns'] == 0:
34
+ # not using model_lock
35
+ pass
36
+ elif nrows <= 1:
37
+ with gr.Row():
38
+ for chat_kwargs1, model_state_lock in zip(chat_kwargs, kwargs['model_states']):
39
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
40
+ elif nrows == kwargs['model_states']:
41
+ with gr.Row():
42
+ for chat_kwargs1, model_state_lock in zip(chat_kwargs, kwargs['model_states']):
43
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
44
+ elif nrows == 2:
45
+ with gr.Row():
46
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
47
+ if mii >= len(kwargs['model_states']) / 2:
48
+ continue
49
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
50
+ with gr.Row():
51
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
52
+ if mii < len(kwargs['model_states']) / 2:
53
+ continue
54
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
55
+ elif nrows == 3:
56
+ with gr.Row():
57
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
58
+ if mii >= 1 * len(kwargs['model_states']) / 3:
59
+ continue
60
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
61
+ with gr.Row():
62
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
63
+ if mii < 1 * len(kwargs['model_states']) / 3 or mii >= 2 * len(kwargs['model_states']) / 3:
64
+ continue
65
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
66
+ with gr.Row():
67
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
68
+ if mii < 2 * len(kwargs['model_states']) / 3:
69
+ continue
70
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
71
+ elif nrows >= 4:
72
+ with gr.Row():
73
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
74
+ if mii >= 1 * len(kwargs['model_states']) / 4:
75
+ continue
76
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
77
+ with gr.Row():
78
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
79
+ if mii < 1 * len(kwargs['model_states']) / 4 or mii >= 2 * len(kwargs['model_states']) / 4:
80
+ continue
81
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
82
+ with gr.Row():
83
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
84
+ if mii < 2 * len(kwargs['model_states']) / 4 or mii >= 3 * len(kwargs['model_states']) / 4:
85
+ continue
86
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
87
+ with gr.Row():
88
+ for mii, (chat_kwargs1, model_state_lock) in enumerate(zip(chat_kwargs, kwargs['model_states'])):
89
+ if mii < 3 * len(kwargs['model_states']) / 4:
90
+ continue
91
+ text_outputs.append(gr.Chatbot(**chat_kwargs1))
92
+
93
+ with gr.Row():
94
+ text_output = gr.Chatbot(label=output_label0, visible=not kwargs['model_lock'], height=kwargs['height'] or 400)
95
+ text_output2 = gr.Chatbot(label=output_label0_model2,
96
+ visible=False and not kwargs['model_lock'], height=kwargs['height'] or 400)
97
+ return text_output, text_output2, text_outputs
98
+
99
+
100
+ def make_prompt_form(kwargs):
101
+ if kwargs['langchain_mode'] != LangChainMode.DISABLED.value:
102
+ extra_prompt_form = ". For summarization, empty submission uses first top_k_docs documents."
103
+ else:
104
+ extra_prompt_form = ""
105
+ if kwargs['input_lines'] > 1:
106
+ instruction_label = "Shift-Enter to Submit, Enter for more lines%s" % extra_prompt_form
107
+ else:
108
+ instruction_label = "Enter to Submit, Shift-Enter for more lines%s" % extra_prompt_form
109
+
110
+ with gr.Row():#elem_id='prompt-form-area'):
111
+ with gr.Column(scale=50):
112
+ instruction = gr.Textbox(
113
+ lines=kwargs['input_lines'],
114
+ label='Ask anything',
115
+ placeholder=instruction_label,
116
+ info=None,
117
+ elem_id='prompt-form',
118
+ container=True,
119
+ )
120
+ with gr.Row():
121
+ submit = gr.Button(value='Submit', variant='primary', scale=0, size='sm')
122
+ stop_btn = gr.Button(value="Stop", variant='secondary', scale=0, size='sm')
123
+
124
+ return instruction, submit, stop_btn
h2o-logo.svg ADDED
iterators/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .timeout_iterator import TimeoutIterator, AsyncTimeoutIterator
2
+ from .iterator_pipe import IteratorPipe, AsyncIteratorPipe
3
+
4
+ __all__ = ["TimeoutIterator", "AsyncTimeoutIterator", "IteratorPipe", "AsyncIteratorPipe"]
iterators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (337 Bytes). View file
 
iterators/__pycache__/iterator_pipe.cpython-310.pyc ADDED
Binary file (2.71 kB). View file
 
iterators/__pycache__/timeout_iterator.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
iterators/iterator_pipe.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import queue
2
+ import asyncio
3
+
4
+
5
+ class IteratorPipe:
6
+ """
7
+ Iterator Pipe creates an iterator that can be fed in data from another block of code or thread of execution
8
+ """
9
+
10
+ def __init__(self, sentinel=object()):
11
+ self._q = queue.Queue()
12
+ self._sentinel = sentinel
13
+ self._sentinel_pushed = False
14
+ self._closed = False
15
+
16
+ def __iter__(self):
17
+ return self
18
+
19
+ def __next__(self):
20
+ if self._closed:
21
+ raise StopIteration
22
+
23
+ data = self._q.get(block=True)
24
+ if data is self._sentinel:
25
+ self._closed = True
26
+ raise StopIteration
27
+
28
+ return data
29
+
30
+ def put(self, data) -> bool:
31
+ """
32
+ Pushes next item to Iterator and returns True
33
+ If iterator has been closed via close(), doesn't push anything and returns False
34
+ """
35
+ if self._sentinel_pushed:
36
+ return False
37
+
38
+ self._q.put(data)
39
+ return True
40
+
41
+ def close(self):
42
+ """
43
+ Close is idempotent. Calling close multiple times is safe
44
+ Iterator will raise StopIteration only after all elements pushed before close have been iterated
45
+ """
46
+ # make close idempotent
47
+ if not self._sentinel_pushed:
48
+ self._sentinel_pushed = True
49
+ self._q.put(self._sentinel)
50
+
51
+
52
+ class AsyncIteratorPipe:
53
+
54
+ def __init__(self, sentinel=object()):
55
+ self._q = asyncio.Queue()
56
+ self._sentinel = sentinel
57
+ self._sentinel_pushed = False
58
+ self._closed = False
59
+
60
+ def __aiter__(self):
61
+ return self
62
+
63
+ async def __anext__(self):
64
+ if self._closed:
65
+ raise StopAsyncIteration
66
+
67
+ data = await self._q.get()
68
+ if data is self._sentinel:
69
+ self._closed = True
70
+ raise StopAsyncIteration
71
+
72
+ return data
73
+
74
+ async def put(self, data) -> bool:
75
+ """
76
+ Pushes next item to Iterator and returns True
77
+ If iterator has been closed via close(), doesn't push anything and returns False
78
+ """
79
+ if self._sentinel_pushed:
80
+ return False
81
+
82
+ await self._q.put(data)
83
+ return True
84
+
85
+ async def close(self):
86
+ """
87
+ Close is idempotent. Calling close multiple times is safe
88
+ Iterator will raise StopIteration only after all elements pushed before close have been iterated
89
+ """
90
+ # make close idempotent
91
+ if not self._sentinel_pushed:
92
+ self._sentinel_pushed = True
93
+ await self._q.put(self._sentinel)
iterators/timeout_iterator.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import queue
2
+ import asyncio
3
+ import threading
4
+ import traceback
5
+
6
+
7
+ class TimeoutIterator:
8
+ """
9
+ Wrapper class to add timeout feature to synchronous iterators
10
+ - timeout: timeout for next(). Default=ZERO_TIMEOUT i.e. no timeout or blocking calls to next. Updated using set_timeout()
11
+ - sentinel: the object returned by iterator when timeout happens
12
+ - reset_on_next: if set to True, timeout is reset to the value of ZERO_TIMEOUT on each iteration
13
+
14
+ TimeoutIterator uses a thread internally.
15
+ The thread stops once the iterator exhausts or raises an exception during iteration.
16
+
17
+ Any exceptions raised within the wrapped iterator are propagated as it is.
18
+ Exception is raised when all elements generated by the actual iterator before exception have been consumed
19
+ Timeout can be set dynamically before going for iteration
20
+ """
21
+ ZERO_TIMEOUT = 0.0
22
+
23
+ def __init__(self, iterator, timeout=0.0, sentinel=object(), reset_on_next=False, raise_on_exception=True):
24
+ self._iterator = iterator
25
+ self._timeout = timeout
26
+ self._sentinel = sentinel
27
+ self._reset_on_next = reset_on_next
28
+ self._raise_on_exception = raise_on_exception
29
+
30
+ self._interrupt = False
31
+ self._done = False
32
+ self._buffer = queue.Queue()
33
+ self._thread = threading.Thread(target=self.__lookahead)
34
+ self._thread.start()
35
+
36
+ def get_sentinel(self):
37
+ return self._sentinel
38
+
39
+ def set_reset_on_next(self, reset_on_next):
40
+ self._reset_on_next = reset_on_next
41
+
42
+ def set_timeout(self, timeout: float):
43
+ """
44
+ Set timeout for next iteration
45
+ """
46
+ self._timeout = timeout
47
+
48
+ def interrupt(self):
49
+ """
50
+ interrupt and stop the underlying thread.
51
+ the thread acutally dies only after interrupt has been set and
52
+ the underlying iterator yields a value after that.
53
+ """
54
+ self._interrupt = True
55
+
56
+ def __iter__(self):
57
+ return self
58
+
59
+ def __next__(self):
60
+ """
61
+ yield the result from iterator
62
+ if timeout > 0:
63
+ yield data if available.
64
+ otherwise yield sentinal
65
+ """
66
+ if self._done:
67
+ raise StopIteration
68
+
69
+ data = self._sentinel
70
+ try:
71
+ if self._timeout > self.ZERO_TIMEOUT:
72
+ data = self._buffer.get(timeout=self._timeout)
73
+ else:
74
+ data = self._buffer.get()
75
+ except queue.Empty:
76
+ pass
77
+ finally:
78
+ # see if timeout needs to be reset
79
+ if self._reset_on_next:
80
+ self._timeout = self.ZERO_TIMEOUT
81
+
82
+ # propagate any exceptions including StopIteration
83
+ if isinstance(data, BaseException):
84
+ self._done = True
85
+ if isinstance(data, StopIteration):
86
+ raise data
87
+ ex = ''.join(traceback.format_tb(data.__traceback__))
88
+ print("Generation Failed: %s %s" % (str(data), str(ex)), flush=True)
89
+ if self._raise_on_exception:
90
+ raise data
91
+ else:
92
+ return data
93
+
94
+ return data
95
+
96
+ def __lookahead(self):
97
+ try:
98
+ while True:
99
+ self._buffer.put(next(self._iterator))
100
+ if self._interrupt:
101
+ raise StopIteration()
102
+ except BaseException as e:
103
+ self._buffer.put(e)
104
+
105
+
106
+ class AsyncTimeoutIterator:
107
+ """
108
+ Async version of TimeoutIterator. See method documentation of TimeoutIterator
109
+ """
110
+ ZERO_TIMEOUT = 0.0
111
+
112
+ def __init__(self, iterator, timeout=0.0, sentinel=object(), reset_on_next=False):
113
+ self._iterator = iterator
114
+ self._timeout = timeout
115
+ self._sentinel = sentinel
116
+ self._reset_on_next = reset_on_next
117
+
118
+ self._interrupt = False
119
+ self._done = False
120
+ self._buffer = asyncio.Queue()
121
+ self._task = asyncio.get_event_loop().create_task(self.__lookahead())
122
+
123
+ def get_sentinel(self):
124
+ return self._sentinel
125
+
126
+ def set_reset_on_next(self, reset_on_next):
127
+ self._reset_on_next = reset_on_next
128
+
129
+ def set_timeout(self, timeout: float):
130
+ self._timeout = timeout
131
+
132
+ def interrupt(self):
133
+ self._interrupt = True
134
+
135
+ def __aiter__(self):
136
+ return self
137
+
138
+ async def __anext__(self):
139
+ if self._done:
140
+ raise StopAsyncIteration
141
+
142
+ data = self._sentinel
143
+ try:
144
+ if self._timeout > self.ZERO_TIMEOUT:
145
+ data = await asyncio.wait_for(self._buffer.get(), self._timeout)
146
+ else:
147
+ data = await self._buffer.get()
148
+ except asyncio.TimeoutError:
149
+ pass
150
+ finally:
151
+ # see if timeout needs to be reset
152
+ if self._reset_on_next:
153
+ self._timeout = self.ZERO_TIMEOUT
154
+
155
+ # propagate any exceptions including StopIteration
156
+ if isinstance(data, BaseException):
157
+ self._done = True
158
+ raise data
159
+
160
+ return data
161
+
162
+ async def __lookahead(self):
163
+ try:
164
+ while True:
165
+ data = await self._iterator.__anext__()
166
+ await self._buffer.put(data)
167
+ if self._interrupt:
168
+ raise StopAsyncIteration()
169
+ except BaseException as e:
170
+ await self._buffer.put(e)
requirements.txt CHANGED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # for generate (gradio server) and finetune
2
+ datasets==2.13.0
3
+ sentencepiece==0.1.99
4
+ gradio==3.35.2
5
+ huggingface_hub==0.15.1
6
+ appdirs==1.4.4
7
+ fire==0.5.0
8
+ docutils==0.20.1
9
+ torch==2.0.1
10
+ evaluate==0.4.0
11
+ rouge_score==0.1.2
12
+ sacrebleu==2.3.1
13
+ scikit-learn==1.2.2
14
+ alt-profanity-check==1.2.2
15
+ better-profanity==0.7.0
16
+ numpy==1.24.3
17
+ pandas==2.0.2
18
+ matplotlib==3.7.1
19
+ loralib==0.1.1
20
+ bitsandbytes==0.39.0
21
+ accelerate==0.20.3
22
+ git+https://github.com/huggingface/peft.git@0b62b4378b4ce9367932c73540349da9a41bdea8
23
+ transformers==4.30.2
24
+ tokenizers==0.13.3
25
+ APScheduler==3.10.1
26
+
27
+ # optional for generate
28
+ pynvml==11.5.0
29
+ psutil==5.9.5
30
+ boto3==1.26.101
31
+ botocore==1.29.101
32
+
33
+ # optional for finetune
34
+ tensorboard==2.13.0
35
+ neptune==1.2.0
36
+
37
+ # for gradio client
38
+ gradio_client==0.2.7
39
+ beautifulsoup4==4.12.2
40
+ markdown==3.4.3
41
+
42
+ # data and testing
43
+ pytest==7.2.2
44
+ pytest-xdist==3.2.1
45
+ nltk==3.8.1
46
+ textstat==0.7.3
47
+ # pandoc==2.3
48
+ #pypandoc==1.11
49
+ pypandoc_binary==1.11
50
+ openpyxl==3.1.2
51
+ lm_dataformat==0.0.20
52
+ bioc==2.0
53
+
54
+ # falcon
55
+ einops==0.6.1
56
+ instructorembedding==1.0.1
57
+
58
+ # for gpt4all .env file, but avoid worrying about imports
59
+ python-dotenv==1.0.0
60
+
61
+ text-generation==0.6.0
62
+ # for tokenization when don't have HF tokenizer
63
+ tiktoken==0.4.0
64
+ # optional: for OpenAI endpoint or embeddings (requires key)
65
+ openai==0.27.8
66
+ # optional for chat with PDF
67
+ langchain==0.0.202
68
+ pypdf==3.9.1
69
+ # avoid textract, requires old six
70
+ #textract==1.6.5
71
+
72
+ # for HF embeddings
73
+ sentence_transformers==2.2.2
74
+
75
+ # local vector db
76
+ chromadb==0.3.25
77
+ # server vector db
78
+ #pymilvus==2.2.8
79
+
80
+ # weak url support, if can't install opencv etc. If comment-in this one, then comment-out unstructured[local-inference]==0.6.6
81
+ # unstructured==0.6.6
82
+
83
+ # strong support for images
84
+ # Requires on Ubuntu: sudo apt-get install libmagic-dev poppler-utils tesseract-ocr libreoffice
85
+ unstructured[local-inference]==0.7.4
86
+ #pdf2image==1.16.3
87
+ #pytesseract==0.3.10
88
+ pillow
89
+
90
+ pdfminer.six==20221105
91
+ urllib3
92
+ requests_file
93
+
94
+ #pdf2image==1.16.3
95
+ #pytesseract==0.3.10
96
+ tabulate==0.9.0
97
+ # FYI pandoc already part of requirements.txt
98
+
99
+ # JSONLoader, but makes some trouble for some users
100
+ # jq==1.4.1
101
+
102
+ # to check licenses
103
+ # Run: pip-licenses|grep -v 'BSD\|Apache\|MIT'
104
+ pip-licenses==4.3.0
105
+
106
+ # weaviate vector db
107
+ weaviate-client==3.20.0
108
+ # optional for chat with PDF
109
+ langchain==0.0.202
110
+ pypdf==3.9.1
111
+ # avoid textract, requires old six
112
+ #textract==1.6.5
113
+
114
+ # for HF embeddings
115
+ sentence_transformers==2.2.2
116
+
117
+ # local vector db
118
+ chromadb==0.3.25
119
+ # server vector db
120
+ #pymilvus==2.2.8
121
+
122
+ # weak url support, if can't install opencv etc. If comment-in this one, then comment-out unstructured[local-inference]==0.6.6
123
+ # unstructured==0.6.6
124
+
125
+ # strong support for images
126
+ # Requires on Ubuntu: sudo apt-get install libmagic-dev poppler-utils tesseract-ocr libreoffice
127
+ unstructured[local-inference]==0.7.4
128
+ #pdf2image==1.16.3
129
+ #pytesseract==0.3.10
130
+ pillow
131
+
132
+ pdfminer.six==20221105
133
+ urllib3
134
+ requests_file
135
+
136
+ #pdf2image==1.16.3
137
+ #pytesseract==0.3.10
138
+ tabulate==0.9.0
139
+ # FYI pandoc already part of requirements.txt
140
+
141
+ # JSONLoader, but makes some trouble for some users
142
+ # jq==1.4.1
143
+
144
+ # to check licenses
145
+ # Run: pip-licenses|grep -v 'BSD\|Apache\|MIT'
146
+ pip-licenses==4.3.0
147
+
148
+ # weaviate vector db
149
+ weaviate-client==3.20.0
150
+ faiss-gpu==1.7.2
151
+ arxiv==1.4.7
152
+ pymupdf==1.22.3 # AGPL license
153
+ # extract-msg==0.41.1 # GPL3