Spaces:
Runtime error
Runtime error
ChatPaperFree Project
Browse files- README.md +185 -13
- app.py +892 -0
- optimizeGoogle.py +228 -0
- requirements.txt +11 -0
README.md
CHANGED
@@ -1,13 +1,185 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# ChatPaperFree GeminiPro
|
2 |
+
|
3 |
+
实际上,这个项目是在ChatPaper的基础上进行的更新,采用了最近由Google开源的Gemini Pro大模型。这样一来,我们可以免费使用ChatPaper,并且未来我还计划加入对论文图片的读取以提取摘要(测试结果是OK的)。
|
4 |
+
|
5 |
+
目前,我们能够对用户输入的论文进行自动总结。未来,我还计划加入对论文图片/表格/公式的识别 extraction,从而生成更全面而易读的总结。如果在对话中chatbot能提供更优质的服务,我还会尝试进行更深层次的模型fine-tuning。我会在后续尝试进行更新,大家也可以提出自己的意见,也欢迎提PR。这是ChatPaper的[GitHub链接](https://github.com/kaixindelele/ChatPaper.git),多多关注。
|
6 |
+
|
7 |
+
另外,为了跟上快速发展的人工智能领域和庞大的arxiv论文,我们从arXiv爬取了大量论文,并制作了网站[进步屋](https://ipaper.today/)使研究人员能够便捷获取当前热点。通过Gemini Pro对论文进行自动归纳,我们可以用极少的文本来展示论文要点,帮助用户快速评估哪篇值得深入研读。
|
8 |
+
|
9 |
+
在这个不断变化的时代,ChatPaperFree GeminiPro通过利用强大技术,有效提升我们学习效率。同时,我们也欢迎你提供关键词,共同完善这个平台,让每个人都能在技术演进中取得新的进步。(可在https://github.com/wmpscc/ipaper.today提出关键词,欢迎)
|
10 |
+
|
11 |
+
希望未来,我们可以搭建更友好的人机合作模式。
|
12 |
+
|
13 |
+
## Usage
|
14 |
+
|
15 |
+
```bash
|
16 |
+
pip install -r requriements.txt
|
17 |
+
python app.py
|
18 |
+
```
|
19 |
+
|
20 |
+
成功后,进入http://127.0.0.1:7860即可,接着就可以输入自己的API key。
|
21 |
+
|
22 |
+
Google的Gemini Pro的API key是免费的,所以大家都是可以申请的,具体申请可以在[https://makersuite.google.com/](https://makersuite.google.com/)进行获取,每个人都可以获取多个,如果大家有自己的一些想法,也可以看谷歌的API使用文档[https://ai.google.dev/tutorials/python_quickstart](https://ai.google.dev/tutorials/python_quickstart)。
|
23 |
+
|
24 |
+

|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
## 获取最新文章(进步屋)
|
29 |
+
|
30 |
+
实际上,这个操作与ChatPaper的爬取论文类似,我们通过爬取最新arxiv论文,根据设定的关键词,每天对论文进行爬取,以最快的速度跟踪最新的文章。实验室已经搭建了一个网站,大家可以多多支持,提出自己的关键词,我们会不定时进行更新,让你每天都能看到最新的文章。
|
31 |
+
|
32 |
+
这是进步屋的网站:[进步屋](https://ipaper.today/) https://ipaper.today/ ,大家如果有什么需要学习的内容,可以给出关键词,在[GitHub](https://github.com/wmpscc/ipaper.today)提issue。
|
33 |
+
|
34 |
+
后续,我还计划加入自动生成摘要和分析的功能,包括尝试让数字人播报等等,敬请期待。
|
35 |
+
|
36 |
+

|
37 |
+
|
38 |
+
|
39 |
+
|
40 |
+
最近,我还会尝试生成文章的简单摘要,丰富内容,这是即将上线的由GPT生成简单摘要的部分,后续还可以加入更多功能,比如ChatPaper的prompt,我猜可以得到更好的效果。
|
41 |
+
|
42 |
+

|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
## 使用技巧:
|
47 |
+
|
48 |
+
- 找到好的文章后,可以精读这篇文章;
|
49 |
+
- 推荐其他两个精读论文的AI辅助网站:[Typeset.io](https://typeset.io/) 和 [chatpdf](https://chatpdf)。
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
## Example1(进步屋)
|
54 |
+
|
55 |
+
比如最近`3D Gassian Splatting`很火,所以我也有关注这一方面,这是我最近爬取最新的几篇文章
|
56 |
+
|
57 |
+
|
58 |
+
|
59 |
+
### Triplane Meets Gaussian Splatting: Fast and Generalizable Single-View 3D Reconstruction with Transformers
|
60 |
+
|
61 |
+
**Authors:Zi-Xin Zou, Zhipeng Yu, Yuan-Chen Guo, Yangguang Li, Ding Liang, Yan-Pei Cao, Song-Hai Zhang**
|
62 |
+
|
63 |
+
Recent advancements in 3D reconstruction from single images have been driven by the evolution of generative models. Prominent among these are methods based on Score Distillation Sampling (SDS) and the adaptation of diffusion models in the 3D domain. Despite their progress, these techniques often face limitations due to slow optimization or rendering processes, leading to extensive training and optimization times. In this paper, we introduce a novel approach for single-view reconstruction that efficiently generates a 3D model from a single image via feed-forward inference. Our method utilizes two transformer-based networks, namely a point decoder and a triplane decoder, to reconstruct 3D objects using a hybrid Triplane-Gaussian intermediate representation. This hybrid representation strikes a balance, achieving a faster rendering speed compared to implicit representations while simultaneously delivering superior rendering quality than explicit representations. The point decoder is designed for generating point clouds from single images, offering an explicit representation which is then utilized by the triplane decoder to query Gaussian features for each point. This design choice addresses the challenges associated with directly regressing explicit 3D Gaussian attributes characterized by their non-structural nature. Subsequently, the 3D Gaussians are decoded by an MLP to enable rapid rendering through splatting. Both decoders are built upon a scalable, transformer-based architecture and have been efficiently trained on large-scale 3D datasets. The evaluations conducted on both synthetic datasets and real-world images demonstrate that our method not only achieves higher quality but also ensures a faster runtime in comparison to previous state-of-the-art techniques. Please see our project page at https://zouzx.github.io/TriplaneGaussian/.
|
64 |
+
|
65 |
+
[PDF](http://arxiv.org/abs/2312.09147v1)
|
66 |
+
|
67 |
+
**Summary**
|
68 |
+
基于变分自编码器和扩散模型的3D单视图重建方法取得了长足的进步。
|
69 |
+
|
70 |
+
**Key Takeaways**
|
71 |
+
|
72 |
+
- 利用变压器网络和点解码器实现单图像的3D对象重建
|
73 |
+
- 使用混合的Triplane-Gaussian中间表示实现更快的渲染速度和更高的渲染质量
|
74 |
+
- 通过MLP解码3D高斯以实现快速渲染
|
75 |
+
- 在合成数据集和真实图像上进行了有效的评估
|
76 |
+
- 相比于先前的技术,方法达到了更高的质量和更快的运行时间
|
77 |
+
- 方法的详细信息可在https://zouzx.github.io/TriplaneGaussian/上找到。
|
78 |
+
|
79 |
+
|
80 |
+
<details>
|
81 |
+
<summary>点此查看论文截图</summary>
|
82 |
+
<img src="./crop_Gaussian Splatting/2312.09147v1/page_0_0.jpg" align="middle">
|
83 |
+
<img src="./crop_Gaussian Splatting/2312.09147v1/page_2_0.jpg" align="middle">
|
84 |
+
<img src="./crop_Gaussian Splatting/2312.09147v1/page_5_0.jpg" align="middle">
|
85 |
+
</details>
|
86 |
+
|
87 |
+
|
88 |
+
|
89 |
+
### 3DGS-Avatar: Animatable Avatars via Deformable 3D Gaussian Splatting
|
90 |
+
|
91 |
+
**Authors:Zhiyin Qian, Shaofei Wang, Marko Mihajlovic, Andreas Geiger, Siyu Tang**
|
92 |
+
|
93 |
+
We introduce an approach that creates animatable human avatars from monocular videos using 3D Gaussian Splatting (3DGS). Existing methods based on neural radiance fields (NeRFs) achieve high-quality novel-view/novel-pose image synthesis but often require days of training, and are extremely slow at inference time. Recently, the community has explored fast grid structures for efficient training of clothed avatars. Albeit being extremely fast at training, these methods can barely achieve an interactive rendering frame rate with around 15 FPS. In this paper, we use 3D Gaussian Splatting and learn a non-rigid deformation network to reconstruct animatable clothed human avatars that can be trained within 30 minutes and rendered at real-time frame rates (50+ FPS). Given the explicit nature of our representation, we further introduce as-isometric-as-possible regularizations on both the Gaussian mean vectors and the covariance matrices, enhancing the generalization of our model on highly articulated unseen poses. Experimental results show that our method achieves comparable and even better performance compared to state-of-the-art approaches on animatable avatar creation from a monocular input, while being 400x and 250x faster in training and inference, respectively.
|
94 |
+
|
95 |
+
[PDF](http://arxiv.org/abs/2312.09228v1)
|
96 |
+
|
97 |
+
**Summary**
|
98 |
+
使用三维高斯点阵和非刚性变形网络创建可动人体化身,训练时间短,渲染速度快。
|
99 |
+
|
100 |
+
**Key Takeaways**
|
101 |
+
|
102 |
+
- 3D高斯点阵创建可动人体化身,训练时间30分钟,渲染速度50+ FPS
|
103 |
+
- 引入正则化提高模型在高度复杂的姿势上的泛化能力
|
104 |
+
- 实验结果表明方法在从单眼输入创建可动化身方面性能优越
|
105 |
+
- 与现有方法相比,训练速度快400倍,推理速度快250倍
|
106 |
+
|
107 |
+
|
108 |
+
<details>
|
109 |
+
<summary>点此查看论文截图</summary>
|
110 |
+
<img src="./crop_Gaussian Splatting/2312.09228v1/page_0_0.jpg" align="middle">
|
111 |
+
<img src="./crop_Gaussian Splatting/2312.09228v1/page_1_0.jpg" align="middle">
|
112 |
+
<img src="./crop_Gaussian Splatting/2312.09228v1/page_3_0.jpg" align="middle">
|
113 |
+
<img src="./crop_Gaussian Splatting/2312.09228v1/page_4_0.jpg" align="middle">
|
114 |
+
</details>
|
115 |
+
|
116 |
+
|
117 |
+
|
118 |
+
## Example2(ChatPaperFree)
|
119 |
+
|
120 |
+
比如这里使用上述的 `3DGS-Avatar: Animatable Avatars via Deformable 3D Gaussian Splatting` 进行测试,大家都可以尝试一下
|
121 |
+
|
122 |
+

|
123 |
+
|
124 |
+
1. 论文标题:3DGS-Avatar:可变形3D高斯点云生成的可动画身
|
125 |
+
|
126 |
+
2. 作者:
|
127 |
+
|
128 |
+
- Changil Kim
|
129 |
+
- Jinwoo Kim
|
130 |
+
- Tae-Hyun Oh
|
131 |
+
- Joon-Young Lee
|
132 |
+
- In So Kweon
|
133 |
+
|
134 |
+
3. 第一作者单位:韩国科学技术院(KAIST)
|
135 |
+
|
136 |
+
4. 关键词:
|
137 |
+
|
138 |
+
- 可动画身
|
139 |
+
- 3D高斯点云生成
|
140 |
+
- 可变形神经场
|
141 |
+
- 单目视频
|
142 |
+
|
143 |
+
5. 论文链接:https://arxiv.org/abs/2312.09228 Github 链接:None
|
144 |
+
|
145 |
+
6. 摘要:
|
146 |
+
|
147 |
+
|
148 |
+
|
149 |
+
(1):研究背景:
|
150 |
+
|
151 |
+
- 重建可动画身具有广泛的应用前景,但从图像输入中重建衣着的人体模型是一项具有挑战性的任务。
|
152 |
+
- 基于NeRF的神经辐射场方法在几何和外观重建方面取得了很好的效果,但训练和推理过程非常耗时。
|
153 |
+
- 最近提出的3D高斯点���生成方法在静态场景重建中取得了很好的效果,具有快速训练和推理的优点。
|
154 |
+
|
155 |
+
(2):过去方法和问题:
|
156 |
+
|
157 |
+
- 现有方法主要依赖于NeRF或其变体,但这些方法通常需要大型的多层感知机来建模神经辐射场,导致训练和推理过程非常耗时。
|
158 |
+
- 一些方法尝试使用更快的训练和推理方法,但它们通常会牺牲渲染质量或无法对姿势相关的非刚性变形进行建模。
|
159 |
+
|
160 |
+
(3):研究方法:
|
161 |
+
|
162 |
+
- 本文提出了一种基于3D高斯点云生成的可动画身重建方法。
|
163 |
+
- 该方法将刚性人体关节与非刚性变形场有效地集成到3D高斯点云生成框架中。
|
164 |
+
- 使用了一个小型多层感知机来解码颜色,该感知机能够对局部非刚性变形和动态光照条件做出响应。
|
165 |
+
- 应用了“尽可能等距”正则化项,以保持几何一致性和逼真的变形,尤其是在动态和变化的姿势中。
|
166 |
+
|
167 |
+
(4):实验结果:
|
168 |
+
|
169 |
+
- 在单目视频输入的情况下,该方法在可动画身创建方面与最先进的方法相当或更好,训练速度提高了400倍,推理速度提高了250倍。
|
170 |
+
- 与专注于快速训练的方法相比,该方法虽然训练速度较慢,但能够对姿势相关的非刚性变形进行建模,并产生明显更好的渲染质量,同时渲染速度提高了3倍。
|
171 |
+
|
172 |
+
7. 方法:
|
173 |
+
|
174 |
+
(1):提出了一种基于3D高斯点云生成的可动画身重建方法,将刚性人体关节与非刚性变形场有效地集成到3D高斯点云生成框架中;
|
175 |
+
|
176 |
+
(2):使用了一个小型多层感知机来解码颜色,该感知机能够对局部非刚性变形和动态光照条件做出响应;
|
177 |
+
|
178 |
+
(3):应用了“尽可能等距”正则化项,以保持几何一致性和逼真的变形,尤其是在动态和变化的姿势中。
|
179 |
+
|
180 |
+
8. 结论:
|
181 |
+
|
182 |
+
(1):本文提出了一种基于 3D 高斯点云生成的可动画身重建方法,该方法在单目视频输入的情况下,在可动画身创建方面与最先进的方法相当或更好,训练速度提高了 400 倍,推理速度提高了 250 倍。
|
183 |
+
|
184 |
+
(2):创新点:提出了一种基于 3D 高斯点云生成的可动画身重建方法,将刚性人体关节与非刚性变形场有效地集成到 3D 高斯点云生成框架中;使用了一个小型多层感知机来解码颜色,该感知机能够对局部非刚性变形和动态光照条件做出响应;应用了“尽可能等距”正则化项,以保持几何一致性和逼真的变形,尤其是在动态和变化的姿势中。性能:在单目视频输入的情况下,该方法在可动画身创建方面与最先进的方法相当或更好,训练速度提高了 400 倍,推理速度提高了 250 倍;与专注于快速训练的方法相比,该方法虽然训练速度较慢,但能够对姿势相关的非刚性变形进行建模,并产生明显更好的渲染质量,同时渲染速度提高了 3 倍。工作量:该方法的训练和推理速度都非常快,训练一个模型只需要几分钟,推理一个模型只需要几毫秒。
|
185 |
+
|
app.py
ADDED
@@ -0,0 +1,892 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 mistune
|
15 |
+
import json
|
16 |
+
import tiktoken
|
17 |
+
import concurrent.futures
|
18 |
+
from optimizeGoogle import chatPaper
|
19 |
+
|
20 |
+
proxy = {'http':'http://127.0.0.1:7890',
|
21 |
+
'https':'http://127.0.0.1:7890'}
|
22 |
+
|
23 |
+
def parse_text(text):
|
24 |
+
lines = text.split("\n")
|
25 |
+
for i, line in enumerate(lines):
|
26 |
+
if "```" in line:
|
27 |
+
items = line.split('`')
|
28 |
+
if items[-1]:
|
29 |
+
lines[i] = f'<pre><code class="{items[-1]}">'
|
30 |
+
else:
|
31 |
+
lines[i] = f'</code></pre>'
|
32 |
+
else:
|
33 |
+
if i > 0:
|
34 |
+
line = line.replace("<", "<")
|
35 |
+
line = line.replace(">", ">")
|
36 |
+
lines[i] = '<br/>' + line.replace(" ", " ")
|
37 |
+
return "".join(lines)
|
38 |
+
|
39 |
+
|
40 |
+
# def get_response(system, context, myKey, raw = False):
|
41 |
+
# openai.api_key = myKey
|
42 |
+
# response = openai.ChatCompletion.create(
|
43 |
+
# model="gpt-3.5-turbo",
|
44 |
+
# messages=[system, *context],
|
45 |
+
# )
|
46 |
+
# openai.api_key = ""
|
47 |
+
# if raw:
|
48 |
+
# return response
|
49 |
+
# else:
|
50 |
+
# message = response["choices"][0]["message"]["content"]
|
51 |
+
# message_with_stats = f'{message}'
|
52 |
+
# return message, parse_text(message_with_stats)
|
53 |
+
|
54 |
+
valid_api_keys = []
|
55 |
+
|
56 |
+
|
57 |
+
def api_key_check(api_key):
|
58 |
+
try:
|
59 |
+
chat = chatPaper([api_key], proxy=proxy)
|
60 |
+
if chat.check_api_available():
|
61 |
+
return api_key
|
62 |
+
else:
|
63 |
+
return None
|
64 |
+
except Exception as e:
|
65 |
+
# print(e)
|
66 |
+
return None
|
67 |
+
|
68 |
+
|
69 |
+
def valid_apikey(api_keys):
|
70 |
+
api_keys = api_keys.replace(' ', '')
|
71 |
+
api_key_list = api_keys.split(',')
|
72 |
+
print(api_key_list)
|
73 |
+
global valid_api_keys
|
74 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
75 |
+
future_results = {
|
76 |
+
executor.submit(api_key_check, api_key): api_key
|
77 |
+
for api_key in api_key_list
|
78 |
+
}
|
79 |
+
for future in concurrent.futures.as_completed(future_results):
|
80 |
+
result = future.result()
|
81 |
+
if result:
|
82 |
+
valid_api_keys.append(result)
|
83 |
+
if len(valid_api_keys) > 0:
|
84 |
+
return "有效的api-key一共有{}个,分别是:{}, 现在可以提交你的paper".format(
|
85 |
+
len(valid_api_keys), valid_api_keys)
|
86 |
+
return "无效的api-key"
|
87 |
+
|
88 |
+
|
89 |
+
class Paper:
|
90 |
+
|
91 |
+
def __init__(self, path, title='', url='', abs='', authers=[], sl=[]):
|
92 |
+
# 初始化函数,根据pdf路径初始化Paper对象
|
93 |
+
self.url = url # 文章链接
|
94 |
+
self.path = path # pdf路径
|
95 |
+
self.sl = sl
|
96 |
+
self.section_names = [] # 段落标题
|
97 |
+
self.section_texts = {} # 段落内容
|
98 |
+
self.abs = abs
|
99 |
+
self.title_page = 0
|
100 |
+
if title == '':
|
101 |
+
self.pdf = fitz.open(self.path) # pdf文档
|
102 |
+
self.title = self.get_title()
|
103 |
+
self.parse_pdf()
|
104 |
+
else:
|
105 |
+
self.title = title
|
106 |
+
self.authers = authers
|
107 |
+
self.roman_num = [
|
108 |
+
"I", "II", 'III', "IV", "V", "VI", "VII", "VIII", "IIX", "IX", "X"
|
109 |
+
]
|
110 |
+
self.digit_num = [str(d + 1) for d in range(10)]
|
111 |
+
self.first_image = ''
|
112 |
+
|
113 |
+
def parse_pdf(self):
|
114 |
+
self.pdf = fitz.open(self.path) # pdf文档
|
115 |
+
self.text_list = [page.get_text() for page in self.pdf]
|
116 |
+
self.all_text = ' '.join(self.text_list)
|
117 |
+
self.section_page_dict = self._get_all_page_index() # 段落与页码的对应字典
|
118 |
+
print("section_page_dict", self.section_page_dict)
|
119 |
+
self.section_text_dict = self._get_all_page() # 段落与内容的对应字典
|
120 |
+
self.section_text_dict.update({"title": self.title})
|
121 |
+
self.section_text_dict.update({"paper_info": self.get_paper_info()})
|
122 |
+
self.pdf.close()
|
123 |
+
|
124 |
+
def get_paper_info(self):
|
125 |
+
first_page_text = self.pdf[self.title_page].get_text()
|
126 |
+
if "Abstract" in self.section_text_dict.keys():
|
127 |
+
abstract_text = self.section_text_dict['Abstract']
|
128 |
+
else:
|
129 |
+
abstract_text = self.abs
|
130 |
+
introduction_text = self.section_text_dict['Introduction']
|
131 |
+
first_page_text = first_page_text.replace(abstract_text, "").replace(
|
132 |
+
introduction_text, "")
|
133 |
+
return first_page_text
|
134 |
+
|
135 |
+
def get_image_path(self, image_path=''):
|
136 |
+
"""
|
137 |
+
将PDF中的第一张图保存到image.png里面,存到本地目录,返回文件名称,供gitee读取
|
138 |
+
:param filename: 图片所在路径,"C:\\Users\\Administrator\\Desktop\\nwd.pdf"
|
139 |
+
:param image_path: 图片提取后的保存路径
|
140 |
+
:return:
|
141 |
+
"""
|
142 |
+
# open file
|
143 |
+
max_size = 0
|
144 |
+
image_list = []
|
145 |
+
with fitz.Document(self.path) as my_pdf_file:
|
146 |
+
# 遍历所有页面
|
147 |
+
for page_number in range(1, len(my_pdf_file) + 1):
|
148 |
+
# 查看独立页面
|
149 |
+
page = my_pdf_file[page_number - 1]
|
150 |
+
# 查看当前页所有图片
|
151 |
+
images = page.get_images()
|
152 |
+
# 遍历当前页面所有图片
|
153 |
+
for image_number, image in enumerate(page.get_images(),
|
154 |
+
start=1):
|
155 |
+
# 访问图片xref
|
156 |
+
xref_value = image[0]
|
157 |
+
# 提取图片信息
|
158 |
+
base_image = my_pdf_file.extract_image(xref_value)
|
159 |
+
# 访问图片
|
160 |
+
image_bytes = base_image["image"]
|
161 |
+
# 获取图片扩展名
|
162 |
+
ext = base_image["ext"]
|
163 |
+
# 加载图片
|
164 |
+
image = Image.open(io.BytesIO(image_bytes))
|
165 |
+
image_size = image.size[0] * image.size[1]
|
166 |
+
if image_size > max_size:
|
167 |
+
max_size = image_size
|
168 |
+
image_list.append(image)
|
169 |
+
for image in image_list:
|
170 |
+
image_size = image.size[0] * image.size[1]
|
171 |
+
if image_size == max_size:
|
172 |
+
image_name = f"image.{ext}"
|
173 |
+
im_path = os.path.join(image_path, image_name)
|
174 |
+
print("im_path:", im_path)
|
175 |
+
|
176 |
+
max_pix = 480
|
177 |
+
origin_min_pix = min(image.size[0], image.size[1])
|
178 |
+
|
179 |
+
if image.size[0] > image.size[1]:
|
180 |
+
min_pix = int(image.size[1] * (max_pix / image.size[0]))
|
181 |
+
newsize = (max_pix, min_pix)
|
182 |
+
else:
|
183 |
+
min_pix = int(image.size[0] * (max_pix / image.size[1]))
|
184 |
+
newsize = (min_pix, max_pix)
|
185 |
+
image = image.resize(newsize)
|
186 |
+
|
187 |
+
image.save(open(im_path, "wb"))
|
188 |
+
return im_path, ext
|
189 |
+
return None, None
|
190 |
+
|
191 |
+
# 定义一个函数,根据字体的大小,识别每个章节名称,并返回一个列表
|
192 |
+
def get_chapter_names(self, ):
|
193 |
+
# # 打开一个pdf文件
|
194 |
+
doc = fitz.open(self.path) # pdf文档
|
195 |
+
text_list = [page.get_text() for page in doc]
|
196 |
+
all_text = ''
|
197 |
+
for text in text_list:
|
198 |
+
all_text += text
|
199 |
+
# # 创建一个空列表,用于存储章节名称
|
200 |
+
chapter_names = []
|
201 |
+
for line in all_text.split('\n'):
|
202 |
+
line_list = line.split(' ')
|
203 |
+
if '.' in line:
|
204 |
+
point_split_list = line.split('.')
|
205 |
+
space_split_list = line.split(' ')
|
206 |
+
if 1 < len(space_split_list) < 5:
|
207 |
+
if 1 < len(point_split_list) < 5 and (
|
208 |
+
point_split_list[0] in self.roman_num
|
209 |
+
or point_split_list[0] in self.digit_num):
|
210 |
+
print("line:", line)
|
211 |
+
chapter_names.append(line)
|
212 |
+
|
213 |
+
return chapter_names
|
214 |
+
|
215 |
+
def get_title(self):
|
216 |
+
doc = self.pdf # 打开pdf文件
|
217 |
+
max_font_size = 0 # 初始化最大字体大小为0
|
218 |
+
max_string = "" # 初始化最大字体大小对应的字符串为空
|
219 |
+
max_font_sizes = [0]
|
220 |
+
for page_index, page in enumerate(doc): # 遍历每一页
|
221 |
+
text = page.get_text("dict") # 获取页面上的文本信息
|
222 |
+
blocks = text["blocks"] # 获取文本块列表
|
223 |
+
for block in blocks: # 遍历每个文本块
|
224 |
+
if block["type"] == 0 and len(block['lines']): # 如果是文字类型
|
225 |
+
if len(block["lines"][0]["spans"]):
|
226 |
+
font_size = block["lines"][0]["spans"][0][
|
227 |
+
"size"] # 获取第一行第一段文字的字体大小
|
228 |
+
max_font_sizes.append(font_size)
|
229 |
+
if font_size > max_font_size: # 如果字体大小大于当前最大值
|
230 |
+
max_font_size = font_size # 更新最大值
|
231 |
+
max_string = block["lines"][0]["spans"][0][
|
232 |
+
"text"] # 更新最大值对应的字符串
|
233 |
+
max_font_sizes.sort()
|
234 |
+
print("max_font_sizes", max_font_sizes[-10:])
|
235 |
+
cur_title = ''
|
236 |
+
for page_index, page in enumerate(doc): # 遍历每一页
|
237 |
+
text = page.get_text("dict") # 获取页面上的文本信息
|
238 |
+
blocks = text["blocks"] # 获取文本块列表
|
239 |
+
for block in blocks: # 遍历每个文本块
|
240 |
+
if block["type"] == 0 and len(block['lines']): # 如果是文字类型
|
241 |
+
if len(block["lines"][0]["spans"]):
|
242 |
+
cur_string = block["lines"][0]["spans"][0][
|
243 |
+
"text"] # 更新最大值对应的字符串
|
244 |
+
font_flags = block["lines"][0]["spans"][0][
|
245 |
+
"flags"] # 获取第一行第一段文字的字体特征
|
246 |
+
font_size = block["lines"][0]["spans"][0][
|
247 |
+
"size"] # 获取第一行第一段文字的字体大小
|
248 |
+
# print(font_size)
|
249 |
+
if abs(font_size - max_font_sizes[-1]) < 0.3 or abs(
|
250 |
+
font_size - max_font_sizes[-2]) < 0.3:
|
251 |
+
# print("The string is bold.", max_string, "font_size:", font_size, "font_flags:", font_flags)
|
252 |
+
if len(cur_string
|
253 |
+
) > 4 and "arXiv" not in cur_string:
|
254 |
+
# print("The string is bold.", max_string, "font_size:", font_size, "font_flags:", font_flags)
|
255 |
+
if cur_title == '':
|
256 |
+
cur_title += cur_string
|
257 |
+
else:
|
258 |
+
cur_title += ' ' + cur_string
|
259 |
+
self.title_page = page_index
|
260 |
+
|
261 |
+
title = cur_title.replace('\n', ' ')
|
262 |
+
return title
|
263 |
+
|
264 |
+
def _get_all_page_index(self):
|
265 |
+
# 定义需要寻找的章节名称列表
|
266 |
+
section_list = self.sl
|
267 |
+
# 初始化一个字典来存储找到的章节和它们在文档中出现的页码
|
268 |
+
section_page_dict = {}
|
269 |
+
# 遍历每一页文档
|
270 |
+
for page_index, page in enumerate(self.pdf):
|
271 |
+
# 获取当前页面的文本内容
|
272 |
+
cur_text = page.get_text()
|
273 |
+
# 遍历需要寻找的章节名称列表
|
274 |
+
for section_name in section_list:
|
275 |
+
# 将章节名称转换成大写形式
|
276 |
+
section_name_upper = section_name.upper()
|
277 |
+
# 如果当前页面包含"Abstract"这个关键词
|
278 |
+
if "Abstract" == section_name and section_name in cur_text:
|
279 |
+
# 将"Abstract"和它所在的页码加入字典中
|
280 |
+
section_page_dict[section_name] = page_index
|
281 |
+
# 如果当前页面包含章节名称,则将章节名称和它所在的页码加入字典中
|
282 |
+
else:
|
283 |
+
if section_name + '\n' in cur_text:
|
284 |
+
section_page_dict[section_name] = page_index
|
285 |
+
elif section_name_upper + '\n' in cur_text:
|
286 |
+
section_page_dict[section_name] = page_index
|
287 |
+
# 返回所有找到的章节名称及它们在文档中出现的页码
|
288 |
+
return section_page_dict
|
289 |
+
|
290 |
+
def _get_all_page(self):
|
291 |
+
"""
|
292 |
+
获取PDF文件中每个页面的文本信息,并将文本信息按照章节组织成字典返回。
|
293 |
+
Returns:
|
294 |
+
section_dict (dict): 每个章节的文本信息字典,key为章节名,value为章节文本。
|
295 |
+
"""
|
296 |
+
text = ''
|
297 |
+
text_list = []
|
298 |
+
section_dict = {}
|
299 |
+
|
300 |
+
# 再处理其他章节:
|
301 |
+
text_list = [page.get_text() for page in self.pdf]
|
302 |
+
for sec_index, sec_name in enumerate(self.section_page_dict):
|
303 |
+
print(sec_index, sec_name, self.section_page_dict[sec_name])
|
304 |
+
if sec_index <= 0 and self.abs:
|
305 |
+
continue
|
306 |
+
else:
|
307 |
+
# 直接考虑后面的内容:
|
308 |
+
start_page = self.section_page_dict[sec_name]
|
309 |
+
if sec_index < len(list(self.section_page_dict.keys())) - 1:
|
310 |
+
end_page = self.section_page_dict[list(
|
311 |
+
self.section_page_dict.keys())[sec_index + 1]]
|
312 |
+
else:
|
313 |
+
end_page = len(text_list)
|
314 |
+
print("start_page, end_page:", start_page, end_page)
|
315 |
+
cur_sec_text = ''
|
316 |
+
if end_page - start_page == 0:
|
317 |
+
if sec_index < len(list(
|
318 |
+
self.section_page_dict.keys())) - 1:
|
319 |
+
next_sec = list(
|
320 |
+
self.section_page_dict.keys())[sec_index + 1]
|
321 |
+
if text_list[start_page].find(sec_name) == -1:
|
322 |
+
start_i = text_list[start_page].find(
|
323 |
+
sec_name.upper())
|
324 |
+
else:
|
325 |
+
start_i = text_list[start_page].find(sec_name)
|
326 |
+
if text_list[start_page].find(next_sec) == -1:
|
327 |
+
end_i = text_list[start_page].find(
|
328 |
+
next_sec.upper())
|
329 |
+
else:
|
330 |
+
end_i = text_list[start_page].find(next_sec)
|
331 |
+
cur_sec_text += text_list[start_page][start_i:end_i]
|
332 |
+
else:
|
333 |
+
for page_i in range(start_page, end_page):
|
334 |
+
# print("page_i:", page_i)
|
335 |
+
if page_i == start_page:
|
336 |
+
if text_list[start_page].find(sec_name) == -1:
|
337 |
+
start_i = text_list[start_page].find(
|
338 |
+
sec_name.upper())
|
339 |
+
else:
|
340 |
+
start_i = text_list[start_page].find(sec_name)
|
341 |
+
cur_sec_text += text_list[page_i][start_i:]
|
342 |
+
elif page_i < end_page:
|
343 |
+
cur_sec_text += text_list[page_i]
|
344 |
+
elif page_i == end_page:
|
345 |
+
if sec_index < len(
|
346 |
+
list(self.section_page_dict.keys())) - 1:
|
347 |
+
next_sec = list(
|
348 |
+
self.section_page_dict.keys())[sec_index +
|
349 |
+
1]
|
350 |
+
if text_list[start_page].find(next_sec) == -1:
|
351 |
+
end_i = text_list[start_page].find(
|
352 |
+
next_sec.upper())
|
353 |
+
else:
|
354 |
+
end_i = text_list[start_page].find(
|
355 |
+
next_sec)
|
356 |
+
cur_sec_text += text_list[page_i][:end_i]
|
357 |
+
section_dict[sec_name] = cur_sec_text.replace('-\n',
|
358 |
+
'').replace(
|
359 |
+
'\n', ' ')
|
360 |
+
return section_dict
|
361 |
+
|
362 |
+
|
363 |
+
# 定义Reader类
|
364 |
+
class Reader:
|
365 |
+
# 初始化方法,设置属性
|
366 |
+
def __init__(self,
|
367 |
+
key_word='',
|
368 |
+
query='',
|
369 |
+
filter_keys='',
|
370 |
+
root_path='./',
|
371 |
+
gitee_key='',
|
372 |
+
sort=arxiv.SortCriterion.SubmittedDate,
|
373 |
+
user_name='defualt',
|
374 |
+
language='cn',
|
375 |
+
api_keys: list = [],
|
376 |
+
model_name="gemini-Pro",
|
377 |
+
p=1.0,
|
378 |
+
temperature=1.0):
|
379 |
+
self.api_keys = api_keys
|
380 |
+
self.chatPaper = chatPaper(api_keys=self.api_keys,
|
381 |
+
apiTimeInterval=10,
|
382 |
+
temperature=temperature,
|
383 |
+
top_p=p,
|
384 |
+
model_name=model_name,
|
385 |
+
proxy=proxy) #openAI api封装
|
386 |
+
self.user_name = user_name # 读者姓名
|
387 |
+
self.key_word = key_word # 读者感兴趣的关键词
|
388 |
+
self.query = query # 读者输入的搜索查询
|
389 |
+
self.sort = sort # 读者选择的排序方式
|
390 |
+
self.language = language # 读者选择的语言
|
391 |
+
self.filter_keys = filter_keys # 用于在摘要中筛选的关键词
|
392 |
+
self.root_path = root_path
|
393 |
+
self.file_format = 'md' # or 'txt',如果为图片,则必须为'md'
|
394 |
+
self.save_image = False
|
395 |
+
if self.save_image:
|
396 |
+
self.gitee_key = self.config.get('Gitee', 'api')
|
397 |
+
else:
|
398 |
+
self.gitee_key = ''
|
399 |
+
self.max_token_num = 4096
|
400 |
+
self.encoding = tiktoken.get_encoding("gpt2")
|
401 |
+
|
402 |
+
def get_arxiv(self, max_results=30):
|
403 |
+
search = arxiv.Search(
|
404 |
+
query=self.query,
|
405 |
+
max_results=max_results,
|
406 |
+
sort_by=self.sort,
|
407 |
+
sort_order=arxiv.SortOrder.Descending,
|
408 |
+
)
|
409 |
+
return search
|
410 |
+
|
411 |
+
def filter_arxiv(self, max_results=30):
|
412 |
+
search = self.get_arxiv(max_results=max_results)
|
413 |
+
print("all search:")
|
414 |
+
for index, result in enumerate(search.results()):
|
415 |
+
print(index, result.title, result.updated)
|
416 |
+
|
417 |
+
filter_results = []
|
418 |
+
filter_keys = self.filter_keys
|
419 |
+
|
420 |
+
print("filter_keys:", self.filter_keys)
|
421 |
+
# 确保每个关键词都能在摘要中找到,才算是目标论文
|
422 |
+
for index, result in enumerate(search.results()):
|
423 |
+
abs_text = result.summary.replace('-\n', '-').replace('\n', ' ')
|
424 |
+
meet_num = 0
|
425 |
+
for f_key in filter_keys.split(" "):
|
426 |
+
if f_key.lower() in abs_text.lower():
|
427 |
+
meet_num += 1
|
428 |
+
if meet_num == len(filter_keys.split(" ")):
|
429 |
+
filter_results.append(result)
|
430 |
+
# break
|
431 |
+
print("filter_results:", len(filter_results))
|
432 |
+
print("filter_papers:")
|
433 |
+
for index, result in enumerate(filter_results):
|
434 |
+
print(index, result.title, result.updated)
|
435 |
+
return filter_results
|
436 |
+
|
437 |
+
def validateTitle(self, title):
|
438 |
+
# 将论文的乱七八糟的路径格式修正
|
439 |
+
rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > |'
|
440 |
+
new_title = re.sub(rstr, "_", title) # 替换为下划线
|
441 |
+
return new_title
|
442 |
+
|
443 |
+
def download_pdf(self, filter_results):
|
444 |
+
# 先创建文件夹
|
445 |
+
date_str = str(datetime.datetime.now())[:13].replace(' ', '-')
|
446 |
+
key_word = str(self.key_word.replace(':', ' '))
|
447 |
+
path = self.root_path + 'pdf_files/' + self.query.replace(
|
448 |
+
'au: ', '').replace('title: ', '').replace('ti: ', '').replace(
|
449 |
+
':', ' ')[:25] + '-' + date_str
|
450 |
+
try:
|
451 |
+
os.makedirs(path)
|
452 |
+
except:
|
453 |
+
pass
|
454 |
+
print("All_paper:", len(filter_results))
|
455 |
+
# 开始下载:
|
456 |
+
paper_list = []
|
457 |
+
for r_index, result in enumerate(filter_results):
|
458 |
+
try:
|
459 |
+
title_str = self.validateTitle(result.title)
|
460 |
+
pdf_name = title_str + '.pdf'
|
461 |
+
# result.download_pdf(path, filename=pdf_name)
|
462 |
+
self.try_download_pdf(result, path, pdf_name)
|
463 |
+
paper_path = os.path.join(path, pdf_name)
|
464 |
+
print("paper_path:", paper_path)
|
465 |
+
paper = Paper(
|
466 |
+
path=paper_path,
|
467 |
+
url=result.entry_id,
|
468 |
+
title=result.title,
|
469 |
+
abs=result.summary.replace('-\n', '-').replace('\n', ' '),
|
470 |
+
authers=[str(aut) for aut in result.authors],
|
471 |
+
)
|
472 |
+
# 下载完毕,开始解析:
|
473 |
+
paper.parse_pdf()
|
474 |
+
paper_list.append(paper)
|
475 |
+
except Exception as e:
|
476 |
+
print("download_error:", e)
|
477 |
+
pass
|
478 |
+
return paper_list
|
479 |
+
|
480 |
+
@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4,
|
481 |
+
max=10),
|
482 |
+
stop=tenacity.stop_after_attempt(5),
|
483 |
+
reraise=True)
|
484 |
+
def try_download_pdf(self, result, path, pdf_name):
|
485 |
+
result.download_pdf(path, filename=pdf_name)
|
486 |
+
|
487 |
+
@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4,
|
488 |
+
max=10),
|
489 |
+
stop=tenacity.stop_after_attempt(5),
|
490 |
+
reraise=True)
|
491 |
+
def upload_gitee(self, image_path, image_name='', ext='png'):
|
492 |
+
"""
|
493 |
+
上传到码云
|
494 |
+
:return:
|
495 |
+
"""
|
496 |
+
with open(image_path, 'rb') as f:
|
497 |
+
base64_data = base64.b64encode(f.read())
|
498 |
+
base64_content = base64_data.decode()
|
499 |
+
|
500 |
+
date_str = str(datetime.datetime.now())[:19].replace(':', '-').replace(
|
501 |
+
' ', '-') + '.' + ext
|
502 |
+
path = image_name + '-' + date_str
|
503 |
+
|
504 |
+
payload = {
|
505 |
+
"access_token": self.gitee_key,
|
506 |
+
"owner": self.config.get('Gitee', 'owner'),
|
507 |
+
"repo": self.config.get('Gitee', 'repo'),
|
508 |
+
"path": self.config.get('Gitee', 'path'),
|
509 |
+
"content": base64_content,
|
510 |
+
"message": "upload image"
|
511 |
+
}
|
512 |
+
# 这里需要修改成你的gitee的账户和仓库名,以及文件夹的名字:
|
513 |
+
url = f'https://gitee.com/api/v5/repos/' + self.config.get(
|
514 |
+
'Gitee', 'owner') + '/' + self.config.get(
|
515 |
+
'Gitee', 'repo') + '/contents/' + self.config.get(
|
516 |
+
'Gitee', 'path') + '/' + path
|
517 |
+
rep = requests.post(url, json=payload).json()
|
518 |
+
print("rep:", rep)
|
519 |
+
if 'content' in rep.keys():
|
520 |
+
image_url = rep['content']['download_url']
|
521 |
+
else:
|
522 |
+
image_url = r"https://gitee.com/api/v5/repos/" + self.config.get(
|
523 |
+
'Gitee', 'owner') + '/' + self.config.get(
|
524 |
+
'Gitee', 'repo') + '/contents/' + self.config.get(
|
525 |
+
'Gitee', 'path') + '/' + path
|
526 |
+
|
527 |
+
return image_url
|
528 |
+
|
529 |
+
|
530 |
+
def summary_with_chat(self, paper_list):
|
531 |
+
htmls = []
|
532 |
+
utoken = 0
|
533 |
+
ctoken = 0
|
534 |
+
ttoken = 0
|
535 |
+
for paper_index, paper in enumerate(paper_list):
|
536 |
+
# 第一步先用title,abs,和introduction进行总结。
|
537 |
+
text = ''
|
538 |
+
text += 'Title:' + paper.title
|
539 |
+
text += 'Url:' + paper.url
|
540 |
+
text += 'Abstrat:' + paper.abs
|
541 |
+
text += 'Paper_info:' + paper.section_text_dict['paper_info']
|
542 |
+
# intro
|
543 |
+
text += list(paper.section_text_dict.values())[0]
|
544 |
+
#max_token = 2500 * 4
|
545 |
+
#text = text[:max_token]
|
546 |
+
chat_summary_text, utoken1, ctoken1, ttoken1 = self.chat_summary(
|
547 |
+
text=text)
|
548 |
+
htmls.append(chat_summary_text)
|
549 |
+
|
550 |
+
# TODO 往md文档中插入论文里的像素最大的一张图片,这个方案可以弄的更加智能一些:
|
551 |
+
method_key = ''
|
552 |
+
for parse_key in paper.section_text_dict.keys():
|
553 |
+
if 'method' in parse_key.lower(
|
554 |
+
) or 'approach' in parse_key.lower():
|
555 |
+
method_key = parse_key
|
556 |
+
break
|
557 |
+
|
558 |
+
if method_key != '':
|
559 |
+
text = ''
|
560 |
+
method_text = ''
|
561 |
+
summary_text = ''
|
562 |
+
summary_text += "<summary>" + chat_summary_text
|
563 |
+
# methods
|
564 |
+
method_text += paper.section_text_dict[method_key]
|
565 |
+
text = summary_text + "\n<Methods>:\n" + method_text
|
566 |
+
chat_method_text, utoken2, ctoken2, ttoken2 = self.chat_method(
|
567 |
+
text=text)
|
568 |
+
else:
|
569 |
+
chat_method_text = ''
|
570 |
+
htmls.append(chat_method_text)
|
571 |
+
htmls.append("\n")
|
572 |
+
|
573 |
+
# 第三步总结全文,并打分:
|
574 |
+
conclusion_key = ''
|
575 |
+
for parse_key in paper.section_text_dict.keys():
|
576 |
+
if 'conclu' in parse_key.lower():
|
577 |
+
conclusion_key = parse_key
|
578 |
+
break
|
579 |
+
|
580 |
+
text = ''
|
581 |
+
conclusion_text = ''
|
582 |
+
summary_text = ''
|
583 |
+
summary_text += "<summary>" + chat_summary_text + "\n <Method summary>:\n" + chat_method_text
|
584 |
+
if conclusion_key != '':
|
585 |
+
# conclusion
|
586 |
+
conclusion_text += paper.section_text_dict[conclusion_key]
|
587 |
+
text = summary_text + "\n <Conclusion>:\n" + conclusion_text
|
588 |
+
else:
|
589 |
+
text = summary_text
|
590 |
+
chat_conclusion_text, utoken3, ctoken3, ttoken3 = self.chat_conclusion(
|
591 |
+
text=text)
|
592 |
+
htmls.append(chat_conclusion_text)
|
593 |
+
htmls.append("\n")
|
594 |
+
# token统计
|
595 |
+
utoken = utoken + utoken1 + utoken2 + utoken3
|
596 |
+
ctoken = ctoken + ctoken1 + ctoken2 + ctoken3
|
597 |
+
ttoken = ttoken + ttoken1 + ttoken2 + ttoken3
|
598 |
+
cost = (ttoken / 1000) * 0.002
|
599 |
+
pos_count = {
|
600 |
+
"usage_token_used": str(utoken),
|
601 |
+
"completion_token_used": str(ctoken),
|
602 |
+
"total_token_used": str(ttoken),
|
603 |
+
"cost": str(cost),
|
604 |
+
}
|
605 |
+
md_text = "\n\n".join(htmls)
|
606 |
+
|
607 |
+
with open(os.path.join('./', 'output.md'), "w", encoding="utf8") as f:
|
608 |
+
f.write(md_text)
|
609 |
+
return mistune.markdown(md_text), pos_count
|
610 |
+
return markdown.markdown(md_text), pos_count # , os.path.join('./', 'output.md')
|
611 |
+
|
612 |
+
@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4,
|
613 |
+
max=10),
|
614 |
+
stop=tenacity.stop_after_attempt(5),
|
615 |
+
reraise=True)
|
616 |
+
def chat_conclusion(self, text):
|
617 |
+
conclusion_prompt_token = 650
|
618 |
+
text_token = len(self.encoding.encode(text))
|
619 |
+
clip_text_index = int(
|
620 |
+
len(text) * (self.max_token_num - conclusion_prompt_token) /
|
621 |
+
text_token)
|
622 |
+
clip_text = text[:clip_text_index]
|
623 |
+
self.chatPaper.reset(
|
624 |
+
convo_id="chatConclusion",
|
625 |
+
system_prompt="You are a reviewer in the field of [" +
|
626 |
+
self.key_word + "] and you need to critically review this article")
|
627 |
+
self.chatPaper.add_to_conversation_last(
|
628 |
+
convo_id="chatConclusion",
|
629 |
+
role="user",
|
630 |
+
message=
|
631 |
+
"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:"
|
632 |
+
+ clip_text) # 背景知识,可以参考OpenReview的审稿流程
|
633 |
+
content = """
|
634 |
+
8. Make the following summary.Be sure to use Chinese answers (proper nouns need to be marked in English).
|
635 |
+
(1):What is the significance of this piece of work?
|
636 |
+
(2):Summarize the strengths and weaknesses of this article in three dimensions: innovation point, performance, and workload.
|
637 |
+
.......
|
638 |
+
Follow the format of the output later:
|
639 |
+
8. Conclusion: \n\n
|
640 |
+
(1):xxx;\n
|
641 |
+
(2):Innovation point: xxx; Performance: xxx; Workload: xxx;\n
|
642 |
+
|
643 |
+
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.
|
644 |
+
"""
|
645 |
+
result = self.chatPaper.ask(
|
646 |
+
prompt=content,
|
647 |
+
role="user",
|
648 |
+
convo_id="chatConclusion",
|
649 |
+
)
|
650 |
+
print(result)
|
651 |
+
return result[0], result[1], result[2], result[3]
|
652 |
+
|
653 |
+
@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4,
|
654 |
+
max=10),
|
655 |
+
stop=tenacity.stop_after_attempt(5),
|
656 |
+
reraise=True)
|
657 |
+
def chat_method(self, text):
|
658 |
+
method_prompt_token = 650
|
659 |
+
text_token = len(self.encoding.encode(text))
|
660 |
+
clip_text_index = int(
|
661 |
+
len(text) * (self.max_token_num - method_prompt_token) /
|
662 |
+
text_token)
|
663 |
+
clip_text = text[:clip_text_index]
|
664 |
+
self.chatPaper.reset(
|
665 |
+
convo_id="chatMethod",
|
666 |
+
system_prompt="You are a researcher in the field of [" +
|
667 |
+
self.key_word +
|
668 |
+
"] who is good at summarizing papers using concise statements"
|
669 |
+
) # chatgpt 角色
|
670 |
+
self.chatPaper.add_to_conversation_last(
|
671 |
+
convo_id="chatMethod",
|
672 |
+
role="user",
|
673 |
+
message=str(
|
674 |
+
"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."
|
675 |
+
+ clip_text))
|
676 |
+
content = """
|
677 |
+
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.
|
678 |
+
(1):...
|
679 |
+
(2):...
|
680 |
+
(3):...
|
681 |
+
.......
|
682 |
+
Follow the format of the output that follows:
|
683 |
+
7. Methods: \n\n
|
684 |
+
(1):xxx;\n
|
685 |
+
(2):xxx;\n
|
686 |
+
(3):xxx;\n
|
687 |
+
....... \n\n
|
688 |
+
\n\n
|
689 |
+
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.
|
690 |
+
"""
|
691 |
+
result = self.chatPaper.ask(
|
692 |
+
prompt=content,
|
693 |
+
role="user",
|
694 |
+
convo_id="chatMethod",
|
695 |
+
)
|
696 |
+
print(result)
|
697 |
+
return result[0], result[1], result[2], result[3]
|
698 |
+
|
699 |
+
@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, min=4,
|
700 |
+
max=10),
|
701 |
+
stop=tenacity.stop_after_attempt(5),
|
702 |
+
reraise=True)
|
703 |
+
def chat_summary(self, text):
|
704 |
+
summary_prompt_token = 1000
|
705 |
+
text_token = len(self.encoding.encode(text))
|
706 |
+
clip_text_index = int(
|
707 |
+
len(text) * (self.max_token_num - summary_prompt_token) /
|
708 |
+
text_token)
|
709 |
+
clip_text = text[:clip_text_index]
|
710 |
+
# 重新设定GPT 角色
|
711 |
+
self.chatPaper.reset(
|
712 |
+
convo_id="chatSummary",
|
713 |
+
system_prompt="You are a researcher in the field of [" +
|
714 |
+
self.key_word +
|
715 |
+
"] who is good at summarizing papers using concise statements")
|
716 |
+
# 提交summary prompt
|
717 |
+
self.chatPaper.add_to_conversation_last(
|
718 |
+
convo_id="chatSummary",
|
719 |
+
role="user",
|
720 |
+
message=str(
|
721 |
+
"This is the title, author, link, abstract and introduction of an English document. I need your help to read and summarize the following questions: "
|
722 |
+
+ clip_text))
|
723 |
+
content = """
|
724 |
+
1. Mark the title of the paper (with Chinese translation)
|
725 |
+
2. list all the authors' names (use English)
|
726 |
+
3. mark the first author's affiliation (output Chinese translation only)
|
727 |
+
4. mark the keywords of this article (use English)
|
728 |
+
5. link to the paper, Github code link (if available, fill in Github:None if not)
|
729 |
+
6. summarize according to the following four points.Be sure to use Chinese answers (proper nouns need to be marked in English)
|
730 |
+
(1):What is the research background of this article?
|
731 |
+
(2):What are the past methods? What are the problems with them? Is the approach well motivated?
|
732 |
+
(3):What is the research methodology proposed in this paper?
|
733 |
+
(4):On what task and what performance is achieved by the methods in this paper? Can the performance support their goals?
|
734 |
+
Follow the format of the output that follows:
|
735 |
+
1. Title: xxx\n\n
|
736 |
+
2. Authors: xxx\n\n
|
737 |
+
3. Affiliation: xxx\n\n
|
738 |
+
4. Keywords: xxx\n\n
|
739 |
+
5. Urls: xxx or xxx , xxx \n\n
|
740 |
+
6. Summary: \n\n
|
741 |
+
(1):xxx;\n
|
742 |
+
(2):xxx;\n
|
743 |
+
(3):xxx;\n
|
744 |
+
(4):xxx.\n\n
|
745 |
+
|
746 |
+
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.
|
747 |
+
"""
|
748 |
+
# 提出对应的问题
|
749 |
+
result = self.chatPaper.ask(
|
750 |
+
prompt=content,
|
751 |
+
role="user",
|
752 |
+
convo_id="chatSummary",
|
753 |
+
)
|
754 |
+
print(result)
|
755 |
+
return result[0], result[1], result[2], result[3]
|
756 |
+
|
757 |
+
def export_to_markdown(self, text, file_name, mode='w'):
|
758 |
+
# 使用markdown模块的convert方法,将文本转换为html格式
|
759 |
+
# html = markdown.markdown(text)
|
760 |
+
# 打开一个文件,以写入模式
|
761 |
+
with open(file_name, mode, encoding="utf-8") as f:
|
762 |
+
# 将html格式的内容写入文件
|
763 |
+
f.write(text)
|
764 |
+
|
765 |
+
# 定义一个方法,打印出读者信息
|
766 |
+
def show_info(self):
|
767 |
+
print(f"Key word: {self.key_word}")
|
768 |
+
print(f"Query: {self.query}")
|
769 |
+
print(f"Sort: {self.sort}")
|
770 |
+
|
771 |
+
|
772 |
+
def upload_pdf(api_keys, text, model_name, p, temperature, file):
|
773 |
+
# 检查两个输入都不为空
|
774 |
+
api_key_list = None
|
775 |
+
if api_keys:
|
776 |
+
api_key_list = api_keys.split(',')
|
777 |
+
elif not api_keys and valid_api_keys != []:
|
778 |
+
api_key_list = valid_api_keys
|
779 |
+
if not text or not file or not api_key_list:
|
780 |
+
return "两个输入都不能为空,请输入字符并上传 PDF 文件!"
|
781 |
+
|
782 |
+
# 判断PDF文件
|
783 |
+
#if file and file.name.split(".")[-1].lower() != "pdf":
|
784 |
+
# return '请勿上传非 PDF 文件!'
|
785 |
+
else:
|
786 |
+
section_list = text.split(',')
|
787 |
+
paper_list = [Paper(path=file, sl=section_list)]
|
788 |
+
# 创建一个Reader对象
|
789 |
+
print(api_key_list)
|
790 |
+
reader = Reader(api_keys=api_key_list,
|
791 |
+
model_name=model_name,
|
792 |
+
p=p,
|
793 |
+
temperature=temperature)
|
794 |
+
sum_info, cost = reader.summary_with_chat(
|
795 |
+
paper_list=paper_list) # type: ignore
|
796 |
+
return cost, sum_info
|
797 |
+
|
798 |
+
|
799 |
+
api_title = "api-key可用验证(Gemini Pro)"
|
800 |
+
api_description = '''<div align='left'>
|
801 |
+
|
802 |
+
使用 Google 的 GeminiPro 进行论文摘要生成,灵感来源于 ChatPaper 项目。
|
803 |
+
|
804 |
+
💥💥💥<strong>面向全球,服务万千科研人的ChatPaper在线版正式上线:<a href="https://chatpaper.org/">https://chatpaper.org/</a> </strong>💥💥💥
|
805 |
+
|
806 |
+
Use ChatGPT to summary the papers.Star our Github [🌟ChatPaper](https://github.com/kaixindelele/ChatPaper) .
|
807 |
+
|
808 |
+
基于此,修改部分为Gemini Pro来进行论文摘要,并且这一部分是免费的,只要获取API key即可,也请多多关注
|
809 |
+
|
810 |
+
Use Gemini Pro to summary the papers.Star our Github [🌟ChatPaperFree](https://github.com/Kedreamix/ChatPaperFree) .
|
811 |
+
|
812 |
+
另外,请多多关注 [进步屋](https://ipaper.today/),我们会根据关键词,每天更新最新的arixv论文,follow最新的研究方向,并且使用GPT进行总结,帮助你更好的读论文
|
813 |
+
|
814 |
+
💗如果您觉得我们的项目对您有帮助,还请您给我们一些鼓励!💗
|
815 |
+
|
816 |
+
🔴请注意:千万不要用于严肃的学术场景,只能用于论文阅读前的初筛!
|
817 |
+
|
818 |
+
|
819 |
+
</div>
|
820 |
+
'''
|
821 |
+
|
822 |
+
api_input = [
|
823 |
+
gradio.inputs.Textbox(label="请输入你的API-key(必填, 多个API-key请用英文逗号隔开)",
|
824 |
+
default="",
|
825 |
+
type='password')
|
826 |
+
]
|
827 |
+
api_gui = gradio.Interface(fn=valid_apikey,
|
828 |
+
inputs=api_input,
|
829 |
+
outputs="text",
|
830 |
+
title=api_title,
|
831 |
+
description=api_description)
|
832 |
+
|
833 |
+
# 标题
|
834 |
+
title = "ChatPaper(Gemini Pro)"
|
835 |
+
# 描述
|
836 |
+
description = api_description = '''<div align='left'>
|
837 |
+
|
838 |
+
使用 Google 的 GeminiPro 进行论文摘要生成,灵感来源于 ChatPaper 项目。
|
839 |
+
|
840 |
+
💥💥💥<strong>面向全球,服务万千科研人的ChatPaper在线版正式上线:<a href="https://chatpaper.org/">https://chatpaper.org/</a> </strong>💥💥💥
|
841 |
+
|
842 |
+
Use ChatGPT to summary the papers.Star our Github [🌟ChatPaper](https://github.com/kaixindelele/ChatPaper) .
|
843 |
+
|
844 |
+
基于此,修改部分为Gemini Pro来进行论文摘要,并且这一部分是免费的,只要获取API key即可,也请多多关注
|
845 |
+
|
846 |
+
Use Gemini Pro to summary the papers.Star our Github [🌟ChatPaperFree](https://github.com/Kedreamix/ChatPaperFree) .
|
847 |
+
|
848 |
+
另外,请多多关注 [进步屋](https://ipaper.today/),我们会根据关键词,每天更新最新的arixv论文,follow最新的研究方向,并且使用GPT进行总结,帮助你更好的读论文
|
849 |
+
|
850 |
+
💗如果您觉得我们的项目对您有帮助,还请您给我们一些鼓励!💗
|
851 |
+
|
852 |
+
🔴请注意:千万不要用于严肃的学术场景,只能用于论文阅读前的初筛!
|
853 |
+
|
854 |
+
|
855 |
+
</div>
|
856 |
+
'''
|
857 |
+
# 创建Gradio界面
|
858 |
+
ip = [
|
859 |
+
gradio.inputs.Textbox(label="请输入你的API-key(必填, 多个API-key请用英文逗号隔开),不需要空格",
|
860 |
+
default="",
|
861 |
+
type='password'),
|
862 |
+
gradio.inputs.Textbox(
|
863 |
+
label="请输入论文大标题索引(用英文逗号隔开,必填)",
|
864 |
+
default=
|
865 |
+
"'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'"
|
866 |
+
),
|
867 |
+
gradio.inputs.Radio(choices=["gemini-Pro", "gemini-Pro-vision(comming Soon)"],
|
868 |
+
default="gemini-Pro",
|
869 |
+
label="Select model"),
|
870 |
+
gradio.inputs.Slider(minimum=-0,
|
871 |
+
maximum=1.0,
|
872 |
+
default=1.0,
|
873 |
+
step=0.05,
|
874 |
+
label="Top-p (nucleus sampling)"),
|
875 |
+
gradio.inputs.Slider(minimum=-0,
|
876 |
+
maximum=5.0,
|
877 |
+
default=0.5,
|
878 |
+
step=0.5,
|
879 |
+
label="Temperature"),
|
880 |
+
gradio.inputs.File(label="请上传论文PDF(必填)")
|
881 |
+
]
|
882 |
+
|
883 |
+
chatpaper_gui = gradio.Interface(fn=upload_pdf,
|
884 |
+
inputs=ip,
|
885 |
+
outputs=["json", "html"],
|
886 |
+
title=title,
|
887 |
+
description=description)
|
888 |
+
|
889 |
+
# Start server
|
890 |
+
gui = gradio.TabbedInterface(interface_list=[api_gui, chatpaper_gui],
|
891 |
+
tab_names=["API-key", "ChatPaper"])
|
892 |
+
gui.launch(quiet=True, show_api=False, debug=True)
|
optimizeGoogle.py
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
A simple wrapper for the official Google GeminiPro 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 |
+
import google.generativeai as genai
|
16 |
+
ENCODER = tiktoken.get_encoding("gpt2")
|
17 |
+
class chatPaper:
|
18 |
+
"""
|
19 |
+
Official Google API
|
20 |
+
"""
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
api_keys: list,
|
24 |
+
proxy = None,
|
25 |
+
api_proxy = None,
|
26 |
+
max_tokens: int = 4000,
|
27 |
+
temperature: float = 0.5,
|
28 |
+
top_p: float = 1.0,
|
29 |
+
model_name: str = "gemini-Pro",
|
30 |
+
reply_count: int = 1,
|
31 |
+
system_prompt = "You are ChatPaper, A paper reading bot",
|
32 |
+
lastAPICallTime = time.time()-100,
|
33 |
+
apiTimeInterval = 20,
|
34 |
+
) -> None:
|
35 |
+
self.model_name = model_name
|
36 |
+
self.system_prompt = system_prompt
|
37 |
+
self.apiTimeInterval = apiTimeInterval
|
38 |
+
self.session = requests.Session()
|
39 |
+
self.api_keys = PQ()
|
40 |
+
for key in api_keys:
|
41 |
+
self.api_keys.put((lastAPICallTime,key))
|
42 |
+
self.proxy = proxy
|
43 |
+
if self.proxy:
|
44 |
+
proxies = {
|
45 |
+
"http": self.proxy['http'],
|
46 |
+
"https": self.proxy['https'],
|
47 |
+
}
|
48 |
+
os.environ["http_proxy"] = self.proxy['http']
|
49 |
+
os.environ["https_proxy"] = self.proxy['https']
|
50 |
+
self.session.proxies = proxies
|
51 |
+
self.max_tokens = max_tokens
|
52 |
+
self.temperature = temperature
|
53 |
+
self.top_p = top_p
|
54 |
+
self.reply_count = reply_count
|
55 |
+
self.decrease_step = 250
|
56 |
+
self.conversation = {}
|
57 |
+
if self.token_str(self.system_prompt) > self.max_tokens:
|
58 |
+
raise Exception("System prompt is too long")
|
59 |
+
self.lock = threading.Lock()
|
60 |
+
|
61 |
+
def get_api_key(self):
|
62 |
+
with self.lock:
|
63 |
+
apiKey = self.api_keys.get()
|
64 |
+
delay = self._calculate_delay(apiKey)
|
65 |
+
time.sleep(delay)
|
66 |
+
self.api_keys.put((time.time(), apiKey[1]))
|
67 |
+
return apiKey[1]
|
68 |
+
|
69 |
+
def _calculate_delay(self, apiKey):
|
70 |
+
elapsed_time = time.time() - apiKey[0]
|
71 |
+
if elapsed_time < self.apiTimeInterval:
|
72 |
+
return self.apiTimeInterval - elapsed_time
|
73 |
+
else:
|
74 |
+
return 0
|
75 |
+
|
76 |
+
def add_to_conversation(self, message: str, role: str, convo_id: str = "default"):
|
77 |
+
if(convo_id not in self.conversation):
|
78 |
+
self.reset(convo_id)
|
79 |
+
self.conversation[convo_id].append({"role": role, "parts": [message]})
|
80 |
+
|
81 |
+
def add_to_conversation_last(self, message: str, role: str, convo_id: str = "default"):
|
82 |
+
if(convo_id not in self.conversation):
|
83 |
+
self.reset(convo_id)
|
84 |
+
self.conversation[convo_id][-1]["parts"] += message
|
85 |
+
|
86 |
+
def __truncate_conversation(self, convo_id: str = "default"):
|
87 |
+
"""
|
88 |
+
Truncate the conversation
|
89 |
+
"""
|
90 |
+
last_dialog = self.conversation[convo_id][-1]
|
91 |
+
query = str(last_dialog['parts'][0])
|
92 |
+
if(len(ENCODER.encode(str(query)))>self.max_tokens):
|
93 |
+
query = query[:int(1.5*self.max_tokens)]
|
94 |
+
while(len(ENCODER.encode(str(query)))>self.max_tokens):
|
95 |
+
query = query[:self.decrease_step]
|
96 |
+
self.conversation[convo_id] = self.conversation[convo_id][:-1]
|
97 |
+
# print(self.conversation)
|
98 |
+
full_conversation = "\n".join([str(x["parts"][0]) for x in self.conversation[convo_id]],)
|
99 |
+
if len(ENCODER.encode(full_conversation)) > self.max_tokens:
|
100 |
+
self.conversation_summary(convo_id=convo_id)
|
101 |
+
full_conversation = ""
|
102 |
+
for x in self.conversation[convo_id]:
|
103 |
+
full_conversation = str(x["parts"][0]) + "\n" + full_conversation
|
104 |
+
while True:
|
105 |
+
if (len(ENCODER.encode(full_conversation+query)) > self.max_tokens):
|
106 |
+
query = query[:self.decrease_step]
|
107 |
+
else:
|
108 |
+
break
|
109 |
+
# print(last_dialog)
|
110 |
+
last_dialog['parts'][0] = str(query)
|
111 |
+
self.conversation[convo_id].append(last_dialog)
|
112 |
+
|
113 |
+
def ask_stream(
|
114 |
+
self,
|
115 |
+
prompt: str,
|
116 |
+
role: str = "user",
|
117 |
+
convo_id: str = "default",
|
118 |
+
**kwargs,
|
119 |
+
) -> Generator:
|
120 |
+
if convo_id not in self.conversation:
|
121 |
+
self.reset(convo_id=convo_id)
|
122 |
+
self.add_to_conversation_last(prompt, "user", convo_id=convo_id)
|
123 |
+
self.__truncate_conversation(convo_id=convo_id)
|
124 |
+
|
125 |
+
genai.configure(api_key=self.get_api_key())
|
126 |
+
|
127 |
+
model = genai.GenerativeModel('gemini-pro')
|
128 |
+
|
129 |
+
response = model.generate_content(self.conversation[convo_id],
|
130 |
+
generation_config=genai.types.GenerationConfig(
|
131 |
+
# Only one candidate for now.
|
132 |
+
candidate_count=kwargs.get("n", self.reply_count),
|
133 |
+
# stop_sequences=['x'],
|
134 |
+
max_output_tokens=self.max_tokens,
|
135 |
+
temperature=kwargs.get("temperature", self.temperature)),
|
136 |
+
stream = True)
|
137 |
+
# try:
|
138 |
+
# response.text
|
139 |
+
# except Exception as e:
|
140 |
+
# print(f"Exception: {e}")
|
141 |
+
# raise Exception(
|
142 |
+
# f"Gemini Error",
|
143 |
+
# )
|
144 |
+
|
145 |
+
for line in response:
|
146 |
+
yield line.text
|
147 |
+
|
148 |
+
def ask(self, prompt: str, role: str = "user", convo_id: str = "default", **kwargs):
|
149 |
+
"""
|
150 |
+
Non-streaming ask
|
151 |
+
"""
|
152 |
+
response = self.ask_stream(
|
153 |
+
prompt=prompt,
|
154 |
+
role=role,
|
155 |
+
convo_id=convo_id,
|
156 |
+
**kwargs,
|
157 |
+
)
|
158 |
+
full_response: str = "".join(response)
|
159 |
+
self.add_to_conversation(full_response, role, convo_id=convo_id)
|
160 |
+
usage_token = self.token_str(prompt)
|
161 |
+
com_token = self.token_str(full_response)
|
162 |
+
total_token = self.token_cost(convo_id=convo_id)
|
163 |
+
return full_response, usage_token, com_token, total_token
|
164 |
+
|
165 |
+
def check_api_available(self):
|
166 |
+
url = f"https://generativelanguage.googleapis.com/v1beta3/models/text-bison-001:generateText?key={self.get_api_key()}"
|
167 |
+
|
168 |
+
headers = {
|
169 |
+
'Content-Type': 'application/json',
|
170 |
+
}
|
171 |
+
|
172 |
+
data = {
|
173 |
+
'prompt': {
|
174 |
+
'text': "hello",
|
175 |
+
},
|
176 |
+
}
|
177 |
+
|
178 |
+
response = requests.post(url, headers=headers, json=data)
|
179 |
+
|
180 |
+
if response.status_code == 200:
|
181 |
+
print(response)
|
182 |
+
else:
|
183 |
+
print(False)
|
184 |
+
if response.status_code == 200:
|
185 |
+
return True
|
186 |
+
else:
|
187 |
+
return False
|
188 |
+
|
189 |
+
def reset(self, convo_id: str = "default", system_prompt = None):
|
190 |
+
"""
|
191 |
+
Reset the conversation
|
192 |
+
"""
|
193 |
+
self.conversation[convo_id] = [
|
194 |
+
{"role": "user", "parts": [str(system_prompt or self.system_prompt)]},
|
195 |
+
]
|
196 |
+
|
197 |
+
def conversation_summary(self, convo_id: str = "default"):
|
198 |
+
input = ""
|
199 |
+
role = ""
|
200 |
+
for conv in self.conversation[convo_id]:
|
201 |
+
if (conv["role"]=='user'):
|
202 |
+
role = 'User'
|
203 |
+
else:
|
204 |
+
role = 'Gemini'
|
205 |
+
input+=role+' : '+conv['content']+'\n'
|
206 |
+
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."
|
207 |
+
if(self.token_str(str(input)+prompt)>self.max_tokens):
|
208 |
+
input = input[self.token_str(str(input))-self.max_tokens:]
|
209 |
+
while self.token_str(str(input)+prompt)>self.max_tokens:
|
210 |
+
input = input[self.decrease_step:]
|
211 |
+
prompt = prompt.replace("{conversation}", input)
|
212 |
+
self.reset(convo_id='conversationSummary')
|
213 |
+
response = self.ask(prompt,convo_id='conversationSummary')
|
214 |
+
while self.token_str(str(response))>self.max_tokens:
|
215 |
+
response = response[:-self.decrease_step]
|
216 |
+
self.reset(convo_id='conversationSummary',system_prompt='Summariaze our diaglog')
|
217 |
+
self.conversation[convo_id] = [
|
218 |
+
{"role": "user", "parts": [self.system_prompt]},
|
219 |
+
{"role": "user", "parts": ["Summariaze our diaglog"]},
|
220 |
+
{"role": 'model', "parts": [response]},
|
221 |
+
]
|
222 |
+
return self.conversation[convo_id]
|
223 |
+
def token_cost(self,convo_id: str = "default"):
|
224 |
+
return len(ENCODER.encode("\n".join([x["parts"][0] for x in self.conversation[convo_id]])))
|
225 |
+
def token_str(self,content:str):
|
226 |
+
return len(ENCODER.encode(content))
|
227 |
+
def main():
|
228 |
+
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
|