circlecircle wangrongsheng commited on
Commit
07abe0e
0 Parent(s):

Duplicate from wangrongsheng/ChatPaper

Browse files

Co-authored-by: wangrongsheng <wangrongsheng@users.noreply.huggingface.co>

Files changed (5) hide show
  1. .gitattributes +34 -0
  2. README.md +14 -0
  3. app.py +730 -0
  4. optimizeOpenAI.py +226 -0
  5. requirements.txt +11 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatPaper
3
+ emoji: 🚀
4
+ colorFrom: pink
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 3.20.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: gpl-3.0
11
+ duplicated_from: wangrongsheng/ChatPaper
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import os
3
+ import re
4
+ import datetime
5
+ import arxiv
6
+ import openai, tenacity
7
+ import base64, requests
8
+ import argparse
9
+ import configparser
10
+ import fitz, io, os
11
+ from PIL import Image
12
+ import gradio
13
+ import markdown
14
+ import json
15
+ import tiktoken
16
+ import concurrent.futures
17
+ from optimizeOpenAI import chatPaper
18
+ def parse_text(text):
19
+ lines = text.split("\n")
20
+ for i,line in enumerate(lines):
21
+ if "```" in line:
22
+ items = line.split('`')
23
+ if items[-1]:
24
+ lines[i] = f'<pre><code class="{items[-1]}">'
25
+ else:
26
+ lines[i] = f'</code></pre>'
27
+ else:
28
+ if i>0:
29
+ line = line.replace("<", "&lt;")
30
+ line = line.replace(">", "&gt;")
31
+ lines[i] = '<br/>'+line.replace(" ", "&nbsp;")
32
+ return "".join(lines)
33
+
34
+ # def get_response(system, context, myKey, raw = False):
35
+ # openai.api_key = myKey
36
+ # response = openai.ChatCompletion.create(
37
+ # model="gpt-3.5-turbo",
38
+ # messages=[system, *context],
39
+ # )
40
+ # openai.api_key = ""
41
+ # if raw:
42
+ # return response
43
+ # else:
44
+ # message = response["choices"][0]["message"]["content"]
45
+ # message_with_stats = f'{message}'
46
+ # return message, parse_text(message_with_stats)
47
+
48
+ valid_api_keys = []
49
+
50
+ def api_key_check(api_key):
51
+ try:
52
+ chat = chatPaper([api_key])
53
+ if chat.check_api_available():
54
+ return api_key
55
+ else:
56
+ return None
57
+ except:
58
+ return None
59
+
60
+ def valid_apikey(api_keys):
61
+ api_keys = api_keys.replace(' ', '')
62
+ api_key_list = api_keys.split(',')
63
+ print(api_key_list)
64
+ global valid_api_keys
65
+ with concurrent.futures.ThreadPoolExecutor() as executor:
66
+ future_results = {executor.submit(api_key_check, api_key): api_key for api_key in api_key_list}
67
+ for future in concurrent.futures.as_completed(future_results):
68
+ result = future.result()
69
+ if result:
70
+ valid_api_keys.append(result)
71
+ if len(valid_api_keys) > 0:
72
+ return "有效的api-key一共有{}个,分别是:{}, 现在可以提交你的paper".format(len(valid_api_keys), valid_api_keys)
73
+ return "无效的api-key"
74
+
75
+
76
+ class Paper:
77
+ def __init__(self, path, title='', url='', abs='', authers=[], sl=[]):
78
+ # 初始化函数,根据pdf路径初始化Paper对象
79
+ self.url = url # 文章链接
80
+ self.path = path # pdf路径
81
+ self.sl = sl
82
+ self.section_names = [] # 段落标题
83
+ self.section_texts = {} # 段落内容
84
+ self.abs = abs
85
+ self.title_page = 0
86
+ if title == '':
87
+ self.pdf = fitz.open(self.path) # pdf文档
88
+ self.title = self.get_title()
89
+ self.parse_pdf()
90
+ else:
91
+ self.title = title
92
+ self.authers = authers
93
+ self.roman_num = ["I", "II", 'III', "IV", "V", "VI", "VII", "VIII", "IIX", "IX", "X"]
94
+ self.digit_num = [str(d+1) for d in range(10)]
95
+ self.first_image = ''
96
+
97
+ def parse_pdf(self):
98
+ self.pdf = fitz.open(self.path) # pdf文档
99
+ self.text_list = [page.get_text() for page in self.pdf]
100
+ self.all_text = ' '.join(self.text_list)
101
+ self.section_page_dict = self._get_all_page_index() # 段落与页码的对应字典
102
+ print("section_page_dict", self.section_page_dict)
103
+ self.section_text_dict = self._get_all_page() # 段落与内容的对应字典
104
+ self.section_text_dict.update({"title": self.title})
105
+ self.section_text_dict.update({"paper_info": self.get_paper_info()})
106
+ self.pdf.close()
107
+
108
+ def get_paper_info(self):
109
+ first_page_text = self.pdf[self.title_page].get_text()
110
+ if "Abstract" in self.section_text_dict.keys():
111
+ abstract_text = self.section_text_dict['Abstract']
112
+ else:
113
+ abstract_text = self.abs
114
+ introduction_text = self.section_text_dict['Introduction']
115
+ first_page_text = first_page_text.replace(abstract_text, "").replace(introduction_text, "")
116
+ return first_page_text
117
+
118
+ def get_image_path(self, image_path=''):
119
+ """
120
+ 将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取
121
+ :param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf"
122
+ :param image_path: 图片提取后的保存路径
123
+ :return:
124
+ """
125
+ # open file
126
+ max_size = 0
127
+ image_list = []
128
+ with fitz.Document(self.path) as my_pdf_file:
129
+ # 遍历所有页面
130
+ for page_number in range(1, len(my_pdf_file) + 1):
131
+ # 查看独立页面
132
+ page = my_pdf_file[page_number - 1]
133
+ # 查看当前页所有图片
134
+ images = page.get_images()
135
+ # 遍历当���页面所有图片
136
+ for image_number, image in enumerate(page.get_images(), start=1):
137
+ # 访问图片xref
138
+ xref_value = image[0]
139
+ # 提取图片信息
140
+ base_image = my_pdf_file.extract_image(xref_value)
141
+ # 访问图片
142
+ image_bytes = base_image["image"]
143
+ # 获取图片扩展名
144
+ ext = base_image["ext"]
145
+ # 加载图片
146
+ image = Image.open(io.BytesIO(image_bytes))
147
+ image_size = image.size[0] * image.size[1]
148
+ if image_size > max_size:
149
+ max_size = image_size
150
+ image_list.append(image)
151
+ for image in image_list:
152
+ image_size = image.size[0] * image.size[1]
153
+ if image_size == max_size:
154
+ image_name = f"image.{ext}"
155
+ im_path = os.path.join(image_path, image_name)
156
+ print("im_path:", im_path)
157
+
158
+ max_pix = 480
159
+ origin_min_pix = min(image.size[0], image.size[1])
160
+
161
+ if image.size[0] > image.size[1]:
162
+ min_pix = int(image.size[1] * (max_pix/image.size[0]))
163
+ newsize = (max_pix, min_pix)
164
+ else:
165
+ min_pix = int(image.size[0] * (max_pix/image.size[1]))
166
+ newsize = (min_pix, max_pix)
167
+ image = image.resize(newsize)
168
+
169
+ image.save(open(im_path, "wb"))
170
+ return im_path, ext
171
+ return None, None
172
+
173
+ # 定义一个函数,根据字体的大小,识别每个章节名称,并返回一个列表
174
+ def get_chapter_names(self,):
175
+ # # 打开一个pdf文件
176
+ doc = fitz.open(self.path) # pdf文档
177
+ text_list = [page.get_text() for page in doc]
178
+ all_text = ''
179
+ for text in text_list:
180
+ all_text += text
181
+ # # 创建一个空列表,用于存储章节名称
182
+ chapter_names = []
183
+ for line in all_text.split('\n'):
184
+ line_list = line.split(' ')
185
+ if '.' in line:
186
+ point_split_list = line.split('.')
187
+ space_split_list = line.split(' ')
188
+ if 1 < len(space_split_list) < 5:
189
+ if 1 < len(point_split_list) < 5 and (point_split_list[0] in self.roman_num or point_split_list[0] in self.digit_num):
190
+ print("line:", line)
191
+ chapter_names.append(line)
192
+
193
+ return chapter_names
194
+
195
+ def get_title(self):
196
+ doc = self.pdf # 打开pdf文件
197
+ max_font_size = 0 # 初始化最大字体大小为0
198
+ max_string = "" # 初始化最大字体大小对应的字符串为空
199
+ max_font_sizes = [0]
200
+ for page_index, page in enumerate(doc): # 遍历每一页
201
+ text = page.get_text("dict") # 获取页面上的文本信息
202
+ blocks = text["blocks"] # 获取文本块列表
203
+ for block in blocks: # 遍历每个文本块
204
+ if block["type"] == 0 and len(block['lines']): # 如果是文字类型
205
+ if len(block["lines"][0]["spans"]):
206
+ font_size = block["lines"][0]["spans"][0]["size"] # 获取第一行第一段文字的字体大小
207
+ max_font_sizes.append(font_size)
208
+ if font_size > max_font_size: # 如果字体大小大于当前最大值
209
+ max_font_size = font_size # 更新最大值
210
+ max_string = block["lines"][0]["spans"][0]["text"] # 更新最大值对应的字符串
211
+ max_font_sizes.sort()
212
+ print("max_font_sizes", max_font_sizes[-10:])
213
+ cur_title = ''
214
+ for page_index, page in enumerate(doc): # 遍历每一页
215
+ text = page.get_text("dict") # 获取页面上的文本信息
216
+ blocks = text["blocks"] # 获取文本块列表
217
+ for block in blocks: # 遍历每个文本块
218
+ if block["type"] == 0 and len(block['lines']): # 如果是文字类型
219
+ if len(block["lines"][0]["spans"]):
220
+ cur_string = block["lines"][0]["spans"][0]["text"] # 更新最大值对应的字符串
221
+ font_flags = block["lines"][0]["spans"][0]["flags"] # 获取第一行第一段文字的字体特征
222
+ font_size = block["lines"][0]["spans"][0]["size"] # 获取第一行第一段文字的字体大小
223
+ # print(font_size)
224
+ if abs(font_size - max_font_sizes[-1]) < 0.3 or abs(font_size - max_font_sizes[-2]) < 0.3:
225
+ # print("The string is bold.", max_string, "font_size:", font_size, "font_flags:", font_flags)
226
+ if len(cur_string) > 4 and "arXiv" not in cur_string:
227
+ # print("The string is bold.", max_string, "font_size:", font_size, "font_flags:", font_flags)
228
+ if cur_title == '' :
229
+ cur_title += cur_string
230
+ else:
231
+ cur_title += ' ' + cur_string
232
+ self.title_page = page_index
233
+
234
+ title = cur_title.replace('\n', ' ')
235
+ return title
236
+
237
+ def _get_all_page_index(self):
238
+ # 定义需要寻找的章节名称列表
239
+ section_list = self.sl
240
+ # 初始化一个字典来存储找到的章节和它们在文档中出现的页码
241
+ section_page_dict = {}
242
+ # 遍历每一页文档
243
+ for page_index, page in enumerate(self.pdf):
244
+ # 获取当前页面的文本内容
245
+ cur_text = page.get_text()
246
+ # 遍历需要寻找的章节名称列表
247
+ for section_name in section_list:
248
+ # 将章节名称转换成大写形式
249
+ section_name_upper = section_name.upper()
250
+ # 如果当前页面包含"Abstract"这个关键词
251
+ if "Abstract" == section_name and section_name in cur_text:
252
+ # 将"Abstract"和它所在的页码加入字典中
253
+ section_page_dict[section_name] = page_index
254
+ # 如果当前页面包含章节名称,则将章节名称和它所在的页码加入字典中
255
+ else:
256
+ if section_name + '\n' in cur_text:
257
+ section_page_dict[section_name] = page_index
258
+ elif section_name_upper + '\n' in cur_text:
259
+ section_page_dict[section_name] = page_index
260
+ # 返回所有找到的章节名称及它们在文档中出现的页码
261
+ return section_page_dict
262
+
263
+ def _get_all_page(self):
264
+ """
265
+ 获取PDF文件中每个页面的文本信息,并将文本信息按照章节组织成字典返回。
266
+ Returns:
267
+ section_dict (dict): 每个章节的文本信息字典,key为章节名,value为章节文本。
268
+ """
269
+ text = ''
270
+ text_list = []
271
+ section_dict = {}
272
+
273
+ # 再处理其他章节:
274
+ text_list = [page.get_text() for page in self.pdf]
275
+ for sec_index, sec_name in enumerate(self.section_page_dict):
276
+ print(sec_index, sec_name, self.section_page_dict[sec_name])
277
+ if sec_index <= 0 and self.abs:
278
+ continue
279
+ else:
280
+ # 直接考虑后面的内容:
281
+ start_page = self.section_page_dict[sec_name]
282
+ if sec_index < len(list(self.section_page_dict.keys()))-1:
283
+ end_page = self.section_page_dict[list(self.section_page_dict.keys())[sec_index+1]]
284
+ else:
285
+ end_page = len(text_list)
286
+ print("start_page, end_page:", start_page, end_page)
287
+ cur_sec_text = ''
288
+ if end_page - start_page == 0:
289
+ if sec_index < len(list(self.section_page_dict.keys()))-1:
290
+ next_sec = list(self.section_page_dict.keys())[sec_index+1]
291
+ if text_list[start_page].find(sec_name) == -1:
292
+ start_i = text_list[start_page].find(sec_name.upper())
293
+ else:
294
+ start_i = text_list[start_page].find(sec_name)
295
+ if text_list[start_page].find(next_sec) == -1:
296
+ end_i = text_list[start_page].find(next_sec.upper())
297
+ else:
298
+ end_i = text_list[start_page].find(next_sec)
299
+ cur_sec_text += text_list[start_page][start_i:end_i]
300
+ else:
301
+ for page_i in range(start_page, end_page):
302
+ # print("page_i:", page_i)
303
+ if page_i == start_page:
304
+ if text_list[start_page].find(sec_name) == -1:
305
+ start_i = text_list[start_page].find(sec_name.upper())
306
+ else:
307
+ start_i = text_list[start_page].find(sec_name)
308
+ cur_sec_text += text_list[page_i][start_i:]
309
+ elif page_i < end_page:
310
+ cur_sec_text += text_list[page_i]
311
+ elif page_i == end_page:
312
+ if sec_index < len(list(self.section_page_dict.keys()))-1:
313
+ next_sec = list(self.section_page_dict.keys())[sec_index+1]
314
+ if text_list[start_page].find(next_sec) == -1:
315
+ end_i = text_list[start_page].find(next_sec.upper())
316
+ else:
317
+ end_i = text_list[start_page].find(next_sec)
318
+ cur_sec_text += text_list[page_i][:end_i]
319
+ section_dict[sec_name] = cur_sec_text.replace('-\n', '').replace('\n', ' ')
320
+ return section_dict
321
+
322
+ # 定义Reader类
323
+ class Reader:
324
+ # 初始化方法,设置属性
325
+ def __init__(self, key_word='', query='', filter_keys='',
326
+ root_path='./',
327
+ gitee_key='',
328
+ sort=arxiv.SortCriterion.SubmittedDate, user_name='defualt', language='cn', api_keys:list = [], model_name="gpt-3.5-turbo", p=1.0, temperature=1.0):
329
+ self.api_keys = api_keys
330
+ self.chatPaper = chatPaper( api_keys = self.api_keys, apiTimeInterval=10 , temperature=temperature,top_p=p,model_name=model_name) #openAI api封装
331
+ self.user_name = user_name # 读者姓名
332
+ self.key_word = key_word # 读者感兴趣的关键词
333
+ self.query = query # 读者输入的搜索查询
334
+ self.sort = sort # 读者选择的排序方式
335
+ self.language = language # 读者选择的语言
336
+ self.filter_keys = filter_keys # 用于在摘要中筛选的关键词
337
+ self.root_path = root_path
338
+ self.file_format = 'md' # or 'txt',如果为图片,则必须为'md'
339
+ self.save_image = False
340
+ if self.save_image:
341
+ self.gitee_key = self.config.get('Gitee', 'api')
342
+ else:
343
+ self.gitee_key = ''
344
+ self.max_token_num = 4096
345
+ self.encoding = tiktoken.get_encoding("gpt2")
346
+
347
+ def get_arxiv(self, max_results=30):
348
+ search = arxiv.Search(query=self.query,
349
+ max_results=max_results,
350
+ sort_by=self.sort,
351
+ sort_order=arxiv.SortOrder.Descending,
352
+ )
353
+ return search
354
+
355
+ def filter_arxiv(self, max_results=30):
356
+ search = self.get_arxiv(max_results=max_results)
357
+ print("all search:")
358
+ for index, result in enumerate(search.results()):
359
+ print(index, result.title, result.updated)
360
+
361
+ filter_results = []
362
+ filter_keys = self.filter_keys
363
+
364
+ print("filter_keys:", self.filter_keys)
365
+ # 确保每个关键词都能在摘要中找到,才算是目标论文
366
+ for index, result in enumerate(search.results()):
367
+ abs_text = result.summary.replace('-\n', '-').replace('\n', ' ')
368
+ meet_num = 0
369
+ for f_key in filter_keys.split(" "):
370
+ if f_key.lower() in abs_text.lower():
371
+ meet_num += 1
372
+ if meet_num == len(filter_keys.split(" ")):
373
+ filter_results.append(result)
374
+ # break
375
+ print("filter_results:", len(filter_results))
376
+ print("filter_papers:")
377
+ for index, result in enumerate(filter_results):
378
+ print(index, result.title, result.updated)
379
+ return filter_results
380
+
381
+ def validateTitle(self, title):
382
+ # 将论文的乱七八糟的路径格式修正
383
+ rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > |'
384
+ new_title = re.sub(rstr, "_", title) # 替换为下划线
385
+ return new_title
386
+
387
+ def download_pdf(self, filter_results):
388
+ # 先创建文件夹
389
+ date_str = str(datetime.datetime.now())[:13].replace(' ', '-')
390
+ key_word = str(self.key_word.replace(':', ' '))
391
+ path = self.root_path + 'pdf_files/' + self.query.replace('au: ', '').replace('title: ', '').replace('ti: ', '').replace(':', ' ')[:25] + '-' + date_str
392
+ try:
393
+ os.makedirs(path)
394
+ except:
395
+ pass
396
+ print("All_paper:", len(filter_results))
397
+ # 开始下载:
398
+ paper_list = []
399
+ for r_index, result in enumerate(filter_results):
400
+ try:
401
+ title_str = self.validateTitle(result.title)
402
+ pdf_name = title_str+'.pdf'
403
+ # result.download_pdf(path, filename=pdf_name)
404
+ self.try_download_pdf(result, path, pdf_name)
405
+ paper_path = os.path.join(path, pdf_name)
406
+ print("paper_path:", paper_path)
407
+ paper = Paper(path=paper_path,
408
+ url=result.entry_id,
409
+ title=result.title,
410
+ abs=result.summary.replace('-\n', '-').replace('\n', ' '),
411
+ authers=[str(aut) for aut in result.authors],
412
+ )
413
+ # 下载完毕,开始解析:
414
+ paper.parse_pdf()
415
+ paper_list.append(paper)
416
+ except Exception as e:
417
+ print("download_error:", e)
418
+ pass
419
+ return paper_list
420
+
421
+ @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
422
+ stop=tenacity.stop_after_attempt(5),
423
+ reraise=True)
424
+ def try_download_pdf(self, result, path, pdf_name):
425
+ result.download_pdf(path, filename=pdf_name)
426
+
427
+ @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
428
+ stop=tenacity.stop_after_attempt(5),
429
+ reraise=True)
430
+ def upload_gitee(self, image_path, image_name='', ext='png'):
431
+ """
432
+ 上传到码云
433
+ :return:
434
+ """
435
+ with open(image_path, 'rb') as f:
436
+ base64_data = base64.b64encode(f.read())
437
+ base64_content = base64_data.decode()
438
+
439
+ date_str = str(datetime.datetime.now())[:19].replace(':', '-').replace(' ', '-') + '.' + ext
440
+ path = image_name+ '-' +date_str
441
+
442
+ payload = {
443
+ "access_token": self.gitee_key,
444
+ "owner": self.config.get('Gitee', 'owner'),
445
+ "repo": self.config.get('Gitee', 'repo'),
446
+ "path": self.config.get('Gitee', 'path'),
447
+ "content": base64_content,
448
+ "message": "upload image"
449
+ }
450
+ # 这里需要修改成你的gitee的账户和仓库名,以及文件夹的名字:
451
+ url = f'https://gitee.com/api/v5/repos/'+self.config.get('Gitee', 'owner')+'/'+self.config.get('Gitee', 'repo')+'/contents/'+self.config.get('Gitee', 'path')+'/'+path
452
+ rep = requests.post(url, json=payload).json()
453
+ print("rep:", rep)
454
+ if 'content' in rep.keys():
455
+ image_url = rep['content']['download_url']
456
+ else:
457
+ image_url = r"https://gitee.com/api/v5/repos/"+self.config.get('Gitee', 'owner')+'/'+self.config.get('Gitee', 'repo')+'/contents/'+self.config.get('Gitee', 'path')+'/' + path
458
+
459
+ return image_url
460
+
461
+ def summary_with_chat(self, paper_list):
462
+ htmls = []
463
+ utoken = 0
464
+ ctoken = 0
465
+ ttoken = 0
466
+ for paper_index, paper in enumerate(paper_list):
467
+ # 第一步先用title,abs,和introduction进行总结。
468
+ text = ''
469
+ text += 'Title:' + paper.title
470
+ text += 'Url:' + paper.url
471
+ text += 'Abstrat:' + paper.abs
472
+ text += 'Paper_info:' + paper.section_text_dict['paper_info']
473
+ # intro
474
+ text += list(paper.section_text_dict.values())[0]
475
+ #max_token = 2500 * 4
476
+ #text = text[:max_token]
477
+ chat_summary_text, utoken1, ctoken1, ttoken1 = self.chat_summary(text=text)
478
+ htmls.append(chat_summary_text)
479
+
480
+ # TODO 往md文档中插入论文里的像素最大的一张图片,这个方案可以弄的更加智能一些:
481
+ method_key = ''
482
+ for parse_key in paper.section_text_dict.keys():
483
+ if 'method' in parse_key.lower() or 'approach' in parse_key.lower():
484
+ method_key = parse_key
485
+ break
486
+
487
+ if method_key != '':
488
+ text = ''
489
+ method_text = ''
490
+ summary_text = ''
491
+ summary_text += "<summary>" + chat_summary_text
492
+ # methods
493
+ method_text += paper.section_text_dict[method_key]
494
+ text = summary_text + "\n<Methods>:\n" + method_text
495
+ chat_method_text, utoken2, ctoken2, ttoken2 = self.chat_method(text=text)
496
+ htmls.append(chat_method_text)
497
+ else:
498
+ chat_method_text = ''
499
+ htmls.append("\n")
500
+
501
+ # 第三步总结全文,并打分:
502
+ conclusion_key = ''
503
+ for parse_key in paper.section_text_dict.keys():
504
+ if 'conclu' in parse_key.lower():
505
+ conclusion_key = parse_key
506
+ break
507
+
508
+ text = ''
509
+ conclusion_text = ''
510
+ summary_text = ''
511
+ summary_text += "<summary>" + chat_summary_text + "\n <Method summary>:\n" + chat_method_text
512
+ if conclusion_key != '':
513
+ # conclusion
514
+ conclusion_text += paper.section_text_dict[conclusion_key]
515
+ text = summary_text + "\n <Conclusion>:\n" + conclusion_text
516
+ else:
517
+ text = summary_text
518
+ chat_conclusion_text, utoken3, ctoken3, ttoken3 = self.chat_conclusion(text=text)
519
+ htmls.append(chat_conclusion_text)
520
+ htmls.append("\n")
521
+ # token统计
522
+ utoken = utoken + utoken1 + utoken2 + utoken3
523
+ ctoken = ctoken + ctoken1 + ctoken2 + ctoken3
524
+ ttoken = ttoken + ttoken1 + ttoken2 + ttoken3
525
+ cost = (ttoken / 1000) * 0.002
526
+ pos_count = {
527
+ "usage_token_used": str(utoken),
528
+ "completion_token_used": str(ctoken),
529
+ "total_token_used": str(ttoken),
530
+ "cost": str(cost),
531
+ }
532
+ md_text = "\n".join(htmls)
533
+ return markdown.markdown(md_text), pos_count
534
+
535
+
536
+ @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
537
+ stop=tenacity.stop_after_attempt(5),
538
+ reraise=True)
539
+ def chat_conclusion(self, text):
540
+ conclusion_prompt_token = 650
541
+ text_token = len(self.encoding.encode(text))
542
+ clip_text_index = int(len(text)*(self.max_token_num-conclusion_prompt_token)/text_token)
543
+ clip_text = text[:clip_text_index]
544
+ self.chatPaper.reset(convo_id="chatConclusion",system_prompt="You are a reviewer in the field of ["+self.key_word+"] and you need to critically review this article")
545
+ self.chatPaper.add_to_conversation(convo_id="chatConclusion", role="assistant", message="This is the <summary> and <conclusion> part of an English literature, where <summary> you have already summarized, but <conclusion> part, I need your help to summarize the following questions:"+clip_text)# 背景知识,可以参考OpenReview的审稿流程
546
+ content = """
547
+ 8. Make the following summary.Be sure to use Chinese answers (proper nouns need to be marked in English).
548
+ - (1):What is the significance of this piece of work?
549
+ - (2):Summarize the strengths and weaknesses of this article in three dimensions: innovation point, performance, and workload.
550
+ .......
551
+ Follow the format of the output later:
552
+ 8. Conclusion: \n\n
553
+ - (1):xxx;\n
554
+ - (2):Innovation point: xxx; Performance: xxx; Workload: xxx;\n
555
+
556
+ Be sure to use Chinese answers (proper nouns need to be marked in English), statements as concise and academic as possible, do not repeat the content of the previous <summary>, the value of the use of the original numbers, be sure to strictly follow the format, the corresponding content output to xxx, in accordance with \n line feed, ....... means fill in according to the actual requirements, if not, you can not write.
557
+ """
558
+ result = self.chatPaper.ask(
559
+ prompt = content,
560
+ role="user",
561
+ convo_id="chatConclusion",
562
+ )
563
+ print(result)
564
+ return result[0], result[1], result[2], result[3]
565
+
566
+ @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
567
+ stop=tenacity.stop_after_attempt(5),
568
+ reraise=True)
569
+ def chat_method(self, text):
570
+ method_prompt_token = 650
571
+ text_token = len(self.encoding.encode(text))
572
+ clip_text_index = int(len(text)*(self.max_token_num-method_prompt_token)/text_token)
573
+ clip_text = text[:clip_text_index]
574
+ self.chatPaper.reset(convo_id="chatMethod",system_prompt="You are a researcher in the field of ["+self.key_word+"] who is good at summarizing papers using concise statements")# chatgpt 角色
575
+ self.chatPaper.add_to_conversation(convo_id="chatMethod", role="assistant", message=str("This is the <summary> and <Method> part of an English document, where <summary> you have summarized, but the <Methods> part, I need your help to read and summarize the following questions."+clip_text))
576
+ content= """
577
+ 7. Describe in detail the methodological idea of this article. Be sure to use Chinese answers (proper nouns need to be marked in English). For example, its steps are.
578
+ - (1):...
579
+ - (2):...
580
+ - (3):...
581
+ - .......
582
+ Follow the format of the output that follows:
583
+ 7. Methods: \n\n
584
+ - (1):xxx;\n
585
+ - (2):xxx;\n
586
+ - (3):xxx;\n
587
+ ....... \n\n
588
+
589
+ Be sure to use Chinese answers (proper nouns need to be marked in English), statements as concise and academic as possible, do not repeat the content of the previous <summary>, the value of the use of the original numbers, be sure to strictly follow the format, the corresponding content output to xxx, in accordance with \n line feed, ....... means fill in according to the actual requirements, if not, you can not write.
590
+ """
591
+ result = self.chatPaper.ask(
592
+ prompt = content,
593
+ role="user",
594
+ convo_id="chatMethod",
595
+ )
596
+ print(result)
597
+ return result[0], result[1], result[2], result[3]
598
+
599
+ @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
600
+ stop=tenacity.stop_after_attempt(5),
601
+ reraise=True)
602
+ def chat_summary(self, text):
603
+ summary_prompt_token = 1000
604
+ text_token = len(self.encoding.encode(text))
605
+ clip_text_index = int(len(text)*(self.max_token_num-summary_prompt_token)/text_token)
606
+ clip_text = text[:clip_text_index]
607
+ self.chatPaper.reset(convo_id="chatSummary",system_prompt="You are a researcher in the field of ["+self.key_word+"] who is good at summarizing papers using concise statements")
608
+ self.chatPaper.add_to_conversation(convo_id="chatSummary", role="assistant", message=str("This is the title, author, link, abstract and introduction of an English document. I need your help to read and summarize the following questions: "+clip_text))
609
+ content= """
610
+ 1. Mark the title of the paper (with Chinese translation)
611
+ 2. list all the authors' names (use English)
612
+ 3. mark the first author's affiliation (output Chinese translation only)
613
+ 4. mark the keywords of this article (use English)
614
+ 5. link to the paper, Github code link (if available, fill in Github:None if not)
615
+ 6. summarize according to the following four points.Be sure to use Chinese answers (proper nouns need to be marked in English)
616
+ - (1):What is the research background of this article?
617
+ - (2):What are the past methods? What are the problems with them? Is the approach well motivated?
618
+ - (3):What is the research methodology proposed in this paper?
619
+ - (4):On what task and what performance is achieved by the methods in this paper? Can the performance support their goals?
620
+ Follow the format of the output that follows:
621
+ 1. Title: xxx\n\n
622
+ 2. Authors: xxx\n\n
623
+ 3. Affiliation: xxx\n\n
624
+ 4. Keywords: xxx\n\n
625
+ 5. Urls: xxx or xxx , xxx \n\n
626
+ 6. Summary: \n\n
627
+ - (1):xxx;\n
628
+ - (2):xxx;\n
629
+ - (3):xxx;\n
630
+ - (4):xxx.\n\n
631
+
632
+ Be sure to use Chinese answers (proper nouns need to be marked in English), statements as concise and academic as possible, do not have too much repetitive information, numerical values using the original numbers, be sure to strictly follow the format, the corresponding content output to xxx, in accordance with \n line feed.
633
+ """
634
+ result = self.chatPaper.ask(
635
+ prompt = content,
636
+ role="user",
637
+ convo_id="chatSummary",
638
+ )
639
+ print(result)
640
+ return result[0], result[1], result[2], result[3]
641
+
642
+ def export_to_markdown(self, text, file_name, mode='w'):
643
+ # 使用markdown模块的convert方法,将文本转换为html格式
644
+ # html = markdown.markdown(text)
645
+ # 打开一个文件,以写入模式
646
+ with open(file_name, mode, encoding="utf-8") as f:
647
+ # 将html格式的内容写入文件
648
+ f.write(text)
649
+
650
+ # 定义一个方法,打印出读者信息
651
+ def show_info(self):
652
+ print(f"Key word: {self.key_word}")
653
+ print(f"Query: {self.query}")
654
+ print(f"Sort: {self.sort}")
655
+
656
+ def upload_pdf(api_keys, text, model_name, p, temperature, file):
657
+ # 检查两个输入都不为空
658
+ api_key_list = None
659
+ if api_keys:
660
+ api_key_list = api_keys.split(',')
661
+ elif not api_keys and valid_api_keys!=[]:
662
+ api_key_list = valid_api_keys
663
+ if not text or not file or not api_key_list:
664
+ return "两个输入都不能为空,请输入字符并上传 PDF 文件!"
665
+
666
+ # 判断PDF文件
667
+ #if file and file.name.split(".")[-1].lower() != "pdf":
668
+ # return '请勿上传非 PDF 文件!'
669
+ else:
670
+ section_list = text.split(',')
671
+ paper_list = [Paper(path=file, sl=section_list)]
672
+ # 创建一个Reader对象
673
+ print(api_key_list)
674
+ reader = Reader(api_keys=api_key_list, model_name=model_name, p=p, temperature=temperature)
675
+ sum_info, cost = reader.summary_with_chat(paper_list=paper_list) # type: ignore
676
+ return cost, sum_info
677
+
678
+ api_title = "api-key可用验证"
679
+ api_description = '''<div align='left'>
680
+
681
+ <img src='https://visitor-badge.laobi.icu/badge?page_id=https://huggingface.co/spaces/wangrongsheng/ChatPaper'>
682
+
683
+ <img align='right' src='https://i.328888.xyz/2023/03/12/vH9dU.png' width="150">
684
+
685
+ Use ChatGPT to summary the papers.Star our Github [🌟ChatPaper](https://github.com/kaixindelele/ChatPaper) .
686
+
687
+ 💗如果您觉得我们的项目对您有帮助,还请您给我们一些鼓励!💗
688
+
689
+ 🔴请注意:千万不要用于严肃的学术场景,只能用于论文阅读前的初筛!
690
+
691
+ </div>
692
+ '''
693
+
694
+ api_input = [
695
+ gradio.inputs.Textbox(label="请输入你的API-key(必填, 多个API-key请用英文逗号隔开)", default="", type='password')
696
+ ]
697
+ api_gui = gradio.Interface(fn=valid_apikey, inputs=api_input, outputs="text", title=api_title, description=api_description)
698
+
699
+ # 标题
700
+ title = "ChatPaper"
701
+ # 描述
702
+ description = '''<div align='left'>
703
+
704
+ <img src='https://visitor-badge.laobi.icu/badge?page_id=https://huggingface.co/spaces/wangrongsheng/ChatPaper'>
705
+
706
+ <img align='right' src='https://i.328888.xyz/2023/03/12/vH9dU.png' width="150">
707
+
708
+ Use ChatGPT to summary the papers.Star our Github [🌟ChatPaper](https://github.com/kaixindelele/ChatPaper) .
709
+
710
+ 💗如果您觉得我们的项目对您有帮助,还请您给我们一些鼓励!💗
711
+
712
+ 🔴请注意:千万不要用于严肃的学术场景,只能用于论文阅读前的初筛!
713
+
714
+ </div>
715
+ '''
716
+ # 创建Gradio界面
717
+ ip = [
718
+ gradio.inputs.Textbox(label="请输入你的API-key(必填, 多个API-key请用英文逗号隔开),不需要空格", default="", type='password'),
719
+ gradio.inputs.Textbox(label="请输入论文大标题索引(用英文逗号隔开,必填)", default="'Abstract,Introduction,Related Work,Background,Preliminary,Problem Formulation,Methods,Methodology,Method,Approach,Approaches,Materials and Methods,Experiment Settings,Experiment,Experimental Results,Evaluation,Experiments,Results,Findings,Data Analysis,Discussion,Results and Discussion,Conclusion,References'"),
720
+ gradio.inputs.Radio(choices=["gpt-3.5-turbo", "gpt-3.5-turbo-0301"], default="gpt-3.5-turbo", label="Select model"),
721
+ gradio.inputs.Slider(minimum=-0, maximum=1.0, default=1.0, step=0.05, label="Top-p (nucleus sampling)"),
722
+ gradio.inputs.Slider(minimum=-0, maximum=5.0, default=0.5, step=0.5, label="Temperature"),
723
+ gradio.inputs.File(label="请上传论文PDF(必填)")
724
+ ]
725
+
726
+ chatpaper_gui = gradio.Interface(fn=upload_pdf, inputs=ip, outputs=["json", "html"], title=title, description=description)
727
+
728
+ # Start server
729
+ gui = gradio.TabbedInterface(interface_list=[api_gui, chatpaper_gui], tab_names=["API-key", "ChatPaper"])
730
+ gui.launch(quiet=True,show_api=False)
optimizeOpenAI.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A simple wrapper for the official ChatGPT API
3
+ """
4
+ import json
5
+ import os
6
+ import threading
7
+ import time
8
+ import requests
9
+ import tiktoken
10
+ from typing import Generator
11
+ from queue import PriorityQueue as PQ
12
+ import json
13
+ import os
14
+ import time
15
+ ENCODER = tiktoken.get_encoding("gpt2")
16
+ class chatPaper:
17
+ """
18
+ Official ChatGPT API
19
+ """
20
+ def __init__(
21
+ self,
22
+ api_keys: list,
23
+ proxy = None,
24
+ api_proxy = None,
25
+ max_tokens: int = 4000,
26
+ temperature: float = 0.5,
27
+ top_p: float = 1.0,
28
+ model_name: str = "gpt-3.5-turbo",
29
+ reply_count: int = 1,
30
+ system_prompt = "You are ChatPaper, A paper reading bot",
31
+ lastAPICallTime = time.time()-100,
32
+ apiTimeInterval = 20,
33
+ ) -> None:
34
+ self.model_name = model_name
35
+ self.system_prompt = system_prompt
36
+ self.apiTimeInterval = apiTimeInterval
37
+ self.session = requests.Session()
38
+ self.api_keys = PQ()
39
+ for key in api_keys:
40
+ self.api_keys.put((lastAPICallTime,key))
41
+ self.proxy = proxy
42
+ if self.proxy:
43
+ proxies = {
44
+ "http": self.proxy,
45
+ "https": self.proxy,
46
+ }
47
+ self.session.proxies = proxies
48
+ self.max_tokens = max_tokens
49
+ self.temperature = temperature
50
+ self.top_p = top_p
51
+ self.reply_count = reply_count
52
+ self.decrease_step = 250
53
+ self.conversation = {}
54
+ if self.token_str(self.system_prompt) > self.max_tokens:
55
+ raise Exception("System prompt is too long")
56
+ self.lock = threading.Lock()
57
+
58
+ def get_api_key(self):
59
+ with self.lock:
60
+ apiKey = self.api_keys.get()
61
+ delay = self._calculate_delay(apiKey)
62
+ time.sleep(delay)
63
+ self.api_keys.put((time.time(), apiKey[1]))
64
+ return apiKey[1]
65
+
66
+ def _calculate_delay(self, apiKey):
67
+ elapsed_time = time.time() - apiKey[0]
68
+ if elapsed_time < self.apiTimeInterval:
69
+ return self.apiTimeInterval - elapsed_time
70
+ else:
71
+ return 0
72
+
73
+ def add_to_conversation(self, message: str, role: str, convo_id: str = "default"):
74
+ if(convo_id not in self.conversation):
75
+ self.reset(convo_id)
76
+ self.conversation[convo_id].append({"role": role, "content": message})
77
+
78
+ def __truncate_conversation(self, convo_id: str = "default"):
79
+ """
80
+ Truncate the conversation
81
+ """
82
+ last_dialog = self.conversation[convo_id][-1]
83
+ query = str(last_dialog['content'])
84
+ if(len(ENCODER.encode(str(query)))>self.max_tokens):
85
+ query = query[:int(1.5*self.max_tokens)]
86
+ while(len(ENCODER.encode(str(query)))>self.max_tokens):
87
+ query = query[:self.decrease_step]
88
+ self.conversation[convo_id] = self.conversation[convo_id][:-1]
89
+ full_conversation = "\n".join([str(x["content"]) for x in self.conversation[convo_id]],)
90
+ if len(ENCODER.encode(full_conversation)) > self.max_tokens:
91
+ self.conversation_summary(convo_id=convo_id)
92
+ while True:
93
+ full_conversation = ""
94
+ for x in self.conversation[convo_id]:
95
+ full_conversation = str(x["content"]) + "\n" + full_conversation
96
+ if (len(ENCODER.encode(full_conversation+query)) > self.max_tokens):
97
+ query = query[:self.decrease_step]
98
+ else:
99
+ break
100
+ last_dialog['content'] = str(query)
101
+ self.conversation[convo_id].append(last_dialog)
102
+
103
+ def ask_stream(
104
+ self,
105
+ prompt: str,
106
+ role: str = "user",
107
+ convo_id: str = "default",
108
+ **kwargs,
109
+ ) -> Generator:
110
+ if convo_id not in self.conversation:
111
+ self.reset(convo_id=convo_id)
112
+ self.add_to_conversation(prompt, "user", convo_id=convo_id)
113
+ self.__truncate_conversation(convo_id=convo_id)
114
+ apiKey = self.get_api_key()
115
+ response = self.session.post(
116
+ "https://api.openai.com/v1/chat/completions",
117
+ headers={"Authorization": f"Bearer {kwargs.get('api_key', apiKey)}"},
118
+ json={
119
+ "model": self.model_name,
120
+ "messages": self.conversation[convo_id],
121
+ "stream": True,
122
+ # kwargs
123
+ "temperature": kwargs.get("temperature", self.temperature),
124
+ "top_p": kwargs.get("top_p", self.top_p),
125
+ "n": kwargs.get("n", self.reply_count),
126
+ "user": role,
127
+ },
128
+ stream=True,
129
+ )
130
+ if response.status_code != 200:
131
+ raise Exception(
132
+ f"Error: {response.status_code} {response.reason} {response.text}",
133
+ )
134
+ for line in response.iter_lines():
135
+ if not line:
136
+ continue
137
+ # Remove "data: "
138
+ line = line.decode("utf-8")[6:]
139
+ if line == "[DONE]":
140
+ break
141
+ resp: dict = json.loads(line)
142
+ choices = resp.get("choices")
143
+ if not choices:
144
+ continue
145
+ delta = choices[0].get("delta")
146
+ if not delta:
147
+ continue
148
+ if "content" in delta:
149
+ content = delta["content"]
150
+ yield content
151
+ def ask(self, prompt: str, role: str = "user", convo_id: str = "default", **kwargs):
152
+ """
153
+ Non-streaming ask
154
+ """
155
+ response = self.ask_stream(
156
+ prompt=prompt,
157
+ role=role,
158
+ convo_id=convo_id,
159
+ **kwargs,
160
+ )
161
+ full_response: str = "".join(response)
162
+ self.add_to_conversation(full_response, role, convo_id=convo_id)
163
+ usage_token = self.token_str(prompt)
164
+ com_token = self.token_str(full_response)
165
+ total_token = self.token_cost(convo_id=convo_id)
166
+ return full_response, usage_token, com_token, total_token
167
+
168
+ def check_api_available(self):
169
+ response = self.session.post(
170
+ "https://api.openai.com/v1/chat/completions",
171
+ headers={"Authorization": f"Bearer {self.get_api_key()}"},
172
+ json={
173
+ "model": self.engine,
174
+ "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "print A"}],
175
+ "stream": True,
176
+ # kwargs
177
+ "temperature": self.temperature,
178
+ "top_p": self.top_p,
179
+ "n": self.reply_count,
180
+ "user": "user",
181
+ },
182
+ stream=True,
183
+ )
184
+ if response.status_code == 200:
185
+ return True
186
+ else:
187
+ return False
188
+ def reset(self, convo_id: str = "default", system_prompt = None):
189
+ """
190
+ Reset the conversation
191
+ """
192
+ self.conversation[convo_id] = [
193
+ {"role": "system", "content": str(system_prompt or self.system_prompt)},
194
+ ]
195
+ def conversation_summary(self, convo_id: str = "default"):
196
+ input = ""
197
+ role = ""
198
+ for conv in self.conversation[convo_id]:
199
+ if (conv["role"]=='user'):
200
+ role = 'User'
201
+ else:
202
+ role = 'ChatGpt'
203
+ input+=role+' : '+conv['content']+'\n'
204
+ prompt = "Your goal is to summarize the provided conversation in English. Your summary should be concise and focus on the key information to facilitate better dialogue for the large language model.Ensure that you include all necessary details and relevant information while still reducing the length of the conversation as much as possible. Your summary should be clear and easily understandable for the ChatGpt model providing a comprehensive and concise summary of the conversation."
205
+ if(self.token_str(str(input)+prompt)>self.max_tokens):
206
+ input = input[self.token_str(str(input))-self.max_tokens:]
207
+ while self.token_str(str(input)+prompt)>self.max_tokens:
208
+ input = input[self.decrease_step:]
209
+ prompt = prompt.replace("{conversation}", input)
210
+ self.reset(convo_id='conversationSummary')
211
+ response = self.ask(prompt,convo_id='conversationSummary')
212
+ while self.token_str(str(response))>self.max_tokens:
213
+ response = response[:-self.decrease_step]
214
+ self.reset(convo_id='conversationSummary',system_prompt='Summariaze our diaglog')
215
+ self.conversation[convo_id] = [
216
+ {"role": "system", "content": self.system_prompt},
217
+ {"role": "user", "content": "Summariaze our diaglog"},
218
+ {"role": 'assistant', "content": response},
219
+ ]
220
+ return self.conversation[convo_id]
221
+ def token_cost(self,convo_id: str = "default"):
222
+ return len(ENCODER.encode("\n".join([x["content"] for x in self.conversation[convo_id]])))
223
+ def token_str(self,content:str):
224
+ return len(ENCODER.encode(content))
225
+ def main():
226
+ return
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ arxiv==1.4.3
2
+ PyMuPDF==1.21.1
3
+ requests==2.26.0
4
+ tiktoken==0.2.0
5
+ tenacity==8.2.2
6
+ pybase64==1.2.3
7
+ Pillow==9.4.0
8
+ openai==0.27.0
9
+ markdown
10
+ gradio==3.20.1
11
+ tiktoken