soulwax commited on
Commit
ebe33dd
1 Parent(s): d89d289

Initial Commit

Browse files
README.md CHANGED
@@ -1,12 +1,12 @@
1
  ---
2
- title: Bluesix Kings
3
- emoji: 🦀
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 3.24.1
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: bluesix-kings
3
+ emoji: 6️⃣
4
+ colorFrom: purple
5
+ colorTo: red
6
  sdk: gradio
 
7
  app_file: app.py
8
  pinned: false
9
+ license: cc-by-nc-4.0
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding:utf-8 -*-
2
+ import os
3
+ import logging
4
+ import sys
5
+ import gradio as gr
6
+ import torch
7
+ import gc
8
+ from app_modules.utils import *
9
+ from app_modules.presets import *
10
+ from app_modules.overwrites import *
11
+
12
+ logging.basicConfig(
13
+ level=logging.DEBUG,
14
+ format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
15
+ )
16
+
17
+ base_model = "decapoda-research/llama-7b-hf"
18
+ adapter_model = "project-baize/baize-lora-7B"
19
+ tokenizer,model,device = load_tokenizer_and_model(base_model,adapter_model)
20
+
21
+ total_count = 0
22
+ def predict(text,
23
+ chatbot,
24
+ history,
25
+ top_p,
26
+ temperature,
27
+ max_length_tokens,
28
+ max_context_length_tokens,):
29
+ if text=="":
30
+ yield chatbot,history,"Empty context."
31
+ return
32
+ try:
33
+ model
34
+ except:
35
+ yield [[text,"No Model Found"]],[],"No Model Found"
36
+ return
37
+
38
+ inputs = generate_prompt_with_history(text,history,tokenizer,max_length=max_context_length_tokens)
39
+ if inputs is None:
40
+ yield chatbot,history,"Input too long."
41
+ return
42
+ else:
43
+ prompt,inputs=inputs
44
+ begin_length = len(prompt)
45
+ input_ids = inputs["input_ids"][:,-max_context_length_tokens:].to(device)
46
+ torch.cuda.empty_cache()
47
+ global total_count
48
+ total_count += 1
49
+ print(total_count)
50
+ if total_count % 50 == 0 :
51
+ os.system("nvidia-smi")
52
+ with torch.no_grad():
53
+ for x in greedy_search(input_ids,model,tokenizer,stop_words=["[|Human|]", "[|AI|]"],max_length=max_length_tokens,temperature=temperature,top_p=top_p):
54
+ if is_stop_word_or_prefix(x,["[|Human|]", "[|AI|]"]) is False:
55
+ if "[|Human|]" in x:
56
+ x = x[:x.index("[|Human|]")].strip()
57
+ if "[|AI|]" in x:
58
+ x = x[:x.index("[|AI|]")].strip()
59
+ x = x.strip()
60
+ a, b= [[y[0],convert_to_markdown(y[1])] for y in history]+[[text, convert_to_markdown(x)]],history + [[text,x]]
61
+ yield a, b, "Generating..."
62
+ if shared_state.interrupted:
63
+ shared_state.recover()
64
+ try:
65
+ yield a, b, "Stop: Success"
66
+ return
67
+ except:
68
+ pass
69
+ del input_ids
70
+ gc.collect()
71
+ torch.cuda.empty_cache()
72
+ #print(text)
73
+ #print(x)
74
+ #print("="*80)
75
+ try:
76
+ yield a,b,"Generate: Success"
77
+ except:
78
+ pass
79
+
80
+ def retry(
81
+ text,
82
+ chatbot,
83
+ history,
84
+ top_p,
85
+ temperature,
86
+ max_length_tokens,
87
+ max_context_length_tokens,
88
+ ):
89
+ logging.info("Retry...")
90
+ if len(history) == 0:
91
+ yield chatbot, history, f"Empty context"
92
+ return
93
+ chatbot.pop()
94
+ inputs = history.pop()[0]
95
+ for x in predict(inputs,chatbot,history,top_p,temperature,max_length_tokens,max_context_length_tokens):
96
+ yield x
97
+
98
+
99
+ gr.Chatbot.postprocess = postprocess
100
+
101
+ with open("assets/custom.css", "r", encoding="utf-8") as f:
102
+ customCSS = f.read()
103
+
104
+ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
105
+ history = gr.State([])
106
+ user_question = gr.State("")
107
+ with gr.Row():
108
+ gr.HTML(title)
109
+ status_display = gr.Markdown("Success", elem_id="status_display")
110
+ gr.Markdown(description_top)
111
+ with gr.Row(scale=1).style(equal_height=True):
112
+ with gr.Column(scale=5):
113
+ with gr.Row(scale=1):
114
+ chatbot = gr.Chatbot(elem_id="chuanhu_chatbot").style(height="100%")
115
+ with gr.Row(scale=1):
116
+ with gr.Column(scale=12):
117
+ user_input = gr.Textbox(
118
+ show_label=False, placeholder="Enter text"
119
+ ).style(container=False)
120
+ with gr.Column(min_width=70, scale=1):
121
+ submitBtn = gr.Button("Send")
122
+ with gr.Column(min_width=70, scale=1):
123
+ cancelBtn = gr.Button("Stop")
124
+ with gr.Row(scale=1):
125
+ emptyBtn = gr.Button(
126
+ "🧹 New Conversation",
127
+ )
128
+ retryBtn = gr.Button("🔄 Regenerate")
129
+ delLastBtn = gr.Button("🗑️ Remove Last Turn")
130
+ with gr.Column():
131
+ with gr.Column(min_width=50, scale=1):
132
+ with gr.Tab(label="Parameter Setting"):
133
+ gr.Markdown("# Parameters")
134
+ top_p = gr.Slider(
135
+ minimum=-0,
136
+ maximum=1.0,
137
+ value=0.95,
138
+ step=0.05,
139
+ interactive=True,
140
+ label="Top-p",
141
+ )
142
+ temperature = gr.Slider(
143
+ minimum=0.1,
144
+ maximum=2.0,
145
+ value=1,
146
+ step=0.1,
147
+ interactive=True,
148
+ label="Temperature",
149
+ )
150
+ max_length_tokens = gr.Slider(
151
+ minimum=0,
152
+ maximum=512,
153
+ value=256,
154
+ step=8,
155
+ interactive=True,
156
+ label="Max Generation Tokens",
157
+ )
158
+ max_context_length_tokens = gr.Slider(
159
+ minimum=0,
160
+ maximum=4096,
161
+ value=2048,
162
+ step=128,
163
+ interactive=True,
164
+ label="Max History Tokens",
165
+ )
166
+ gr.Markdown(description)
167
+
168
+ predict_args = dict(
169
+ fn=predict,
170
+ inputs=[
171
+ user_question,
172
+ chatbot,
173
+ history,
174
+ top_p,
175
+ temperature,
176
+ max_length_tokens,
177
+ max_context_length_tokens,
178
+ ],
179
+ outputs=[chatbot, history, status_display],
180
+ show_progress=True,
181
+ )
182
+ retry_args = dict(
183
+ fn=retry,
184
+ inputs=[
185
+ user_input,
186
+ chatbot,
187
+ history,
188
+ top_p,
189
+ temperature,
190
+ max_length_tokens,
191
+ max_context_length_tokens,
192
+ ],
193
+ outputs=[chatbot, history, status_display],
194
+ show_progress=True,
195
+ )
196
+
197
+ reset_args = dict(
198
+ fn=reset_textbox, inputs=[], outputs=[user_input, status_display]
199
+ )
200
+
201
+ # Chatbot
202
+ transfer_input_args = dict(
203
+ fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn], show_progress=True
204
+ )
205
+
206
+ predict_event1 = user_input.submit(**transfer_input_args).then(**predict_args)
207
+
208
+ predict_event2 = submitBtn.click(**transfer_input_args).then(**predict_args)
209
+
210
+ emptyBtn.click(
211
+ reset_state,
212
+ outputs=[chatbot, history, status_display],
213
+ show_progress=True,
214
+ )
215
+ emptyBtn.click(**reset_args)
216
+
217
+ predict_event3 = retryBtn.click(**retry_args)
218
+
219
+ delLastBtn.click(
220
+ delete_last_conversation,
221
+ [chatbot, history],
222
+ [chatbot, history, status_display],
223
+ show_progress=True,
224
+ )
225
+ cancelBtn.click(
226
+ cancel_outputing, [], [status_display],
227
+ cancels=[
228
+ predict_event1,predict_event2,predict_event3
229
+ ]
230
+ )
231
+ demo.title = "Baize"
232
+
233
+ demo.queue(concurrency_count=1).launch()
app_modules/__pycache__/chat_func.cpython-38.pyc ADDED
Binary file (605 Bytes). View file
 
app_modules/__pycache__/llama_func.cpython-38.pyc ADDED
Binary file (4.62 kB). View file
 
app_modules/__pycache__/openai_func.cpython-38.pyc ADDED
Binary file (1.8 kB). View file
 
app_modules/__pycache__/overwrites.cpython-38.pyc ADDED
Binary file (2.6 kB). View file
 
app_modules/__pycache__/presets.cpython-38.pyc ADDED
Binary file (2.26 kB). View file
 
app_modules/__pycache__/shared.cpython-38.pyc ADDED
Binary file (1.08 kB). View file
 
app_modules/__pycache__/utils.cpython-38.pyc ADDED
Binary file (9.99 kB). View file
 
app_modules/overwrites.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import logging
3
+
4
+ from llama_index import Prompt
5
+ from typing import List, Tuple
6
+ import mdtex2html
7
+
8
+ from app_modules.presets import *
9
+ from app_modules.utils import *
10
+
11
+ def compact_text_chunks(self, prompt: Prompt, text_chunks: List[str]) -> List[str]:
12
+ logging.debug("Compacting text chunks...🚀🚀🚀")
13
+ combined_str = [c.strip() for c in text_chunks if c.strip()]
14
+ combined_str = [f"[{index+1}] {c}" for index, c in enumerate(combined_str)]
15
+ combined_str = "\n\n".join(combined_str)
16
+ # resplit based on self.max_chunk_overlap
17
+ text_splitter = self.get_text_splitter_given_prompt(prompt, 1, padding=1)
18
+ return text_splitter.split_text(combined_str)
19
+
20
+
21
+ def postprocess(
22
+ self, y: List[Tuple[str | None, str | None]]
23
+ ) -> List[Tuple[str | None, str | None]]:
24
+ """
25
+ Parameters:
26
+ y: List of tuples representing the message and response pairs. Each message and response should be a string, which may be in Markdown format.
27
+ Returns:
28
+ List of tuples representing the message and response. Each message and response will be a string of HTML.
29
+ """
30
+ if y is None or y == []:
31
+ return []
32
+ temp = []
33
+ for x in y:
34
+ user, bot = x
35
+ if not detect_converted_mark(user):
36
+ user = convert_asis(user)
37
+ if not detect_converted_mark(bot):
38
+ bot = convert_mdtext(bot)
39
+ temp.append((user, bot))
40
+ return temp
41
+
42
+ with open("./assets/custom.js", "r", encoding="utf-8") as f, open("./assets/Kelpy-Codos.js", "r", encoding="utf-8") as f2:
43
+ customJS = f.read()
44
+ kelpyCodos = f2.read()
45
+
46
+ def reload_javascript():
47
+ print("Reloading javascript...")
48
+ js = f'<script>{customJS}</script><script>{kelpyCodos}</script>'
49
+ def template_response(*args, **kwargs):
50
+ res = GradioTemplateResponseOriginal(*args, **kwargs)
51
+ res.body = res.body.replace(b'</html>', f'{js}</html>'.encode("utf8"))
52
+ res.init_headers()
53
+ return res
54
+
55
+ gr.routes.templates.TemplateResponse = template_response
56
+
57
+ GradioTemplateResponseOriginal = gr.routes.templates.TemplateResponse
app_modules/presets.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding:utf-8 -*-
2
+ import gradio as gr
3
+
4
+
5
+ title = """<h1 align="left" style="min-width:200px; margin-top:0;"> <img src="https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f432.svg" width="32px" style="display: inline"> Baize-7B </h1>"""
6
+ description_top = """\
7
+ <div align="left">
8
+ <p>
9
+ Disclaimer: The LLaMA model is a third-party version available on Hugging Face model hub. This demo should be used for research purposes only. Commercial use is strictly prohibited. The model output is not censored and the authors do not endorse the opinions in the generated content. Use at your own risk.
10
+ </p >
11
+ </div>
12
+ """
13
+ description = """\
14
+ <div align="center" style="margin:16px 0">
15
+ The demo is built on <a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT">ChuanhuChatGPT</a>.
16
+ </div>
17
+ """
18
+ CONCURRENT_COUNT = 100
19
+
20
+
21
+ ALREADY_CONVERTED_MARK = "<!-- ALREADY CONVERTED BY PARSER. -->"
22
+
23
+ small_and_beautiful_theme = gr.themes.Soft(
24
+ primary_hue=gr.themes.Color(
25
+ c50="#02C160",
26
+ c100="rgba(2, 193, 96, 0.2)",
27
+ c200="#02C160",
28
+ c300="rgba(2, 193, 96, 0.32)",
29
+ c400="rgba(2, 193, 96, 0.32)",
30
+ c500="rgba(2, 193, 96, 1.0)",
31
+ c600="rgba(2, 193, 96, 1.0)",
32
+ c700="rgba(2, 193, 96, 0.32)",
33
+ c800="rgba(2, 193, 96, 0.32)",
34
+ c900="#02C160",
35
+ c950="#02C160",
36
+ ),
37
+ secondary_hue=gr.themes.Color(
38
+ c50="#576b95",
39
+ c100="#576b95",
40
+ c200="#576b95",
41
+ c300="#576b95",
42
+ c400="#576b95",
43
+ c500="#576b95",
44
+ c600="#576b95",
45
+ c700="#576b95",
46
+ c800="#576b95",
47
+ c900="#576b95",
48
+ c950="#576b95",
49
+ ),
50
+ neutral_hue=gr.themes.Color(
51
+ name="gray",
52
+ c50="#f9fafb",
53
+ c100="#f3f4f6",
54
+ c200="#e5e7eb",
55
+ c300="#d1d5db",
56
+ c400="#B2B2B2",
57
+ c500="#808080",
58
+ c600="#636363",
59
+ c700="#515151",
60
+ c800="#393939",
61
+ c900="#272727",
62
+ c950="#171717",
63
+ ),
64
+ radius_size=gr.themes.sizes.radius_sm,
65
+ ).set(
66
+ button_primary_background_fill="#06AE56",
67
+ button_primary_background_fill_dark="#06AE56",
68
+ button_primary_background_fill_hover="#07C863",
69
+ button_primary_border_color="#06AE56",
70
+ button_primary_border_color_dark="#06AE56",
71
+ button_primary_text_color="#FFFFFF",
72
+ button_primary_text_color_dark="#FFFFFF",
73
+ button_secondary_background_fill="#F2F2F2",
74
+ button_secondary_background_fill_dark="#2B2B2B",
75
+ button_secondary_text_color="#393939",
76
+ button_secondary_text_color_dark="#FFFFFF",
77
+ # background_fill_primary="#F7F7F7",
78
+ # background_fill_primary_dark="#1F1F1F",
79
+ block_title_text_color="*primary_500",
80
+ block_title_background_fill="*primary_100",
81
+ input_background_fill="#F6F6F6",
82
+ )
app_modules/utils.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding:utf-8 -*-
2
+ from __future__ import annotations
3
+ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type
4
+ import logging
5
+ import json
6
+ import os
7
+ import datetime
8
+ import hashlib
9
+ import csv
10
+ import requests
11
+ import re
12
+ import html
13
+ import markdown2
14
+ import torch
15
+ import sys
16
+ import gc
17
+ from pygments.lexers import guess_lexer, ClassNotFound
18
+
19
+ import gradio as gr
20
+ from pypinyin import lazy_pinyin
21
+ import tiktoken
22
+ import mdtex2html
23
+ from markdown import markdown
24
+ from pygments import highlight
25
+ from pygments.lexers import guess_lexer,get_lexer_by_name
26
+ from pygments.formatters import HtmlFormatter
27
+ import transformers
28
+ from peft import PeftModel
29
+ from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
30
+
31
+ from app_modules.presets import *
32
+
33
+ logging.basicConfig(
34
+ level=logging.INFO,
35
+ format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
36
+ )
37
+
38
+
39
+ def markdown_to_html_with_syntax_highlight(md_str):
40
+ def replacer(match):
41
+ lang = match.group(1) or "text"
42
+ code = match.group(2)
43
+ lang = lang.strip()
44
+ #print(1,lang)
45
+ if lang=="text":
46
+ lexer = guess_lexer(code)
47
+ lang = lexer.name
48
+ #print(2,lang)
49
+ try:
50
+ lexer = get_lexer_by_name(lang, stripall=True)
51
+ except ValueError:
52
+ lexer = get_lexer_by_name("python", stripall=True)
53
+ formatter = HtmlFormatter()
54
+ #print(3,lexer.name)
55
+ highlighted_code = highlight(code, lexer, formatter)
56
+
57
+ return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'
58
+
59
+ code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
60
+ md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)
61
+
62
+ html_str = markdown(md_str)
63
+ return html_str
64
+
65
+
66
+ def normalize_markdown(md_text: str) -> str:
67
+ lines = md_text.split("\n")
68
+ normalized_lines = []
69
+ inside_list = False
70
+
71
+ for i, line in enumerate(lines):
72
+ if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
73
+ if not inside_list and i > 0 and lines[i - 1].strip() != "":
74
+ normalized_lines.append("")
75
+ inside_list = True
76
+ normalized_lines.append(line)
77
+ elif inside_list and line.strip() == "":
78
+ if i < len(lines) - 1 and not re.match(
79
+ r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
80
+ ):
81
+ normalized_lines.append(line)
82
+ continue
83
+ else:
84
+ inside_list = False
85
+ normalized_lines.append(line)
86
+
87
+ return "\n".join(normalized_lines)
88
+
89
+
90
+ def convert_mdtext(md_text):
91
+ code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
92
+ inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
93
+ code_blocks = code_block_pattern.findall(md_text)
94
+ non_code_parts = code_block_pattern.split(md_text)[::2]
95
+
96
+ result = []
97
+ for non_code, code in zip(non_code_parts, code_blocks + [""]):
98
+ if non_code.strip():
99
+ non_code = normalize_markdown(non_code)
100
+ if inline_code_pattern.search(non_code):
101
+ result.append(markdown(non_code, extensions=["tables"]))
102
+ else:
103
+ result.append(mdtex2html.convert(non_code, extensions=["tables"]))
104
+ if code.strip():
105
+ # _, code = detect_language(code) # 暂时去除代码高亮功能,因为在大段代码的情况下会出现问题
106
+ # code = code.replace("\n\n", "\n") # 暂时去除代码中的空行,因为在大段代码的情况下会出现问题
107
+ code = f"\n```{code}\n\n```"
108
+ code = markdown_to_html_with_syntax_highlight(code)
109
+ result.append(code)
110
+ result = "".join(result)
111
+ result += ALREADY_CONVERTED_MARK
112
+ return result
113
+
114
+ def convert_asis(userinput):
115
+ return f"<p style=\"white-space:pre-wrap;\">{html.escape(userinput)}</p>"+ALREADY_CONVERTED_MARK
116
+
117
+ def detect_converted_mark(userinput):
118
+ if userinput.endswith(ALREADY_CONVERTED_MARK):
119
+ return True
120
+ else:
121
+ return False
122
+
123
+
124
+
125
+ def detect_language(code):
126
+ if code.startswith("\n"):
127
+ first_line = ""
128
+ else:
129
+ first_line = code.strip().split("\n", 1)[0]
130
+ language = first_line.lower() if first_line else ""
131
+ code_without_language = code[len(first_line) :].lstrip() if first_line else code
132
+ return language, code_without_language
133
+
134
+ def convert_to_markdown(text):
135
+ text = text.replace("$","&#36;")
136
+ def replace_leading_tabs_and_spaces(line):
137
+ new_line = []
138
+
139
+ for char in line:
140
+ if char == "\t":
141
+ new_line.append("&#9;")
142
+ elif char == " ":
143
+ new_line.append("&nbsp;")
144
+ else:
145
+ break
146
+ return "".join(new_line) + line[len(new_line):]
147
+
148
+ markdown_text = ""
149
+ lines = text.split("\n")
150
+ in_code_block = False
151
+
152
+ for line in lines:
153
+ if in_code_block is False and line.startswith("```"):
154
+ in_code_block = True
155
+ markdown_text += "```\n"
156
+ elif in_code_block is True and line.startswith("```"):
157
+ in_code_block = False
158
+ markdown_text += "```\n"
159
+ elif in_code_block:
160
+ markdown_text += f"{line}\n"
161
+ else:
162
+ line = replace_leading_tabs_and_spaces(line)
163
+ line = re.sub(r"^(#)", r"\\\1", line)
164
+ markdown_text += f"{line} \n"
165
+
166
+ return markdown_text
167
+
168
+ def add_language_tag(text):
169
+ def detect_language(code_block):
170
+ try:
171
+ lexer = guess_lexer(code_block)
172
+ return lexer.name.lower()
173
+ except ClassNotFound:
174
+ return ""
175
+
176
+ code_block_pattern = re.compile(r"(```)(\w*\n[^`]+```)", re.MULTILINE)
177
+
178
+ def replacement(match):
179
+ code_block = match.group(2)
180
+ if match.group(2).startswith("\n"):
181
+ language = detect_language(code_block)
182
+ if language:
183
+ return f"```{language}{code_block}```"
184
+ else:
185
+ return f"```\n{code_block}```"
186
+ else:
187
+ return match.group(1) + code_block + "```"
188
+
189
+ text2 = code_block_pattern.sub(replacement, text)
190
+ return text2
191
+
192
+ def delete_last_conversation(chatbot, history):
193
+ if len(chatbot) > 0:
194
+ chatbot.pop()
195
+
196
+ if len(history) > 0:
197
+ history.pop()
198
+
199
+ return (
200
+ chatbot,
201
+ history,
202
+ "Delete Done",
203
+ )
204
+
205
+ def reset_state():
206
+ return [], [], "Reset Done"
207
+
208
+ def reset_textbox():
209
+ return gr.update(value=""),""
210
+
211
+ def cancel_outputing():
212
+ return "Stop Done"
213
+
214
+ def transfer_input(inputs):
215
+ # 一次性返回,降低延迟
216
+ textbox = reset_textbox()
217
+ return (
218
+ inputs,
219
+ gr.update(value=""),
220
+ gr.Button.update(visible=True),
221
+ )
222
+
223
+
224
+ class State:
225
+ interrupted = False
226
+
227
+ def interrupt(self):
228
+ self.interrupted = True
229
+
230
+ def recover(self):
231
+ self.interrupted = False
232
+ shared_state = State()
233
+
234
+
235
+
236
+
237
+
238
+ # Greedy Search
239
+ def greedy_search(input_ids: torch.Tensor,
240
+ model: torch.nn.Module,
241
+ tokenizer: transformers.PreTrainedTokenizer,
242
+ stop_words: list,
243
+ max_length: int,
244
+ temperature: float = 1.0,
245
+ top_p: float = 1.0,
246
+ top_k: int = 25) -> Iterator[str]:
247
+ generated_tokens = []
248
+ past_key_values = None
249
+ current_length = 1
250
+ for i in range(max_length):
251
+ with torch.no_grad():
252
+ if past_key_values is None:
253
+ outputs = model(input_ids)
254
+ else:
255
+ outputs = model(input_ids[:, -1:], past_key_values=past_key_values)
256
+ logits = outputs.logits[:, -1, :]
257
+ past_key_values = outputs.past_key_values
258
+
259
+ # apply temperature
260
+ logits /= temperature
261
+
262
+ probs = torch.softmax(logits, dim=-1)
263
+ # apply top_p
264
+ probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
265
+ probs_sum = torch.cumsum(probs_sort, dim=-1)
266
+ mask = probs_sum - probs_sort > top_p
267
+ probs_sort[mask] = 0.0
268
+
269
+ # apply top_k
270
+ #if top_k is not None:
271
+ # probs_sort1, _ = torch.topk(probs_sort, top_k)
272
+ # min_top_probs_sort = torch.min(probs_sort1, dim=-1, keepdim=True).values
273
+ # probs_sort = torch.where(probs_sort < min_top_probs_sort, torch.full_like(probs_sort, float(0.0)), probs_sort)
274
+
275
+ probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
276
+ next_token = torch.multinomial(probs_sort, num_samples=1)
277
+ next_token = torch.gather(probs_idx, -1, next_token)
278
+
279
+ input_ids = torch.cat((input_ids, next_token), dim=-1)
280
+
281
+ generated_tokens.append(next_token[0].item())
282
+ text = tokenizer.decode(generated_tokens)
283
+
284
+ yield text
285
+ if any([x in text for x in stop_words]):
286
+ del past_key_values
287
+ del logits
288
+ del probs
289
+ del probs_sort
290
+ del probs_idx
291
+ del probs_sum
292
+ gc.collect()
293
+ return
294
+
295
+ def generate_prompt_with_history(text,history,tokenizer,max_length=2048):
296
+ prompt = "The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n[|Human|]Hello!\n[|AI|]Hi!"
297
+ history = ["\n[|Human|]{}\n[|AI|]{}".format(x[0],x[1]) for x in history]
298
+ history.append("\n[|Human|]{}\n[|AI|]".format(text))
299
+ history_text = ""
300
+ flag = False
301
+ for x in history[::-1]:
302
+ if tokenizer(prompt+history_text+x, return_tensors="pt")['input_ids'].size(-1) <= max_length:
303
+ history_text = x + history_text
304
+ flag = True
305
+ else:
306
+ break
307
+ if flag:
308
+ return prompt+history_text,tokenizer(prompt+history_text, return_tensors="pt")
309
+ else:
310
+ return None
311
+
312
+
313
+ def is_stop_word_or_prefix(s: str, stop_words: list) -> bool:
314
+ for stop_word in stop_words:
315
+ if s.endswith(stop_word):
316
+ return True
317
+ for i in range(1, len(stop_word)):
318
+ if s.endswith(stop_word[:i]):
319
+ return True
320
+ return False
321
+
322
+
323
+
324
+ def load_tokenizer_and_model(base_model,adapter_model,load_8bit=False):
325
+ if torch.cuda.is_available():
326
+ device = "cuda"
327
+ else:
328
+ device = "cpu"
329
+
330
+ try:
331
+ if torch.backends.mps.is_available():
332
+ device = "mps"
333
+ except: # noqa: E722
334
+ pass
335
+ tokenizer = LlamaTokenizer.from_pretrained(base_model)
336
+ if device == "cuda":
337
+ model = LlamaForCausalLM.from_pretrained(
338
+ base_model,
339
+ load_in_8bit=load_8bit,
340
+ torch_dtype=torch.float16,
341
+ device_map="auto",
342
+ )
343
+ model = PeftModel.from_pretrained(
344
+ model,
345
+ adapter_model,
346
+ torch_dtype=torch.float16,
347
+ )
348
+ elif device == "mps":
349
+ model = LlamaForCausalLM.from_pretrained(
350
+ base_model,
351
+ device_map={"": device},
352
+ torch_dtype=torch.float16,
353
+ )
354
+ model = PeftModel.from_pretrained(
355
+ model,
356
+ adapter_model,
357
+ device_map={"": device},
358
+ torch_dtype=torch.float16,
359
+ )
360
+ else:
361
+ model = LlamaForCausalLM.from_pretrained(
362
+ base_model, device_map={"": device}, low_cpu_mem_usage=True
363
+ )
364
+ model = PeftModel.from_pretrained(
365
+ model,
366
+ adapter_model,
367
+ device_map={"": device},
368
+ )
369
+
370
+ if not load_8bit:
371
+ model.half() # seems to fix bugs for some users.
372
+
373
+ model.eval()
374
+ return tokenizer,model,device
375
+
assets/Kelpy-Codos.js ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ==UserScript==
2
+ // @name Kelpy Codos
3
+ // @namespace https://github.com/Keldos-Li/Kelpy-Codos
4
+ // @version 1.0.5
5
+ // @author Keldos; https://keldos.me/
6
+ // @description Add copy button to PRE tags before CODE tag, for Chuanhu ChatGPT especially.
7
+ // Based on Chuanhu ChatGPT version: ac04408 (2023-3-22)
8
+ // @license GPL-3.0
9
+ // @grant none
10
+ // ==/UserScript==
11
+
12
+ (function () {
13
+ 'use strict';
14
+
15
+ function addCopyButton(pre) {
16
+ var code = pre.querySelector('code');
17
+ if (!code) {
18
+ return; // 如果没有找到 <code> 元素,则不添加按钮
19
+ }
20
+ var firstChild = code.firstChild;
21
+ if (!firstChild) {
22
+ return; // 如果 <code> 元素没有子节点,则不添加按钮
23
+ }
24
+ var button = document.createElement('button');
25
+ button.textContent = '\uD83D\uDCCE'; // 使用 📎 符号作为“复制”按钮的文本
26
+ button.style.position = 'relative';
27
+ button.style.float = 'right';
28
+ button.style.fontSize = '1em'; // 可选:调整按钮大小
29
+ button.style.background = 'none'; // 可选:去掉背景颜色
30
+ button.style.border = 'none'; // 可选:去掉边框
31
+ button.style.cursor = 'pointer'; // 可选:显示指针样式
32
+ button.addEventListener('click', function () {
33
+ var range = document.createRange();
34
+ range.selectNodeContents(code);
35
+ range.setStartBefore(firstChild); // 将范围设置为第一个子节点之前
36
+ var selection = window.getSelection();
37
+ selection.removeAllRanges();
38
+ selection.addRange(range);
39
+
40
+ try {
41
+ var success = document.execCommand('copy');
42
+ if (success) {
43
+ button.textContent = '\u2714';
44
+ setTimeout(function () {
45
+ button.textContent = '\uD83D\uDCCE'; // 恢复按钮为“复制”
46
+ }, 2000);
47
+ } else {
48
+ button.textContent = '\u2716';
49
+ }
50
+ } catch (e) {
51
+ console.error(e);
52
+ button.textContent = '\u2716';
53
+ }
54
+
55
+ selection.removeAllRanges();
56
+ });
57
+ code.insertBefore(button, firstChild); // 将按钮插入到第一个子元素之前
58
+ }
59
+
60
+ function handleNewElements(mutationsList, observer) {
61
+ for (var mutation of mutationsList) {
62
+ if (mutation.type === 'childList') {
63
+ for (var node of mutation.addedNodes) {
64
+ if (node.nodeName === 'PRE') {
65
+ addCopyButton(node);
66
+ }
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ var observer = new MutationObserver(handleNewElements);
73
+ observer.observe(document.documentElement, { childList: true, subtree: true });
74
+
75
+ document.querySelectorAll('pre').forEach(addCopyButton);
76
+ })();
assets/custom.css ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --chatbot-color-light: #F3F3F3;
3
+ --chatbot-color-dark: #121111;
4
+ }
5
+
6
+ /* status_display */
7
+ #status_display {
8
+ display: flex;
9
+ min-height: 2.5em;
10
+ align-items: flex-end;
11
+ justify-content: flex-end;
12
+ }
13
+ #status_display p {
14
+ font-size: .85em;
15
+ font-family: monospace;
16
+ color: var(--body-text-color-subdued);
17
+ }
18
+
19
+
20
+
21
+ /* usage_display */
22
+ #usage_display {
23
+ height: 1em;
24
+ }
25
+ #usage_display p{
26
+ padding: 0 1em;
27
+ font-size: .85em;
28
+ font-family: monospace;
29
+ color: var(--body-text-color-subdued);
30
+ }
31
+ /* list */
32
+ ol:not(.options), ul:not(.options) {
33
+ padding-inline-start: 2em !important;
34
+ }
35
+
36
+ /* Thank @Keldos-Li for fixing it */
37
+ /* Light mode (default) */
38
+ #chuanhu_chatbot {
39
+ background-color: var(--chatbot-color-light) !important;
40
+ color: #000000 !important;
41
+ }
42
+ [data-testid = "bot"] {
43
+ background-color: #FFFFFF !important;
44
+ }
45
+ [data-testid = "user"] {
46
+ background-color: #95EC69 !important;
47
+ }
48
+
49
+ /* Dark mode */
50
+ .dark #chuanhu_chatbot {
51
+ background-color: var(--chatbot-color-dark) !important;
52
+ color: #FFFFFF !important;
53
+ }
54
+ .dark [data-testid = "bot"] {
55
+ background-color: #2C2C2C !important;
56
+ }
57
+ .dark [data-testid = "user"] {
58
+ background-color: #26B561 !important;
59
+ }
60
+
61
+ #chuanhu_chatbot {
62
+ height: 100%;
63
+ min-height: 400px;
64
+ }
65
+
66
+ [class *= "message"] {
67
+ border-radius: var(--radius-xl) !important;
68
+ border: none;
69
+ padding: var(--spacing-xl) !important;
70
+ font-size: var(--text-md) !important;
71
+ line-height: var(--line-md) !important;
72
+ min-height: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
73
+ min-width: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
74
+ }
75
+ [data-testid = "bot"] {
76
+ max-width: 85%;
77
+ border-bottom-left-radius: 0 !important;
78
+ }
79
+ [data-testid = "user"] {
80
+ max-width: 85%;
81
+ width: auto !important;
82
+ border-bottom-right-radius: 0 !important;
83
+ }
84
+ /* Table */
85
+ table {
86
+ margin: 1em 0;
87
+ border-collapse: collapse;
88
+ empty-cells: show;
89
+ }
90
+ td,th {
91
+ border: 1.2px solid var(--border-color-primary) !important;
92
+ padding: 0.2em;
93
+ }
94
+ thead {
95
+ background-color: rgba(175,184,193,0.2);
96
+ }
97
+ thead th {
98
+ padding: .5em .2em;
99
+ }
100
+ /* Inline code */
101
+ code {
102
+ display: inline;
103
+ white-space: break-spaces;
104
+ border-radius: 6px;
105
+ margin: 0 2px 0 2px;
106
+ padding: .2em .4em .1em .4em;
107
+ background-color: rgba(175,184,193,0.2);
108
+ }
109
+ /* Code block */
110
+ pre code {
111
+ display: block;
112
+ overflow: auto;
113
+ white-space: pre;
114
+ background-color: hsla(0, 0%, 0%, 80%)!important;
115
+ border-radius: 10px;
116
+ padding: 1.4em 1.2em 0em 1.4em;
117
+ margin: 1.2em 2em 1.2em 0.5em;
118
+ color: #FFF;
119
+ box-shadow: 6px 6px 16px hsla(0, 0%, 0%, 0.2);
120
+ }
121
+ /* Hightlight */
122
+ .highlight .hll { background-color: #49483e }
123
+ .highlight .c { color: #75715e } /* Comment */
124
+ .highlight .err { color: #960050; background-color: #1e0010 } /* Error */
125
+ .highlight .k { color: #66d9ef } /* Keyword */
126
+ .highlight .l { color: #ae81ff } /* Literal */
127
+ .highlight .n { color: #f8f8f2 } /* Name */
128
+ .highlight .o { color: #f92672 } /* Operator */
129
+ .highlight .p { color: #f8f8f2 } /* Punctuation */
130
+ .highlight .ch { color: #75715e } /* Comment.Hashbang */
131
+ .highlight .cm { color: #75715e } /* Comment.Multiline */
132
+ .highlight .cp { color: #75715e } /* Comment.Preproc */
133
+ .highlight .cpf { color: #75715e } /* Comment.PreprocFile */
134
+ .highlight .c1 { color: #75715e } /* Comment.Single */
135
+ .highlight .cs { color: #75715e } /* Comment.Special */
136
+ .highlight .gd { color: #f92672 } /* Generic.Deleted */
137
+ .highlight .ge { font-style: italic } /* Generic.Emph */
138
+ .highlight .gi { color: #a6e22e } /* Generic.Inserted */
139
+ .highlight .gs { font-weight: bold } /* Generic.Strong */
140
+ .highlight .gu { color: #75715e } /* Generic.Subheading */
141
+ .highlight .kc { color: #66d9ef } /* Keyword.Constant */
142
+ .highlight .kd { color: #66d9ef } /* Keyword.Declaration */
143
+ .highlight .kn { color: #f92672 } /* Keyword.Namespace */
144
+ .highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
145
+ .highlight .kr { color: #66d9ef } /* Keyword.Reserved */
146
+ .highlight .kt { color: #66d9ef } /* Keyword.Type */
147
+ .highlight .ld { color: #e6db74 } /* Literal.Date */
148
+ .highlight .m { color: #ae81ff } /* Literal.Number */
149
+ .highlight .s { color: #e6db74 } /* Literal.String */
150
+ .highlight .na { color: #a6e22e } /* Name.Attribute */
151
+ .highlight .nb { color: #f8f8f2 } /* Name.Builtin */
152
+ .highlight .nc { color: #a6e22e } /* Name.Class */
153
+ .highlight .no { color: #66d9ef } /* Name.Constant */
154
+ .highlight .nd { color: #a6e22e } /* Name.Decorator */
155
+ .highlight .ni { color: #f8f8f2 } /* Name.Entity */
156
+ .highlight .ne { color: #a6e22e } /* Name.Exception */
157
+ .highlight .nf { color: #a6e22e } /* Name.Function */
158
+ .highlight .nl { color: #f8f8f2 } /* Name.Label */
159
+ .highlight .nn { color: #f8f8f2 } /* Name.Namespace */
160
+ .highlight .nx { color: #a6e22e } /* Name.Other */
161
+ .highlight .py { color: #f8f8f2 } /* Name.Property */
162
+ .highlight .nt { color: #f92672 } /* Name.Tag */
163
+ .highlight .nv { color: #f8f8f2 } /* Name.Variable */
164
+ .highlight .ow { color: #f92672 } /* Operator.Word */
165
+ .highlight .w { color: #f8f8f2 } /* Text.Whitespace */
166
+ .highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
167
+ .highlight .mf { color: #ae81ff } /* Literal.Number.Float */
168
+ .highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
169
+ .highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
170
+ .highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
171
+ .highlight .sa { color: #e6db74 } /* Literal.String.Affix */
172
+ .highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
173
+ .highlight .sc { color: #e6db74 } /* Literal.String.Char */
174
+ .highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
175
+ .highlight .sd { color: #e6db74 } /* Literal.String.Doc */
176
+ .highlight .s2 { color: #e6db74 } /* Literal.String.Double */
177
+ .highlight .se { color: #ae81ff } /* Literal.String.Escape */
178
+ .highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
179
+ .highlight .si { color: #e6db74 } /* Literal.String.Interpol */
180
+ .highlight .sx { color: #e6db74 } /* Literal.String.Other */
181
+ .highlight .sr { color: #e6db74 } /* Literal.String.Regex */
182
+ .highlight .s1 { color: #e6db74 } /* Literal.String.Single */
183
+ .highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
184
+ .highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
185
+ .highlight .fm { color: #a6e22e } /* Name.Function.Magic */
186
+ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
187
+ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
188
+ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
189
+ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
190
+ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
assets/custom.js ADDED
@@ -0,0 +1 @@
 
 
1
+ // custom javascript here
assets/favicon.ico ADDED
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio @ https://gradio-builds.s3.amazonaws.com/reset-iterator/attempt-01/gradio-3.24.1-py3-none-any.whl
2
+ mdtex2html
3
+ pypinyin
4
+ tiktoken
5
+ socksio
6
+ tqdm
7
+ colorama
8
+ duckduckgo_search
9
+ Pygments
10
+ llama_index
11
+ langchain
12
+ markdown
13
+ markdown2
14
+ torch
15
+ git+https://github.com/huggingface/peft.git
16
+ git+https://github.com/huggingface/transformers.git
17
+ SentencePiece