Compare commits

..

1 Commits

Author SHA1 Message Date
liuweiqing
34e6e97b57 chore: release 1.5.1 2024-02-14 16:55:12 +08:00
79 changed files with 1051 additions and 4249 deletions

View File

@ -1,18 +0,0 @@
# Update these with your Supabase details from your project settings > API
# https://app.supabase.com/project/_/settings/api
NEXT_PUBLIC_SUPABASE_URL=https://yidfukfbrluizjvfrrsj.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlpZGZ1a2Zicmx1aXpqdmZycnNqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDQ4NjMyNjEsImV4cCI6MjAyMDQzOTI2MX0.EXIXAdNIGLFo5wHmwmY2-9bqLO9vyFYDvMMtCtkxgig
# NEXT_PUBLIC_TINYMCE_API_KEY=e983nu390inks6be1wwlsrdxjebot3yc4pld7d44zs6vcrxr
NEXT_PUBLIC_OPENAI_API_KEY=sk-ffe19ebe9fa44d00884330ff1c18cf82
#sess-wZKsUKS8IhPH3jI44krQL41vhl68qH6hwE66hOnL
NEXT_PUBLIC_SEMANTIC_API_KEY=hEQvK6ARe84dzDPcMnpzX4n9jfoqztkMfaftPWnb
NEXT_PUBLIC_PUBMED_API_KEY=057616e7ce6c722f2ae8679e38a8be9b1a09
NEXT_PUBLIC_AI_URL=https://api.deepseek.com # /api/v1/chat/completions
NEXT_PUBLIC_PAPER_URL=/api/paper
#"https://api.openai.com/v1/chat/completions" "https://api.liuweiqing.top" "https://api.liuweiqing.top/v1/chat/completions"
#node转发设置为 /api/v1/chat/completions https://one.caifree.com sk-aiHrrRLYUUelHstX69E9484509254dBf92061d6744FfFaD1
VERCEL_URL=https://www.paperai.life
NODE_ENV=development
# NEXT_PUBLIC_CLIENT_ID=UrgIEI0n03tveTmaOV0IU8qRY4DttGY4
# CLIENT_SECRET=ljShbIlIrfULu4BTUVTT4azeR90PtAif
# REDIRECT_URI=http://localhost:3000/api/oauth/callback

View File

@ -6,7 +6,3 @@ NEXT_PUBLIC_PAPER_URL=/api/paper
NEXT_PUBLIC_SEMANTIC_API_KEY=hEQvK6ARe84dzDPcMnpzX4n9jfoqztkMfaftPWnb
NEXT_PUBLIC_PUBMED_API_KEY=057616e7ce6c722f2ae8679e38a8be9b1a09
VERCEL_URL=https://www.paperai.life
NODE_ENV=production
NEXT_PUBLIC_CLIENT_ID=RcgInz3KqEhb2KdW2yg5WUgAf3KHcJAC
CLIENT_SECRET=U4z8TgPIV1GWCXhFFNEVQyfmDotf91K6
REDIRECT_URI=https://www.paperai.life/api/oauth/callback

View File

@ -1,40 +0,0 @@
name: Upstream Sync
permissions:
contents: write
on:
schedule:
- cron: "0 0 * * *" # every day
workflow_dispatch:
jobs:
sync_latest_from_upstream:
name: Sync latest commits from upstream repo
runs-on: ubuntu-latest
if: ${{ github.event.repository.fork }}
steps:
# Step 1: run a standard checkout action
- name: Checkout target repo
uses: actions/checkout@v3
# Step 2: run the sync action
- name: Sync upstream changes
id: sync
uses: aormsby/Fork-Sync-With-Upstream-action@v3.4
with:
upstream_sync_repo: 14790897/paper-ai
upstream_sync_branch: main
target_sync_branch: main
target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
# Set test_mode true to run tests instead of the true action!!
test_mode: false
- name: Sync check
if: failure()
run: |
echo "[Error] 由于上游仓库的 workflow 文件变更,导致 GitHub 自动暂停了本次自动更新,你需要手动 Sync Fork 一次详细教程请查看https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/README_CN.md#%E6%89%93%E5%BC%80%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0"
echo "[Error] Due to a change in the workflow file of the upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork. Please refer to the detailed tutorial for instructions: https://github.com/Yidadaa/ChatGPT-Next-Web#enable-automatic-updates"
exit 1

11
.gitignore vendored
View File

@ -26,7 +26,7 @@ yarn-debug.log*
yarn-error.log*
# local env files
# .env*.local
.env*.local
# vercel
.vercel
@ -37,18 +37,9 @@ next-env.d.ts
pass
.env
# .env.local
.vercel
post.md
# Sentry Config File
.sentryclirc
#vitepress
docs/.vitepress/dist/*
node_modules
dist
cache
# Sentry Config File
.sentryclirc

View File

@ -1,85 +1,11 @@
# Changelog
## [1.9.0](https://www.github.com/14790897/paper-ai/compare/v1.8.0...v1.9.0) (2024-03-13)
### Features
* google登录 ([15c3a1f](https://www.github.com/14790897/paper-ai/commit/15c3a1f0acae8f5d6e610382b4fb886cc637d4f9))
* 允许重置密码 ([939f5c2](https://www.github.com/14790897/paper-ai/commit/939f5c28e9f658f2899cb262c16e78d42601a320))
* 可以手动停止AI的输出(左下角按钮) ([a72329d](https://www.github.com/14790897/paper-ai/commit/a72329d4a209aba4a0111093ece3b8cf89113ad2))
* 完成linuxdo oauth ([0090ffd](https://www.github.com/14790897/paper-ai/commit/0090ffd3bbe83a99a4de15e733619569cd78a69b))
### [1.5.1](https://www.github.com/14790897/paper-ai/compare/v1.5.0...v1.5.1) (2024-02-14)
### Bug Fixes
* GitHub登入可以插入信息 ([559b401](https://www.github.com/14790897/paper-ai/commit/559b4010c276f45dec791aaea17133d6690aac63))
* github登录无法将用户数据插入数据库 ([65db119](https://www.github.com/14790897/paper-ai/commit/65db119a9ac97009f15238e6ef26236bc6be14c7))
* quilleditor ssr加载失败 ([8a25248](https://www.github.com/14790897/paper-ai/commit/8a25248c29c578c75ec9e05fd1cdd339f131e5d6))
* remove .env.local ([0bfaacf](https://www.github.com/14790897/paper-ai/commit/0bfaacf6ee52309aaa55961037aba29a1558e6a6))
* remove freshwork ([f8e4cfd](https://www.github.com/14790897/paper-ai/commit/f8e4cfd205cfb5b5ec105f662c0ff0b6d8590429))
* seo ([72300bf](https://www.github.com/14790897/paper-ai/commit/72300bf6eb23757845734ccfcfb99d40274c9257))
* seo图片问题 ([6e807a7](https://www.github.com/14790897/paper-ai/commit/6e807a703d2a72f6ce557f043abefc44d746992c))
* 使用cf反代解决semantic cors问题 ([836aa49](https://www.github.com/14790897/paper-ai/commit/836aa49847ec7bc4fd2686a324a82ab19173fc83))
* 前端环境变量需要使用NEXT_PUBLIC_ ([6243aa5](https://www.github.com/14790897/paper-ai/commit/6243aa5401f7689aa7e4caf81a39a87578484299))
* 应用id问题 ([64cab48](https://www.github.com/14790897/paper-ai/commit/64cab48ae34ebb5500553dd3908167a95f1cbaf4))
* 新用户没有获得编辑器焦点会导致报错 ([4b64827](https://www.github.com/14790897/paper-ai/commit/4b64827c1d3c77dc05ebad359f0f4d384145211f))
* 点击空白页面可以可以取消论文列表页 ([b5bd878](https://www.github.com/14790897/paper-ai/commit/b5bd878cdafb6a54826f8aeafb16e6e6bc1e95bb))
* 读取ai响应 ([e7aa998](https://www.github.com/14790897/paper-ai/commit/e7aa998ca7dafe38a0c12ada4f168717c6e45439))
* 谷歌登陆后不再弹出 ([5f3252d](https://www.github.com/14790897/paper-ai/commit/5f3252da6e2715e4afbb7ab0b648112c22604230))
* 通过判断user是否登陆来决定是否one tap ([8730415](https://www.github.com/14790897/paper-ai/commit/87304153526200a2c3340c433c87348d5199287b))
## [1.8.0](https://www.github.com/14790897/paper-ai/compare/v1.7.0...v1.8.0) (2024-02-24)
### Features
* 优雅的报错提示 ([93f8889](https://www.github.com/14790897/paper-ai/commit/93f8889c5798b6f47dfb3a3831c051a11078786d))
* 可以切换多种引用格式 ([9b835bb](https://www.github.com/14790897/paper-ai/commit/9b835bbadd89763ab63fa159f35dd7ed657296c6))
* 增加了时间范围选择,除arxiv ([49a757f](https://www.github.com/14790897/paper-ai/commit/49a757f6c7d2a18bbde0e95cf57d4aaf5127e24c))
* 论文搜索完成进行提示 ([6c37459](https://www.github.com/14790897/paper-ai/commit/6c37459fe3b35f379e5b0b4d3c65224f32efb04d))
### Bug Fixes
* 复制文献问题 ([a38b9ce](https://www.github.com/14790897/paper-ai/commit/a38b9cee529a04100c4ebb8ba4129c2caa86f2d6))
## [1.7.0](https://www.github.com/14790897/paper-ai/compare/v1.6.0...v1.7.0) (2024-02-22)
### Features
* pwa可离线访问 service worker ([ff09eee](https://www.github.com/14790897/paper-ai/commit/ff09eee99343cfa6ee6da301428c4a0b3c790bf6))
* seo优化 ([bedc8a3](https://www.github.com/14790897/paper-ai/commit/bedc8a3ce0a314fd2cc7add65defdce372a1c432))
* 加了个用户反馈组件 ([cef12f3](https://www.github.com/14790897/paper-ai/commit/cef12f31a026be9ccc6229943f6a64b3ebf930db))
* 可选的对文献相关性检验 ([6cda6d1](https://www.github.com/14790897/paper-ai/commit/6cda6d176aac29b3972dfde305a62c0be0dc2437))
### Bug Fixes
* 用户反馈组件 ([8155299](https://www.github.com/14790897/paper-ai/commit/81552993bed272a5a05b19edd41aeb10106124b8))
## [1.6.0](https://www.github.com/14790897/paper-ai/compare/v1.5.0...v1.6.0) (2024-02-19)
### Features
* github登录测试中 ([4ee0816](https://www.github.com/14790897/paper-ai/commit/4ee08169df05a9bcf487a25c4b56c3785edbea7a))
* 可以进行多轮文献查询 ([9d799f1](https://www.github.com/14790897/paper-ai/commit/9d799f1736a7ff72e09f9e36e916c0ab9e04cec4))
* 增加了一个显示当前任务进度的进度条 ([c55a93c](https://www.github.com/14790897/paper-ai/commit/c55a93c79b20c7fb4b5ff15027110267d6874c24))
* 如果AI多次引用同一文献则只返回第一个文献的引用数字 ([763a106](https://www.github.com/14790897/paper-ai/commit/763a1062f982b5f0b96da5afb3b3bb96fd66eaef))
### Bug Fixes
* ai对话 ([96d780d](https://www.github.com/14790897/paper-ai/commit/96d780dd3a1c04e4c4adbd61cd87d07a42fa3eaa))
* pubmed参数写反 ([07070bf](https://www.github.com/14790897/paper-ai/commit/07070bf253044958931e138b5af0099ddc3fb8dd))
* translation ([03febb1](https://www.github.com/14790897/paper-ai/commit/03febb136415fcd48a4248d19c1086bfc0c95f8d))
* 修复lemon路由 ([5e7afea](https://www.github.com/14790897/paper-ai/commit/5e7afea400af03716d08e2d6d7aadb6eccd3448e))
* 去除暗色模式 ([da5cb4f](https://www.github.com/14790897/paper-ai/commit/da5cb4fac84e800e4e8bcc105a395088af615631))
* 只有在AI返回的内容没有错之后才能添加文献 ([3040c11](https://www.github.com/14790897/paper-ai/commit/3040c11ea1b843f923475ac117516e82de3f4458))
* 图标正常显示 ([8ab1bdd](https://www.github.com/14790897/paper-ai/commit/8ab1bdd3935713595d35ed41471146cfa83cc4f0))
* 导出word时文献不更新因为usecallback没有添加变量 ([01d3ffe](https://www.github.com/14790897/paper-ai/commit/01d3ffebf7a86c27161d97b73a949a1f0d73a62b))
* 论文引用格式 ([b603365](https://www.github.com/14790897/paper-ai/commit/b603365265314f61122a8bab0da1561bc1c0c5a2))
## [1.5.0](https://www.github.com/14790897/paper-ai/compare/v1.4.0...v1.5.0) (2024-02-13)

View File

@ -1,35 +1,30 @@
<a href="https://paperai.life">
<div align="center">
<img src="./public/android-chrome-192x192.png" alt="the fastest way to create a paper with real references">
</div>
<h1 align="center">paper-ai</h1>
</a>
[English Documentation](./README_en.md)
<p align="center"> <a href="./README_en.md"><b>English Documentation </b></a> </p>
<a href="https://paperai.life">
<img alt="Next.js and Supabase Starter Kit - the fastest way to build apps with Next.js and Supabase" src="https://paperai.life/opengraph-image.png">
<h1 align="center">paper-ai</h1>
</a>
<p align="center">
使用真实文献最快速完成论文的方法
</p>
<p align="center">
<a href='https://docs.paperai.life/' style='font-size: 20px;'><strong>文档网站(教程比较详细,推荐阅读这里)</strong></a> ·
<a href='https://www.bilibili.com/video/BV1Ya4y1k75V'><strong>bilibili视频教程</strong></a>
</p>
<p align="center">
<a href="#功能"><strong>功能</strong></a> ·
<a href="#演示"><strong>演示</strong></a> ·
<a href="#部署到Vercel"><strong>部署到 Vercel</strong></a> ·
<a href="#克隆并在本地运行"><strong>克隆并在本地运行</strong></a>
<a href="#克隆并在本地运行"><strong>克隆并在本地运行</strong></a> ·
</p>
<br/>
## 功能
### 利用人工智能撰写论文
- **人工智能书写功能** 点击 "AI 写作 "进行正常对话互动。人工智能将根据您的输入提供写作建议或回答问题。
- **寻找文献功能** 点击 "寻找文献",根据输入的关键词在 Semantic Scholar 或 arxiv 或 PubMed 中搜索论文。系统将把信息整合到您的论文中。
- **Paper2AI功能** 点击 "Paper2AI"根据输入的关键词在Semantic Scholar或arxiv或PubMed中搜索论文。系统将把信息整合到您的论文中。
### 编辑和修改
@ -40,24 +35,20 @@
您可以在 [paperai.life](https://paperai.life) 查看完整的工作演示。
## 部署到 Vercel
## 部署到Vercel
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/14790897/paper-ai&project-name=paper-ai&repository-name=paper-ai&demo-title=paper-ai&demo-description=This%20starter%20configures%20Supabase%20Auth%20to%20use%20cookies%2C%20making%20the%20user's%20session%20available%20throughout%20the%20entire%20Next.js%20app%20-%20Client%20Components%2C%20Server%20Components%2C%20Route%20Handlers%2C%20Server%20Actions%20and%20Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fpaperai.life%2Fopengraph-image.png)
上述操作还会将 repo 克隆到 GitHub。
如果只想在本地开发,而不想部署到 Vercel[请按以下步骤操作](#克隆并在本地运行)。
如果只想在本地开发,而不想部署到 Vercel[请按以下步骤操作](#clone-and-run-locally)。
## 镜像运行
1. 拉取镜像
```sh
docker pull 14790897/paperai:latest
```
2. 运行镜像
```sh
docker run -d -p 3000:3000 \
-e NEXT_PUBLIC_AI_URL=自定义AI模型地址\
@ -66,11 +57,10 @@ docker run -d -p 3000:3000 \
```
## 环境变量说明
1. NEXT_PUBLIC_OPENAI_API_KEY 设置 key只要在设置界面右上角齿轮对应的位置留空就会使用预定的变量
2. NEXT_PUBLIC_AI_URL 设置上游 url只要在设置界面右上角齿轮对应的位置留空就会使用预定的变量
3. NEXT_PUBLIC_SEMANTIC_API_KEY 设置 semantic scholar 的 key可以增加请求量
4. NEXT_PUBLIC_PUBMED_API_KEY 设置 pubmed 的 key可以增加请求量
1. NEXT_PUBLIC_OPENAI_API_KEY 设置key只要在设置界面右上角齿轮对应的位置留空就会使用预定的变量
2. NEXT_PUBLIC_AI_URL 设置上游url只要在设置界面右上角齿轮对应的位置留空就会使用预定的变量
3. NEXT_PUBLIC_SEMANTIC_API_KEY 设置semantic scholar的key可以增加请求量
4. NEXT_PUBLIC_PUBMED_API_KEY 设置pubmed的key可以增加请求量
## 克隆并在本地运行
@ -87,14 +77,13 @@ npm install
# 运行项目
npm run dev
```
```
## 参考文档
1. semantic scholar api: https://api.semanticscholar.org/api-docs/#tag/Paper-Data/operation/get_graph_paper_relevance_search
2. pubmed api: https://www.ncbi.nlm.nih.gov/books/NBK25500/
3. i18n: https://locize.com/blog/next-app-dir-i18n/
## 许可证
MIT
该项目已获得[MIT License](LICENSE)的许可

View File

@ -1,24 +1,17 @@
<a href="https://paperai.life">
<div align="center">
<img src="./public/android-chrome-192x192.png" alt="the fastest way to create a paper with real references">
</div>
<h1 align="center">paper-ai</h1>
<img alt="Next.js and Supabase Starter Kit - the fastest way to build apps with Next.js and Supabase" src="https://paperai.life/opengraph-image.png">
<h1 align="center">paper-ai</h1>
</a>
<p align="center">
The fastest way to write a paper with true references
</p>
<p align="center">
<a href='https://docs.paperai.life/' style='font-size: 20px;'><strong> Website Documentation (detailed tutorials, highly recommended)</strong></a> ·
<a href='https://www.bilibili.com/video/BV1Ya4y1k75V'><strong>bilibili Video Tutorial</strong></a>
</p>
<p align="center">
<a href="#features"><strong>Features</strong></a> ·
<a href="#demo"><strong>Demo</strong></a> ·
<a href="#deploy-to-vercel"><strong>Deploy to Vercel</strong></a> ·
<a href="#clone-and-run-locally"><strong>Clone and run locally</strong></a>
<a href="#clone-and-run-locally"><strong>Clone and run locally</strong></a> ·
<!-- <a href="#feedback-and-issues"><strong>Feedback and issues</strong></a>
<a href="#more-supabase-examples"><strong>More Examples</strong></a> -->
</p>
@ -47,31 +40,6 @@ The above will also clone the repo to your GitHub, you can clone that locally an
If you wish to just develop locally and not deploy to Vercel, [follow the steps below](#clone-and-run-locally).
## Using Docker
1. Using `docker pull` command
```sh
docker pull 14790897/paperai:latest
```
2. Run Docker
```sh
docker run -d -p 3000:3000 \
-e NEXT_PUBLIC_AI_URL=CUSTOM_AI_URL \
-e NEXT_PUBLIC_OPENAI_API_KEY=CUSTOM_API_KEY \
14790897/paperai:latest
```
Replace `CUSTOM_AI_URL` and `CUSTOM_API_KEY` to your own AI URL and API key
## Environment variable description
1. NEXT_PUBLIC_OPENAI_API_KEY sets the key. Simply leave the corresponding position in the settings interface (the gear in the upper right corner) blank, the predetermined variable will be used.
2. NEXT_PUBLIC_AI_URL sets the upstream url. Simply leave the corresponding position in the settings interface (the gear in the upper right corner) blank, the predetermined variable will be used.
3. NEXT_PUBLIC_SEMANTIC_API_KEY sets the `semantic scholar` key to increase the number of requests
4. NEXT_PUBLIC_PUBMED_API_KEY sets the `pubmed` key to increase the number of requests
## Clone and run locally
```bash
@ -89,13 +57,5 @@ npm run dev
```
## Reference
1. semantic scholar api: https://api.semanticscholar.org/api-docs/#tag/Paper-Data/operation/get_graph_paper_relevance_search
2. pubmed api: https://www.ncbi.nlm.nih.gov/books/NBK25500/
3. i18n: https://locize.com/blog/next-app-dir-i18n/
## LICENSE
This repository is licensed under the MIT License
See the [LICENSE](LICENSE) file for details.
MIT

View File

@ -0,0 +1,30 @@
"use client"; // Error components must be Client Components
import { useEffect } from "react";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
);
}

BIN
app/[lng]/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -10,14 +10,14 @@
--foreground: 200 50% 3%;
}
/* @media (prefers-color-scheme: dark) {
@media (prefers-color-scheme: dark) {
:root {
--background: 200 50% 3%;
--btn-background: 200 10% 9%;
--btn-background-hover: 200 10% 12%;
--foreground: 200 20% 96%;
}
} */
}
}
@layer base {
@ -123,24 +123,17 @@
#editor {
width: 100%; /* 适应屏幕宽度 */
min-height: 200px; /* 调整为更适合移动设备的尺寸 */
padding: 5px; /* 减少内边距 */
}
#Qtoolbar {
display: flex; /* 使用弹性盒布局 */
flex-direction: row; /* 项目水平排列 */
flex-wrap: wrap; /* 允许项目换行 */
align-items: center; /* 项目在交叉轴上居中对齐 */
justify-content: center; /* 项目在主轴上靠左对齐 */
}
#Qtoolbar > textarea {
width: 100%;
min-height: 60px; /* 调整输入框的高度 */
flex-direction: column; /* 在较小屏幕上垂直堆叠工具栏元素 */
align-items: stretch; /* 拉伸按钮以填充容器 */
}
#Qtoolbar > button,
#Qtoolbar > select,
#Qtoolbar > input {
#Qtoolbar > select {
margin-bottom: 10px; /* 增加元素之间的间距 */
margin-right: 10px; /* 右边距,增加元素之间的间距 */
}
}
@ -167,8 +160,3 @@
transform: scale(1.2); /* 放大到原大小的1.2倍 */
transition: transform 0.3s ease; /* 平滑过渡效果 */
}
/* 去除toast的最大宽度限制 */
.Toastify__toast-container--top-center:has(div.toastDetail) {
width: 80%;
}

30
app/[lng]/layout.tsx Normal file
View File

@ -0,0 +1,30 @@
import { GeistSans } from "geist/font/sans";
import "./globals.css";
import { GoogleAnalytics } from "@next/third-parties/google";
const defaultUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
export const metadata = {
metadataBase: new URL(defaultUrl),
title: "paper ai 使用真实文献让AI完成论文",
description: "写论文最高效的方式",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className={GeistSans.className}>
<body className="bg-background text-foreground">
<main className="min-h-screen flex flex-col items-center">
{children}
</main>
</body>
<GoogleAnalytics gaId="G-05DHTG9XQ5" />
</html>
);
}

View File

@ -3,25 +3,12 @@ import { headers, cookies } from "next/headers";
import { createClient } from "@/utils/supabase/server";
import { redirect } from "next/navigation";
import * as Sentry from "@sentry/nextjs";
import DeployButton from "@/components/DeployButton";
import SettingsLink from "@/components/SettingsLink";
//i18n
import { useTranslation } from "@/app/i18n";
import { FooterBase } from "@/components/Footer/FooterBase";
//supabase
import { insertUserProfile } from "@/utils/supabase/supabaseutils";
// SignInWithProvider
import { SignInWithProvider } from "@/components/SignInWithProvider";
import LinuxdoSignin from "@/components/LinuxdoSignin";
export default async function Login({
export default function Login({
searchParams,
params: { lng },
}: {
searchParams: { message: string };
params: { lng: string };
}) {
const { t } = await useTranslation(lng);
const signIn = async (formData: FormData) => {
"use server";
@ -36,7 +23,7 @@ export default async function Login({
});
//sentry
const user = data?.user;
if (user && process.env.NODE_ENV === "production") {
if (user) {
Sentry.setUser({
email: user.email,
id: user.id,
@ -67,7 +54,22 @@ export default async function Login({
},
});
//profiles表 插入用户信息
await insertUserProfile(data, supabase);
const user = data?.user;
if (user) {
const { data, error: profileError } = await supabase
.from("profiles")
.insert([{ id: user.id, email: user.email }]);
if (profileError) {
console.error("Failed to create user profile:", profileError);
}
//sentry
Sentry.setUser({
email: user.email,
id: user.id,
ip_address: "{{auto}}}",
});
}
if (error) {
return redirect("/login?message=Could not authenticate user");
@ -78,12 +80,6 @@ export default async function Login({
return (
<div className="flex-1 flex flex-col w-full px-8 sm:max-w-md justify-center gap-2">
<nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
<div className="w-full max-w-4xl flex justify-between items-center p-3 text-sm">
<DeployButton />
<SettingsLink />
</div>
</nav>
<Link
href="/"
className="absolute left-8 top-8 py-2 px-4 rounded-md no-underline text-foreground bg-btn-background hover:bg-btn-background-hover flex items-center group text-sm"
@ -104,6 +100,7 @@ export default async function Login({
</svg>{" "}
Back
</Link>
<form
className="animate-in flex-1 flex flex-col w-full justify-center gap-2 text-foreground"
action={signIn}
@ -128,17 +125,13 @@ export default async function Login({
required
/>
<button className="bg-green-700 rounded-md px-4 py-2 text-foreground mb-2">
Sign In
Sign In
</button>
<button
formAction={signUp}
className="border border-foreground/20 rounded-md px-4 py-2 text-foreground mb-2"
>
Sign Up
</button>
{/* 重置密码 */}
<button className="border border-foreground/20 rounded-md px-4 py-2 text-foreground mb-2">
<Link href="/request-reset">Reset Password</Link>
Sign Up
</button>
{searchParams?.message && (
<p className="mt-4 p-4 bg-foreground/10 text-foreground text-center">
@ -146,32 +139,6 @@ export default async function Login({
</p>
)}
</form>
<div>
<LinuxdoSignin />
<SignInWithProvider
provider="github"
redirectTo="https://www.paperai.life/welcome"
/>
<SignInWithProvider
provider="google"
redirectTo="https://www.paperai.life/welcome"
/>
</div>
<footer className="w-full border-t border-t-foreground/10 p-8 flex justify-center text-center text-xs">
<div className="flex items-center space-x-4">
{" "}
{/* 添加flex容器来水平排列子元素 */}
<a
href="https://github.com/14790897/paper-ai"
target="_blank"
className="font-bold text-blue-600 hover:underline hover:text-blue-800"
rel="noreferrer"
>
{t("give me a star in GitHub")}
</a>
<FooterBase t={t} lng={lng} />
</div>
</footer>
</div>
);
}

10
app/[lng]/nodes/page.tsx Normal file
View File

@ -0,0 +1,10 @@
import { createClient } from '@/utils/supabase/server';
import { cookies } from 'next/headers';
export default async function Notes() {
const cookieStore = cookies()
const supabase = createClient(cookieStore);
const { data: notes } = await supabase.from("notes").select();
return <pre>{JSON.stringify(notes, null, 2)}</pre>
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

View File

@ -14,19 +14,18 @@ import PaperManagementWrapper from "@/components/PaperManagementWrapper";
import { useTranslation } from "@/app/i18n";
import { FooterBase } from "@/components/Footer/FooterBase";
import { IndexProps } from "@/utils/global";
import GoogleSignIn from "@/components/GoogleSignIn";
// import Error from "@/app/global-error";
export default async function Index({ params: { lng } }: IndexProps) {
const { t } = await useTranslation(lng);
const cookieStore = cookies();
let supabase: any, user;
const canInitSupabaseClient = () => {
// This function is just for the interactive tutorial.
// Feel free to remove it once you have Supabase connected.
try {
supabase = createClient(cookieStore);
createClient(cookieStore);
return true;
} catch (e) {
return false;
@ -34,12 +33,7 @@ export default async function Index({ params: { lng } }: IndexProps) {
};
const isSupabaseConnected = canInitSupabaseClient();
if (supabase) {
({
data: { user },
} = await supabase.auth.getUser());
}
console.log("user in page", user);
return (
<div className="flex-1 w-full flex flex-col gap-5 items-center">
<nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
@ -48,8 +42,6 @@ export default async function Index({ params: { lng } }: IndexProps) {
{/* 用来表示是否显示论文列表页 */}
<PaperListButtonWrapper />
{isSupabaseConnected && <AuthButton />}
{/* 如果用户没有登录会出现谷歌的sign in按钮登录之后不会出现 */}
{!user && <GoogleSignIn />}
<SettingsLink />
</div>
</nav>
@ -67,27 +59,6 @@ export default async function Index({ params: { lng } }: IndexProps) {
>
{t("give me a star in GitHub")}
</a>
<a
href="https://docs.paperai.life/"
target="_blank"
className="font-bold text-blue-500 hover:underline hover:text-blue-700"
>
<strong>使</strong>
</a>
<a
href="./privacy"
target="_blank"
className="font-bold text-blue-500 hover:underline hover:text-blue-700"
>
<strong>PrivacyPolicy</strong>
</a>
<a
href="./service"
target="_blank"
className="font-bold text-blue-500 hover:underline hover:text-blue-700"
>
<strong>Service</strong>
</a>
<FooterBase t={t} lng={lng} />
</div>
</footer>

View File

@ -1,70 +0,0 @@
import React from "react";
export default function PrivacyPolicy() {
return (
<div className="max-w-4xl mx-auto p-4">
<h1></h1>
<p>
使paperai使
</p>
<h2>使</h2>
<p>使paperai时</p>
<ul>
<li></li>
<li></li>
</ul>
<p>使</p>
<ul>
<li></li>
<li></li>
<li>使</li>
<li>Cookie</li>
</ul>
<p>使</p>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<h2></h2>
<p>
</p>
<ul>
<li>便</li>
<li></li>
<li></li>
</ul>
<h2></h2>
<p>
访
</p>
<h2></h2>
<p>
访使
</p>
<h2></h2>
<p>
//
</p>
<h2></h2>
<p>
paperai上发布新的隐私政策来通知您任何更改
</p>
<h2></h2>
<p>
liuweiqing147@gmail.com过与我们联系
</p>
<p>2024.3.7</p>
</div>
);
}

View File

@ -1,41 +0,0 @@
"use client";
import { useState } from "react";
import { createClient } from "@/utils/supabase/client";
const RequestResetPassword = () => {
const supabase = createClient();
const [email, setEmail] = useState("");
const handleResetPassword = async () => {
const { data, error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: `${window.location.origin}/reset-password`, // 确保这个URL是你重置密码页面的地址
});
console.log("当前链接", `${window.location.origin}/reset-password`);
if (error) {
alert("Error sending password reset email: " + error.message);
} else {
alert("Please check your email for the password reset link");
}
};
return (
<div className="flex flex-col items-center justify-center p-4">
<input
type="email"
placeholder="Your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="px-4 py-2 border rounded-md focus:ring-blue-500 focus:border-blue-500 shadow-sm"
/>
<button
onClick={handleResetPassword}
className="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md shadow hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
>
Reset Password
</button>
</div>
);
};
export default RequestResetPassword;

View File

@ -1,58 +0,0 @@
"use client";
import { useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { useRouter } from "next/navigation";
const ResetPassword = () => {
const supabase = createClient();
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const router = useRouter();
const handleNewPassword = async () => {
// 检查两次输入的密码是否一致
if (newPassword !== confirmPassword) {
alert("The passwords do not match. Please try again.");
return;
}
const { error } = await supabase.auth.updateUser({
password: newPassword,
});
if (error) {
alert("Error resetting password: " + error.message);
} else {
alert("Your password has been reset successfully.");
router.push("/login"); // 导航到登录页面或其他页面
}
};
return (
<div className="flex flex-col items-center justify-center space-y-4 bg-gray-50 p-6 rounded-lg shadow-md">
<input
type="password"
placeholder="New password新密码"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<input
type="password"
placeholder="Confirm new password确认新密码"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
onClick={handleNewPassword}
className="px-4 py-2 w-full text-white bg-blue-500 hover:bg-blue-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors"
>
Update Password
</button>
</div>
);
};
export default ResetPassword;

View File

@ -1,79 +0,0 @@
"use client";
import Head from "next/head";
import * as Sentry from "@sentry/nextjs";
export default function Page() {
return (
<div>
<Head>
<title>Sentry Onboarding</title>
<meta name="description" content="Test Sentry for your Next.js app!" />
</Head>
<main
style={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<h1 style={{ fontSize: "4rem", margin: "14px 0" }}>
<svg
style={{
height: "1em",
}}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 200 44"
>
<path
fill="currentColor"
d="M124.32,28.28,109.56,9.22h-3.68V34.77h3.73V15.19l15.18,19.58h3.26V9.22h-3.73ZM87.15,23.54h13.23V20.22H87.14V12.53h14.93V9.21H83.34V34.77h18.92V31.45H87.14ZM71.59,20.3h0C66.44,19.06,65,18.08,65,15.7c0-2.14,1.89-3.59,4.71-3.59a12.06,12.06,0,0,1,7.07,2.55l2-2.83a14.1,14.1,0,0,0-9-3c-5.06,0-8.59,3-8.59,7.27,0,4.6,3,6.19,8.46,7.52C74.51,24.74,76,25.78,76,28.11s-2,3.77-5.09,3.77a12.34,12.34,0,0,1-8.3-3.26l-2.25,2.69a15.94,15.94,0,0,0,10.42,3.85c5.48,0,9-2.95,9-7.51C79.75,23.79,77.47,21.72,71.59,20.3ZM195.7,9.22l-7.69,12-7.64-12h-4.46L186,24.67V34.78h3.84V24.55L200,9.22Zm-64.63,3.46h8.37v22.1h3.84V12.68h8.37V9.22H131.08ZM169.41,24.8c3.86-1.07,6-3.77,6-7.63,0-4.91-3.59-8-9.38-8H154.67V34.76h3.8V25.58h6.45l6.48,9.2h4.44l-7-9.82Zm-10.95-2.5V12.6h7.17c3.74,0,5.88,1.77,5.88,4.84s-2.29,4.86-5.84,4.86Z M29,2.26a4.67,4.67,0,0,0-8,0L14.42,13.53A32.21,32.21,0,0,1,32.17,40.19H27.55A27.68,27.68,0,0,0,12.09,17.47L6,28a15.92,15.92,0,0,1,9.23,12.17H4.62A.76.76,0,0,1,4,39.06l2.94-5a10.74,10.74,0,0,0-3.36-1.9l-2.91,5a4.54,4.54,0,0,0,1.69,6.24A4.66,4.66,0,0,0,4.62,44H19.15a19.4,19.4,0,0,0-8-17.31l2.31-4A23.87,23.87,0,0,1,23.76,44H36.07a35.88,35.88,0,0,0-16.41-31.8l4.67-8a.77.77,0,0,1,1.05-.27c.53.29,20.29,34.77,20.66,35.17a.76.76,0,0,1-.68,1.13H40.6q.09,1.91,0,3.81h4.78A4.59,4.59,0,0,0,50,39.43a4.49,4.49,0,0,0-.62-2.28Z"
></path>
</svg>
</h1>
<p>Get started by sending us a sample error:</p>
<button
type="button"
style={{
padding: "12px",
cursor: "pointer",
backgroundColor: "#AD6CAA",
borderRadius: "4px",
border: "none",
color: "white",
fontSize: "14px",
margin: "18px",
}}
onClick={() => {
Sentry.startSpan({
name: 'Example Frontend Span',
op: 'test'
}, async () => {
const res = await fetch("/api/sentry-example-api");
if (!res.ok) {
throw new Error("Sentry Example Frontend Error");
}
});
}}
>
Throw error!
</button>
<p>
Next, look for the error on the{" "}
<a href="https://liuweiqing-limited.sentry.io/issues/?project=4506728672264192">Issues Page</a>.
</p>
<p style={{ marginTop: "24px" }}>
For more information, see{" "}
<a href="https://docs.sentry.io/platforms/javascript/guides/nextjs/">
https://docs.sentry.io/platforms/javascript/guides/nextjs/
</a>
</p>
</main>
</div>
);
}

View File

@ -1,50 +0,0 @@
import React from "react";
const TermsOfService = () => {
return (
<div>
<h1></h1>
<p>2024.3.7</p>
<h2>1. </h2>
<p>
使paperai使使
</p>
<h2>2. 使</h2>
<p>
使/
</p>
<h2>3. </h2>
<p>
使
</p>
<h2>4. </h2>
<p>
使使
</p>
<h2>5. </h2>
<p>
</p>
<h2>6. </h2>
<p>
使
</p>
<h2>7. </h2>
<p>USA的法律进行解释和执行</p>
<h2>8. </h2>
<p>
liuweiqing147@gmail.com与我们联系
</p>
</div>
);
};
export default TermsOfService;

BIN
app/[lng]/twitter-image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

View File

@ -1,46 +0,0 @@
"use server";
import { createClient } from "@/utils/supabase/server";
import Link from "next/link";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import LoadingIndicator from "@/components/LoadingIndicator"; // 确保路径正确
import { insertUserProfile } from "@/utils/supabase/supabaseutils";
import React from "react";
export default async function WelcomeScreen() {
// const [isLoading, setIsLoading] = React.useState(true);
const cookieStore = cookies();
const supabase = createClient(cookieStore);
const {
data,
data: { user },
} = await supabase.auth.getUser();
//profiles表 插入用户信息
await insertUserProfile(data, supabase);
// setIsLoading(false);
//1秒后跳转到首页
// setTimeout(() => {
redirect("/");
// }, 1000);
return (
<>
{user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<div style={{ margin: "20px", textAlign: "center" }}>
<h1>welcome, {user.email}!</h1>
</div>
</div>
) : (
<Link
href="/login"
className="py-2 px-3 flex rounded-md no-underline bg-btn-background hover:bg-btn-background-hover"
>
Login
</Link>
)}
<LoadingIndicator />
</>
);
}

View File

@ -1,106 +0,0 @@
// api/oauth/callback.js
import { createClient } from "@/utils/supabase/server";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import axios from "axios";
//supabase
import { insertUserProfile } from "@/utils/supabase/supabaseutils";
import { setVip } from "@/utils/supabase/serverutils";
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get("code");
if (code) {
const cookieStore = cookies();
const supabase = createClient(cookieStore);
// await supabase.auth.exchangeCodeForSession(code);
// 使用授权码请求访问令牌
const tokenResponse = await getToken(code);
const accessToken = tokenResponse!.data.access_token;
console.log("accessToekn", accessToken);
// 使用访问令牌获取用户信息
const userResponse = await axios.get("https://connect.linux.do/api/user", {
headers: { Authorization: `Bearer ${accessToken}` },
});
const userInfo = userResponse.data;
const uuid = "9e1c30b5-723c-4805-b3b8-0ac3c1923514"; //生成密码
let userId = null;
// 尝试注册新用户
const signUpResponse = await supabase.auth.signUp({
email: `${userInfo.username}@linux.do`, // 使用模板字符串构建email
password: uuid, // 使用uuid作为密码
});
if (signUpResponse.error) {
// 如果用户已存在,尝试登录来获取用户信息
await supabase.auth.signOut();
const signInResponse = await supabase.auth.signInWithPassword({
email: `${userInfo.username}@linux.do`,
password: uuid,
});
if (signInResponse.error) {
console.error("Error logging in existing user:", signInResponse.error);
// 处理登录失败的情况
} else {
//signin成功
userId = signInResponse.data.user!.id;
}
} else {
//signup成功之后可能要signin一次
const signInResponse = await supabase.auth.signInWithPassword({
email: `${userInfo.username}@linux.do`,
password: uuid,
});
console.log("signInResponse:", signInResponse);
userId = signUpResponse.data.user!.id;
}
// 如果获取到了用户ID进行后续操作
if (userId) {
// console.log("signUpResponse.data:", signUpResponse.data);
//插入信息并设置VIP
await insertUserProfile(signUpResponse.data, supabase);
await setVip(supabase, userId, true, "Linuxdo");
} else {
return new Response(
JSON.stringify({ error: "Unable to register or login the user" }),
{
status: 500,
headers: {
"Content-Type": "application/json",
},
}
);
}
// URL to redirect to after sign in process completes
return NextResponse.redirect(requestUrl.origin);
}
async function getToken(code: string) {
// 使用client_id和client_secret创建Basic Auth凭证
try {
const tokenResponse = await axios.post(
"https://connect.linux.do/oauth2/token",
`grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(
process.env.REDIRECT_URI
)}`,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${process.env.NEXT_PUBLIC_CLIENT_ID}:${process.env.CLIENT_SECRET}`
).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
// 处理tokenResponse...
return tokenResponse;
} catch (error) {
// 处理错误...
console.error(error);
}
}
}

View File

@ -1,9 +0,0 @@
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
// A faulty API route to test Sentry's error monitoring
export function GET() {
throw new Error("Sentry Example API Route Error");
return NextResponse.json({ data: "Testing Sentry Error..." });
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -4,12 +4,6 @@
"AI写作": "AI writing",
"Paper2AI": "Paper2AI",
"点击AI写作就是正常的对话交流点击寻找文献会根据输入的主题词去寻找对应论文": "Click AI Write for normal conversation, click Paper2AI to find corresponding papers based on the input topic",
"选择论文来源": "Select the source of the paper",
"选择AI模型": "Select AI model",
"生成轮数": "Generation Rounds",
"时间范围": "Range of literature release dates, from this time to this year",
"更新文中的上标,使得数字顺序排列": "Update the superscript in the text to make the numbers in order",
"停止生成": "Stop Generation",
"+ Add Paper": "+ Add Paper",
"Buy VIP TO UNLOCK Cloud Sync and Edit Mutiple Papers Simultaneously": "Buy VIP TO UNLOCK Cloud Sync and Edit Mutiple Papers Simultaneously",
"Paper Management": "Paper Management",
@ -30,14 +24,7 @@
"cocopilot-gpt4": "cocopilot-gpt4 (apiKey prefix with ghu, as GitHub does not allow uploading complete keys)",
"deepseek-chat": "deepseek-chat (Model needs to be manually changed to this one)",
"caifree": "caifree (Recommended)",
"linuxdo": "linuxdo",
"coze": "coze",
"vv佬": "vv giant(Recommended)",
"官网反代": "Official website reverse proxy",
"蒙恬大将军": "Mengtian General(Recommended)",
"oneapi": "oneapi",
"custom": "Custom"
},
"鼠标点击段落中的上标跳转到文献引用?": "Click the superscript in the paragraph to jump to the reference?",
"是否检查文献与主题相关性(如果不相关则不会传给AI引用)": "Check the relevance of the literature to the topic (if it is not relevant, it will not be passed to the AI reference)"
"鼠标点击段落中的上标跳转到文献引用?": "Click the superscript in the paragraph to jump to the reference?"
}

View File

@ -4,12 +4,6 @@
"AI写作": "AI写作",
"Paper2AI": "寻找文献",
"点击AI写作就是正常的对话交流点击寻找文献会根据输入的主题词去寻找对应论文": "点击AI写作就是正常的对话交流点击寻找文献会根据输入的主题词去寻找对应论文",
"选择论文来源": "选择论文来源",
"选择AI模型": "选择AI模型",
"生成轮数": "生成轮数",
"时间范围": "文献发布日期范围,从这个时间到今年",
"更新文中的上标,使得数字顺序排列": "更新文中的上标,使得数字顺序排列",
"停止生成": "停止生成",
"+ Add Paper": "+ 添加新论文(会直接替换编辑器里的内容)",
"Buy VIP TO UNLOCK Cloud Sync and Edit Mutiple Papers Simultaneously": "购买VIP解锁云同步和同时编辑多篇论文",
"Paper Management": "论文管理",
@ -31,14 +25,7 @@
"cocopilot-gpt4": "cocopilot-gpt4apiKey前面手动加上ghu因为GitHub不允许上传完整的密钥",
"deepseek-chat": "deepseek-chat需要手动修改模型为这个",
"caifree": "caifree推荐",
"linuxdo": "linuxdo",
"coze": "扣子coze(我亲自维护)",
"官网反代": "官网反代",
"vv佬": "vv佬(推荐)",
"蒙恬大将军": "蒙恬大将军(推荐)",
"oneapi": "oneapi",
"custom": "自定义"
},
"鼠标点击段落中的上标跳转到文献引用?": "鼠标点击段落中的上标跳转到文献引用?",
"是否检查文献与主题相关性(如果不相关则不会传给AI引用)": "是否检查文献与主题相关性如果不相关则不会传给AI引用"
"鼠标点击段落中的上标跳转到文献引用?": "鼠标点击段落中的上标跳转到文献引用?"
}

View File

@ -1,109 +0,0 @@
import { GeistSans } from "geist/font/sans";
import "./globals.css";
import { GoogleAnalytics } from "@next/third-parties/google";
import Script from "next/script";
const defaultUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
export const metadata = {
manifest: "/manifest.json",
metadataBase: new URL(defaultUrl),
title: "paper ai 使用真实文献让AI完成论文",
description: "写论文最高效的方式",
keywords: [
"free AI",
"免费AI模型",
"AI",
"AI paper",
"true references",
"真实文献",
"真实文献引用",
],
authors: [{ name: "liuweiqing", url: "https://github.com/14790897" }],
creator: "liuweiqing",
publisher: "liuweiqing",
alternates: {
canonical: "/",
languages: {
"en-US": "/en-US",
"de-DE": "/de-DE",
},
},
openGraph: {
images:
"https://file.paperai.life/2024/02/540f3476ef43c831934ce0359c367acd.png",
},
twitter: {
card: "page",
title: "AI write",
description: "The fastest way to write paper",
creator: "@hahfrank",
images: [
"https://file.paperai.life/2024/02/540f3476ef43c831934ce0359c367acd.png",
],
},
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" className={GeistSans.className}>
{/* <Script>{`
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
// 注册成功
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// 注册失败 :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
`}</Script> */}
{/* msft clarify */}
<Script>
{`(function (c, l, a, r, i, t, y) {
c[a] =
c[a] ||
function () {
(c[a].q = c[a].q || []).push(arguments);
};
t = l.createElement(r);
t.async = 1;
t.src = "https://www.clarity.ms/tag/" + i;
y = l.getElementsByTagName(r)[0];
y.parentNode.insertBefore(t, y);
})(window, document, "clarity", "script", "l869naiex9");`}
</Script>
{/* google一键登录 */}
<Script src="https://accounts.google.com/gsi/client" async></Script>
<body className="bg-background text-foreground">
<main className="min-h-screen flex flex-col items-center">
{children}
</main>
</body>
{/* 谷歌分析 */}
<GoogleAnalytics gaId="G-05DHTG9XQ5" />
{/* vocechat聊天 */}
<Script
data-host-id="1"
data-auto-reg="true"
data-login-token=""
data-theme-color="#3EB489"
data-close-width="48"
data-close-height="48"
data-open-width="380"
data-open-height="480"
data-welcome="欢迎提问"
src="https://voce.paperai.life/widget.js"
async
></Script>
</html>
);
}

View File

@ -1,5 +0,0 @@
User-Agent: *
Allow: /
Disallow: /private/
Sitemap: https://www.paperai.life/sitemap.xml

View File

@ -1,30 +0,0 @@
import { MetadataRoute } from "next";
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: "https://www.paperai.life",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 1,
},
{
url: "https://www.paperai.life/settings",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.5,
},
{
url: "https://docs.paperai.life",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.8,
},
{
url: "https://store.paperai.life",
lastModified: new Date(),
changeFrequency: "weekly",
priority: 0.5,
},
];
}

View File

@ -29,8 +29,6 @@ const statePersistConfig = {
"isVip",
"language",
"isJumpToReference",
"isEvaluateTopicMatch",
"citationStyle",
],
};

View File

@ -10,16 +10,16 @@ export interface APIState {
}
const initialState: APIState = {
apiKey: "sk-GHuPUV6ERD8wVmmr36FeB8D809D34d93Bb857c009f6aF9Fe", //sk-ffe19ebe9fa44d00884330ff1c18cf82
apiKey: "sk-aiHrrRLYUUelHstX69E9484509254dBf92061d6744FfFaD1", //sk-ffe19ebe9fa44d00884330ff1c18cf82
referencesRedux: [],
editorContent: "",
upsreamUrl: "https://one.paperai.life", //https://api.openai.com https://one.caifree.com https://chatserver.3211000.xyz https://api.deepseek.com
upsreamUrl: "https://one.caifree.com", //https://api.openai.com https://one.caifree.com https://chatserver.3211000.xyz https://api.deepseek.com
systemPrompt: `作为论文写作助手,您的主要任务是根据用户提供的研究主题和上下文,以及相关的研究论文,来撰写和完善学术论文。在撰写过程中,请注意以下要点:
1.使
2.使 [1]***[1]*
3.
4.
5.使
5.使,
6.
...[1],...[2]`,

View File

@ -6,8 +6,6 @@ export interface APIState {
isVip: boolean;
language: string;
isJumpToReference: boolean;
isEvaluateTopicMatch: boolean;
citationStyle: string;
}
const initialState: APIState = {
@ -17,8 +15,6 @@ const initialState: APIState = {
isVip: false,
language: "en",
isJumpToReference: false,
isEvaluateTopicMatch: false,
citationStyle: "custom-chinese",
};
export const stateSlice = createSlice({
@ -49,12 +45,6 @@ export const stateSlice = createSlice({
setIsJumpToReference: (state, action: PayloadAction<boolean>) => {
state.isJumpToReference = action.payload;
},
setIsEvaluateTopicMatch: (state, action: PayloadAction<boolean>) => {
state.isEvaluateTopicMatch = action.payload;
},
setCitationStyle: (state, action: PayloadAction<string>) => {
state.citationStyle = action.payload;
},
},
});
@ -66,8 +56,6 @@ export const {
setIsVip,
setLanguage,
setIsJumpToReference,
setIsEvaluateTopicMatch,
setCitationStyle,
} = stateSlice.actions;
export const stateReducer = stateSlice.reducer;

View File

@ -1,20 +1,19 @@
// "use server";
import { createClient } from "@/utils/supabase/server";
import Link from "next/link";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { insertUserProfile } from "@/utils/supabase/supabaseutils";
// import { signOut } from "@/utils/supabase/serversignout";
export default async function AuthButton() {
const cookieStore = cookies();
const supabase = createClient(cookieStore);
const {
data,
data: { user },
} = await supabase.auth.getUser();
//profiles表 插入用户信息
await insertUserProfile(data, supabase);
// console.log("1111 in AuthButton user:", user);
const signOut = async () => {
"use server";

View File

@ -2,7 +2,7 @@ export default function DeployButton() {
return (
<a
className="py-2 px-3 flex rounded-md no-underline hover:bg-btn-background-hover border"
href="https://vercel.com/new/clone?repository-url=https://github.com/14790897/paper-ai&project-name=paper-ai&repository-name=paper-ai&demo-title=paper-ai&demo-description=This%20starter%20configures%20Supabase%20Auth%20to%20use%20cookies%2C%20making%20the%20user's%20session%20available%20throughout%20the%20entire%20Next.js%20app%20-%20Client%20Components%2C%20Server%20Components%2C%20Route%20Handlers%2C%20Server%20Actions%20and%20Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https://file.paperai.life/2024/02/540f3476ef43c831934ce0359c367acd.png"
href="https://vercel.com/new/clone?repository-url=https://github.com/14790897/paper-ai&project-name=paper-ai&repository-name=paper-ai&demo-title=paper-ai&demo-description=This%20starter%20configures%20Supabase%20Auth%20to%20use%20cookies%2C%20making%20the%20user's%20session%20available%20throughout%20the%20entire%20Next.js%20app%20-%20Client%20Components%2C%20Server%20Components%2C%20Route%20Handlers%2C%20Server%20Actions%20and%20Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fpaperai.life%2Fopengraph-image.png"
target="_blank"
rel="noreferrer"
>

View File

@ -1,4 +1,3 @@
"use client";
import { useCallback } from "react";
import { saveAs } from "file-saver";
import * as quillToWord from "quill-to-word";
@ -6,14 +5,13 @@ import * as quillToWord from "quill-to-word";
import { useAppDispatch, useAppSelector } from "@/app/store";
import ReduxProvider from "@/app/store/ReduxProvider";
import { Reference } from "@/utils/global";
import { getAllFullReferences } from "@/utils/others/quillutils";
import { formatAllReferencesForCopy } from "@/utils/others/quillutils";
type ParaIn = {
editor: any;
};
const ExportDocx = ({ editor }: ParaIn) => {
const references = useAppSelector((state) => state.auth.referencesRedux);
const citationStyle = useAppSelector((state) => state.state.citationStyle);
const prepareReferencesForQuill = (references: Reference[]) => {
// 首先添加一个标题
@ -26,17 +24,8 @@ const ExportDocx = ({ editor }: ParaIn) => {
insert: "\n参考文献\n",
},
];
const referencesString = getAllFullReferences(references, citationStyle);
const quillReferences = [
{
attributes: {
// 提供默认值,即使这些值不会改变文本样式
bold: false, // 默认为false因为引用通常不需要加粗
align: "left", // 默认为left这是大多数文本的常规对齐方式
},
insert: referencesString,
},
];
const referencesString = formatAllReferencesForCopy(references);
const quillReferences = [{ insert: referencesString }];
// 合并标题和引用列表
return referencesWithTitle.concat(quillReferences);
};
@ -71,7 +60,7 @@ const ExportDocx = ({ editor }: ParaIn) => {
quillToWordConfig
);
saveAs(docAsBlob, "word-export.docx");
}, [editor, references]);
}, [editor]);
return (
<ReduxProvider>

View File

@ -37,15 +37,13 @@ interface Author {
async function getArxivPapers(
query: string,
maxResults = 2,
offset = -1,
maxResults = 5,
sortBy = "submittedDate",
sortOrder = "descending"
) {
const maxOffset = 30 - maxResults; // 假设总记录数为 20
if (offset === -1) offset = getRandomOffset(maxOffset);
console.log("offset in arxiv", offset);
const url = `https://export.arxiv.org/api/query?search_query=${query}&start=${offset}&max_results=${maxResults}&sortBy=${sortBy}&sortOrder=${sortOrder}`;
const maxOffset = 30 - maxResults; // 假设总记录数为 100
const start = getRandomOffset(maxOffset);
const url = `https://export.arxiv.org/api/query?search_query=${query}&start=${start}&max_results=${maxResults}&sortBy=${sortBy}&sortOrder=${sortOrder}`;
try {
const response = await axios.get(url);
@ -57,7 +55,7 @@ async function getArxivPapers(
return result;
} catch (error: any) {
throw new Error(
`Arxiv失败请使用英文并缩短关键词:${JSON.stringify(
`Error fetching data from Arxiv API:${JSON.stringify(
error.response,
null,
2
@ -76,7 +74,7 @@ function extractArxivData(data: ArxivFeed) {
id: entry.id[0],
published: entry.published[0],
title: entry.title[0],
abstract: entry.summary[0],
summary: entry.summary[0],
authors: entry.author.map((author) => author.name[0]),
};
});

View File

@ -10,20 +10,14 @@ type PubMedID = string;
// 定义idList为PubMedID数组
type IDList = PubMedID[];
async function getPubMedPapers(
query: string,
year: number,
offset = -1,
limit = 2
) {
async function getPubMedPapers(query: string, year: number, limit = 2) {
try {
const baseURL =
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
const db = "pubmed"; // 设定搜索的数据库为PubMed
const retMax = limit; // 检索的最大记录数
const maxOffset = 20 - limit; // 假设总记录数为 20
if (offset === -1) offset = getRandomOffset(maxOffset);
const url = `${baseURL}?db=${db}&term=${query}[Title/Abstract]+AND+${year}:3000[Date - Publication]&retMax=${retMax}&retStart=${offset}&api_key=${process.env.NEXT_PUBLIC_PUBMED_API_KEY}`;
const retStart = getRandomOffset(20 - limit); // 假设每页最多30条根据需要随机偏移
const url = `${baseURL}?db=${db}&term=${query}[Title/Abstract]+AND+2018:3000[Date - Publication]&retMax=${retMax}&retStart=${retStart}&api_key=${process.env.NEXT_PUBLIC_PUBMED_API_KEY}`;
const response = await axios.get(url, { responseType: "text" });
console.log(response.data);
// 解析XML数据
@ -37,7 +31,7 @@ async function getPubMedPapers(
// 这里只返回了ID列表你可能需要根据实际需要进行调整
return idList;
} catch (error) {
console.error(" PubMed API失败(请使用英文并缩短关键词):", error);
console.error("Error fetching data from PubMed API:", error);
return null; // 或根据需要处理错误
}
}
@ -66,18 +60,18 @@ async function getPubMedPaperDetails(idList: IDList) {
// 解析XML数据
const parser = new xml2js.Parser({
explicitArray: false,
ignoreAttrs: false, // 忽略XML属性
ignoreAttrs: true, // 忽略XML属性
charkey: "text", // 字符数据的键
trim: true, // 去除文本前后空格
});
let result = await parser.parseStringPromise(data);
// console.log(result);
console.log(result);
// 提取并处理文章详细信息
const articles = result.PubmedArticleSet.PubmedArticle.map((article) => {
const medlineCitation = article.MedlineCitation;
const articleDetails = medlineCitation.Article;
// console.log("atricledetails", articleDetails);
const abstractTexts = articleDetails.Abstract.AbstractText;
let abstract;
@ -85,7 +79,7 @@ async function getPubMedPaperDetails(idList: IDList) {
if (Array.isArray(abstractTexts)) {
// 如果是数组,遍历数组并连接每个元素的文本
abstract = abstractTexts
.map((text) => (typeof text === "object" ? text.text : text))
.map((text) => (typeof text === "object" ? text._ : text))
.join(" ");
} else if (typeof abstractTexts === "string") {
// 如果 abstractTexts 直接就是字符串
@ -133,7 +127,7 @@ async function getPubMedPaperDetails(idList: IDList) {
journalTitle += `: ${articleDetails.Pagination.StartPage}-${articleDetails.Pagination.EndPage}`;
}
// 构建文章的 PubMed URL
const articleUrl = `https://pubmed.ncbi.nlm.nih.gov/${medlineCitation.PMID.text}/`;
const articleUrl = `https://pubmed.ncbi.nlm.nih.gov/${medlineCitation.PMID}/`;
// console.log("medlineCitation", medlineCitation);
console.log("\n,journalTitle", journalTitle);
let title = articleDetails.ArticleTitle;
@ -141,55 +135,29 @@ async function getPubMedPaperDetails(idList: IDList) {
if (title.endsWith(".")) {
title = title.slice(0, -1);
}
// 提取DOI
let doi = null;
if (
article.PubmedData &&
article.PubmedData.ArticleIdList &&
Array.isArray(article.PubmedData.ArticleIdList.ArticleId)
) {
const doiObject = article.PubmedData.ArticleIdList.ArticleId.find(
(idObj) => idObj.$.IdType === "doi"
);
if (doiObject) {
doi = doiObject.text; // 获取DOI值
}
}
console.log("doi", doi);
console.log(
"链接",
medlineCitation.PMID.text,
"属性",
typeof medlineCitation.PMID.text
);
return {
id: Number(medlineCitation.PMID.text),
id: medlineCitation.PMID._,
title: title,
abstract: abstract,
authors: authors,
url: articleUrl,
year: publishedDate,
journal: journalTitle,
doi: doi,
// 其他需要的字段可以继续添加
};
});
return articles;
} catch (error) {
throw new Error(`Error fetching paper details from PubMed:", ${error}`);
console.error("Error fetching paper details from PubMed:", error);
return null;
}
}
// 示例:使用这些函数
async function fetchPubMedData(
query: string,
year: number,
offset: number,
limit: number
) {
async function fetchPubMedData(query: string, year: number, limit: number) {
try {
const idList = await getPubMedPapers(query, year, offset, limit);
const idList = await getPubMedPapers(query, year, limit);
if (idList && idList.length > 0) {
const paperDetails = await getPubMedPaperDetails(idList);
console.log("fetchPubMedData", paperDetails); // 处理或显示文章详情

View File

@ -15,16 +15,11 @@ interface Paper {
url: string;
}
async function getSemanticPapers(
query: string,
year: string,
offset = -1,
limit = 2
) {
async function getSemanticPapers(query: string, year: string, limit = 2) {
try {
const maxOffset = 20 - limit; // 假设总记录数为 20
if (offset === -1) offset = getRandomOffset(maxOffset);
const url = `https://proxy.paperai.life/proxy/https://api.semanticscholar.org/graph/v1/paper/search`;
const offset = getRandomOffset(maxOffset);
const url = `https://api.semanticscholar.org/graph/v1/paper/search`;
const response = await axios.get(url, {
headers: {
"x-api-key": process.env.NEXT_PUBLIC_SEMANTIC_API_KEY,
@ -32,10 +27,9 @@ async function getSemanticPapers(
params: {
query: query,
offset: offset,
limit: limit,
limit: 2,
year: year,
fields:
"title,year,authors.name,abstract,venue,url,journal,externalIds",
fields: "title,year,authors.name,abstract,venue,url,journal",
},
});
// 提取并处理论文数据
@ -52,7 +46,7 @@ async function getSemanticPapers(
} catch (error: any) {
// console.error("Error fetching data from Semantic Scholar API:", error);
throw new Error(
`Semantic Scholar fail请使用英文并缩短关键词:${JSON.stringify(
`Error fetching data from Semantic Scholar API:${JSON.stringify(
error.response,
null,
2

View File

@ -1,93 +0,0 @@
"use client";
import React, { useEffect } from "react";
//supabase
import { createClient } from "@/utils/supabase/client";
const GoogleSignIn = () => {
const supabase = createClient();
// 加载Google身份验证库并初始化
useEffect(() => {
// 异步检查用户是否已经登录
const checkSession = async () => {
const session = await supabase.auth.getSession();
if (session) {
console.log("用户已登录", session);
} else {
loadGoogleSignInScript();
}
};
checkSession();
}, []);
const loadGoogleSignInScript = () => {
// 确保gapi脚本只被加载一次
if (!window.gapi) {
const script = document.createElement("script");
script.src = "https://accounts.google.com/gsi/client";
script.async = true;
script.defer = true;
script.onload = initGoogleSignIn;
document.body.appendChild(script);
} else {
initGoogleSignIn();
}
};
// 初始化Google登录
const initGoogleSignIn = () => {
window.google.accounts.id.initialize({
client_id:
"646783243018-m2n9qfo12k70debpmkesevt5j2hi2itb.apps.googleusercontent.com", // 替换为你的客户端ID
callback: handleSignInWithGoogle,
auto_select: false, // 根据需要设置
itp_support: true,
});
};
// 处理登录响应
const handleSignInWithGoogle = async (response) => {
const { data, error } = await supabase.auth.signInWithIdToken({
provider: "google",
token: response.credential,
nonce: "", // 如果你使用nonce请在这里设置
});
if (error) {
console.error("Login failed:", error);
return;
}
console.log("Login successful:", data);
// 在这里处理登录成功后的逻辑
};
return (
<div>
{/* <div
id="g_id_onload"
data-client_id="646783243018-m2n9qfo12k70debpmkesevt5j2hi2itb.apps.googleusercontent.com"
data-context="signin"
data-ux_mode="popup"
// data-callback="handleSignInWithGoogleccounts.id.ini"
data-nonce=""
data-auto_select="false"
data-itp_support="true"
></div> */}
<div
id="g_id_signin"
className="g_id_signin"
data-type="standard"
data-shape="pill"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left"
></div>
</div>
);
};
export default GoogleSignIn;

View File

@ -1,31 +0,0 @@
"use client";
// import React from "react";
const LinuxdoSignin = () => {
console.log(
"process.env.NEXT_PUBLIC_CLIENT_ID",
process.env.NEXT_PUBLIC_CLIENT_ID
);
const handleLogin = () => {
// 构建授权URL
const responseType = "code";
const authUrl = `https://connect.linux.do/oauth2/authorize?response_type=${responseType}&client_id=${process.env.NEXT_PUBLIC_CLIENT_ID}&state=ttt1`;
// 重定向到授权页面
window.location.href = authUrl;
};
return (
<div>
<button
onClick={handleLogin}
className="bg-gradient-to-r from-yellow-400 to-yellow-500 text-white rounded-md px-4 py-2 mb-2 flex items-center justify-center gap-2 hover:from-yellow-500 hover:to-yellow-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-yellow-400 shadow-lg hover:shadow-xl transition ease-in duration-200 w-full
"
>
Login with Linuxdo(free VIP)
</button>
</div>
);
};
export default LinuxdoSignin;

View File

@ -1,13 +0,0 @@
// @/components/LoadingIndicator.tsx
import React from "react";
function LoadingIndicator() {
return (
<div className="flex justify-center items-center p-5">
<div className="spinner animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent"></div>
<p className="text-lg">Loading editor...</p>
</div>
);
}
export default LoadingIndicator;

View File

@ -1,34 +0,0 @@
import React, { useState } from "react";
import { toast } from "react-toastify";
// 自定义Toast内容组件
const ExpandableToastContent = ({ fullText }) => {
const [isExpanded, setIsExpanded] = useState(false);
const toggleExpand = () => setIsExpanded(!isExpanded);
return (
<div className="w-full max-w-none p-4 bg-white rounded-lg shadow dark:bg-gray-800">
{/* 可以继续添加更多的Tailwind CSS类来定制外观 */}
<div className="text-sm text-gray-500 dark:text-gray-400">
{isExpanded ? fullText : `${fullText.substring(0, 100)}...`}
</div>
<button
onClick={toggleExpand}
className="mt-2 text-blue-500 hover:text-blue-600 dark:hover:text-blue-400"
>
{isExpanded ? "Show Less" : "Show More"}
</button>
</div>
);
};
// 使用自定义Toast内容的函数
export const showExpandableToast = (message: string) => {
toast(<ExpandableToastContent fullText={message} />, {
position: "top-center",
autoClose: 3000,
pauseOnHover: true,
className: "toastDetail",
});
};

View File

@ -1,6 +1,6 @@
"use client";
import { useCallback, useState, useRef, useEffect } from "react";
import { useCallback, useState, useEffect } from "react";
//redux
import { useAppDispatch, useAppSelector } from "@/app/store";
import {
@ -11,7 +11,6 @@ import {
setPaperNumberRedux,
setContentUpdatedFromNetwork,
setIsVip,
setShowPaperManagement,
} from "@/app/store/slices/stateSlice";
//supabase
import { createClient } from "@/utils/supabase/client";
@ -47,8 +46,6 @@ const PaperManagement = ({ lng }) => {
const showPaperManagement = useAppSelector(
(state) => state.state.showPaperManagement
);
const editorContent = useAppSelector((state) => state.auth.editorContent);
const referencesRedux = useAppSelector((state) => state.auth.referencesRedux);
//vip状态
const isVip = useAppSelector((state) => state.state.isVip);
//获取的论文数量列表状态
@ -112,13 +109,6 @@ const PaperManagement = ({ lng }) => {
}
const handleAddPaperClick = async () => {
// 先手动保存本地内容到云端
// await submitPaper(
// supabase,
// editorContent,
// referencesRedux,
// paperNumberRedux
// );
// 添加一个新的空白论文
await submitPaper(
supabase,
@ -135,33 +125,6 @@ const PaperManagement = ({ lng }) => {
// from: { opacity: 0 },
// });
//用于判断点击有没有落在区域中
const paperManagementRef = useRef(null); // 用于引用PaperManagement组件的根元素
const handleClickOutside = (event) => {
if (
paperManagementRef.current &&
!paperManagementRef.current.contains(event.target) &&
showPaperManagement
) {
// 如果点击事件的目标不是PaperManagement组件内的元素
// 隐藏组件
console.log("Clicked outside of the PaperManagement component.");
dispatch(setShowPaperManagement());
}
};
useEffect(() => {
if (showPaperManagement) {
// 只有当组件可见时,才添加事件监听器
document.addEventListener("mousedown", handleClickOutside);
}
// 组件卸载或状态改变时移除事件监听器
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [showPaperManagement]); // 依赖项数组包含showPaperManagement状态
return (
<CSSTransition
in={showPaperManagement}
@ -172,10 +135,7 @@ const PaperManagement = ({ lng }) => {
{/* showPaperManagement ? ( */}
{/* <animated.div style={animations}> */}
<>
<div
ref={paperManagementRef}
className="paper-management-container flex flex-col items-center space-y-4"
>
<div className="paper-management-container flex flex-col items-center space-y-4">
<div className="max-w-md w-full bg-blue-gray-100 rounded overflow-hidden shadow-lg mx-auto p-5">
<h1 className="font-bold text-3xl text-center">
{" "}

View File

@ -1,38 +0,0 @@
import React from "react";
// 定义props的类型
interface ProgressDisplayProps {
generatedPaperNumber: number;
i: number;
}
// 使用接口为函数组件的props提供类型注解
const ProgressDisplay: React.FC<ProgressDisplayProps> = ({
generatedPaperNumber,
i,
}) => {
// 计算完成的百分比
const percentage = ((i / generatedPaperNumber) * 100).toFixed(2);
return (
<div className="relative">
{/* 可以添加一个进度条来直观显示进度 */}
<div className="h-4 bg-gray-200 rounded-full">
<div
className={`h-full rounded-full ${
Number(percentage) < 100 ? "bg-yellow-500" : "bg-green-500"
}`}
style={{ width: `${percentage}%` }}
></div>
</div>
{/* 文字放置在进度条内部 */}
<div className="absolute inset-0 flex items-center justify-center text-xs text-white pointer-events-none">
<p>
{i} / {generatedPaperNumber}task {percentage}% Complete
</p>
</div>
</div>
);
};
export default ProgressDisplay;

View File

@ -1,16 +1,16 @@
"use client";
import React, { useState, useEffect, useRef, use } from "react";
import React, { useState, useEffect, useRef } from "react";
import Quill from "quill";
import "quill/dist/quill.snow.css";
import { useLocalStorage } from "react-use";
import * as Sentry from "@sentry/react";
import Link from "next/link";
// 一些工具函数导入
import getArxivPapers from "./GetArxiv";
import getSemanticPapers from "./GetSemantic";
import { fetchPubMedData } from "./GetPubMed ";
import { sendMessageToOpenAI } from "./chatAI";
import { getTopicFromAI, sendMessageToOpenAI } from "./chatAI";
import {
getTextBeforeCursor,
convertToSuperscript,
@ -19,18 +19,14 @@ import {
getNumberBeforeCursor,
formatJournalReference,
} from "@/utils/others/quillutils";
import { evaluateTopicMatch } from "@/utils/others/aiutils";
//组件
import ExportDocx from "./Export";
import ReferenceList from "./ReferenceList";
import ProgressDisplay from "./ProgressBar";
//redux
import { useAppDispatch, useAppSelector } from "@/app/store";
import {
addReferencesRedux,
setEditorContent,
setApiKey,
setUpsreamUrl,
} from "@/app/store/slices/authSlice";
import { setContentUpdatedFromNetwork } from "@/app/store/slices/stateSlice";
//类型声明
@ -46,10 +42,6 @@ import {
import { debounce } from "lodash";
//i18n
import { useTranslation } from "@/app/i18n/client";
//notification
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { showExpandableToast } from "@/components/Notification";
const toolbarOptions = [
["bold", "italic", "underline", "strike"], // 加粗、斜体、下划线和删除线
@ -81,9 +73,6 @@ const QEditor = ({ lng }) => {
const isJumpToReference = useAppSelector(
(state) => state.state.isJumpToReference
);
const isEvaluateTopicMatch = useAppSelector(
(state) => state.state.isEvaluateTopicMatch
);
const [quill, setQuill] = useState<Quill | null>(null);
const contentUpdatedFromNetwork = useAppSelector(
(state) => state.state.contentUpdatedFromNetwork
@ -96,7 +85,7 @@ const QEditor = ({ lng }) => {
//quill编辑器鼠标位置
const [cursorPosition, setCursorPosition] = useLocalStorage<number | null>(
"光标位置",
0
null
);
//
// 初始化 Quill 编辑器
@ -105,27 +94,13 @@ const QEditor = ({ lng }) => {
// 选择论文来源
const [selectedSource, setSelectedSource] = useLocalStorage(
"学术引擎",
"pubmed"
"semanticScholar"
); // 默认选项
//选择语言模型
const [selectedModel, setSelectedModel] = useLocalStorage(
"gpt语言模型",
"deepseek-chat"
"gpt-4"
); // 默认选项
const [generatedPaperNumber, setGeneratedPaperNumber] = useLocalStorage(
"生成次数",
1
); // 初始值设为1
//选择时间范围
const [timeRange, setTimeRange] = useLocalStorage("时间范围", "2019");
const [generateNumber, setGenerateNumber] = useState(0); //当前任务的进行数
const [openProgressBar, setOpenProgressBar] = useState(false); //设置进度条是否打开
const [showAnnouncement, setShowAnnouncement] = useLocalStorage(
"显示公告",
false
); // 是否显示公告
const [controller, setController] = useState<AbortController | null>(null); // 创建 AbortController 的状态
//redux
const dispatch = useAppDispatch();
const references = useAppSelector((state) => state.auth.referencesRedux);
@ -219,48 +194,7 @@ const QEditor = ({ lng }) => {
console.log("No editor.current to update in useEffect.");
}
}, [editorContent, contentUpdatedFromNetwork]);
//日常通知可以放在这里
useEffect(() => {
if (showAnnouncement) {
toast(
"📢 如果遇到模型无法响应的情况建议右上角切换为coze模型也是gpt4",
{
position: "top-center",
autoClose: false, // 设置为 false使得公告需要用户手动关闭确保用户看到公告信息
closeOnClick: false, // 防止用户意外点击关闭公告
pauseOnHover: true, // 鼠标悬停时暂停自动关闭,因为 autoClose 已设为 false此设置可保留或去除
draggable: true, // 允许用户拖动公告
progress: undefined,
closeButton: true, // 显示关闭按钮,让用户可以在阅读完毕后关闭公告
hideProgressBar: true, // 隐藏进度条,因为公告不会自动关闭
style: {
// 自定义样式,使公告更加显眼
backgroundColor: "#fffae6", // 浅黄色背景
color: "#333333", // 文字颜色
fontWeight: "bold",
fontSize: "16px",
border: "1px solid #ffd700", // 边框颜色
boxShadow: "0px 0px 10px #ffd700", // 添加阴影,增加显眼度
},
// 当公告被关闭时,设置 localStorage以防再次显示
onClose: () => setShowAnnouncement(false),
}
);
}
}, []);
// 强制更新为我设置的API
// useEffect(() => {
// dispatch(setApiKey("sk-GHuPUV6ERD8wVmmr36FeB8D809D34d93Bb857c009f6aF9Fe"));
// dispatch(setUpsreamUrl("https://one.paperai.life"));
// });
useEffect(() => {
if (upsreamUrl === "https://one.liuweiqing.top") {
dispatch(
setApiKey("sk-GHuPUV6ERD8wVmmr36FeB8D809D34d93Bb857c009f6aF9Fe")
);
dispatch(setUpsreamUrl("https://one.paperai.life"));
}
}, [upsreamUrl]);
const handleTextChange = debounce(async function (delta, oldDelta, source) {
if (source === "user") {
// 获取编辑器内容
@ -297,237 +231,135 @@ const QEditor = ({ lng }) => {
const handleInputChange = (event: any) => {
setUserInput(event.target.value);
};
// 处理输入generatedPaperNumber变化的函数
const handleGeneratedPaperNumberChange = (event: any) => {
const newValue = parseInt(event.target.value, 10);
setGeneratedPaperNumber(newValue);
// 处理AI写作
const handleAIWrite = async () => {
quill.setSelection(cursorPosition, 0); // 将光标移动到原来的位置
const prompt = "请帮助用户完成论文写作,使用用户所说的语言完成";
await sendMessageToOpenAI(
userInput,
quill,
selectedModel,
apiKey,
upsreamUrl,
prompt
);
// 清空input内容
setUserInput("");
// 重新获取更新后的内容并更新 Redux store
const updatedContent = quill.root.innerHTML;
dispatch(setEditorContent(updatedContent));
};
// 处理handleAIAction
async function handleAIAction(topic: string, actionType: string) {
// 创建一个新的 AbortController 实例
const newController = new AbortController();
setController(newController);
quill!.setSelection(cursorPosition!, 0); // 将光标移动到原来的位置
setOpenProgressBar(true); //开启进度条
// 处理paper2AI
async function paper2AI(topic: string) {
quill.setSelection(cursorPosition, 0); // 将光标移动到原来的位置
try {
if (actionType === "write") {
// 写作逻辑
const prompt = "请帮助用户完成论文写作,使用用户所说的语言完成";
await sendMessageToOpenAI(
userInput,
quill!,
selectedModel!,
apiKey,
upsreamUrl,
prompt,
cursorPosition!,
true,
newController.signal // 传递 AbortSignal
);
} else if (actionType === "paper2AI") {
// paper2AI 逻辑,根据 actionParam 处理特定任务
let offset = -1;
if (generatedPaperNumber != 1) offset = 0; //如果生成的数量不为1则从0开始
//如果说要评估主题是否匹配的话,就要多获取一些文献
let limit = 2;
if (isEvaluateTopicMatch) {
limit = 4;
if (!topic) {
//使用ai提取当前要请求的论文主题
const prompt =
"As a topic extraction assistant, you can help me extract the current discussion of the paper topic, I will enter the content of the paper, you extract the paper topic , no more than two, Hyphenated query terms yield no matches (replace it with space to find matches) return format is: topic1 topic2";
const userMessage = getTextBeforeCursor(quill, 2000);
topic = await getTopicFromAI(userMessage, prompt, apiKey);
console.log("topic in AI before removeSpecialCharacters", topic);
topic = removeSpecialCharacters(topic);
topic = topic.split(" ").slice(0, 2).join(" ");
//如果超过十个字符就截断
if (topic.length > 10) {
topic = topic.slice(0, 10);
}
for (let i = 0; i < generatedPaperNumber!; i++) {
if (!topic) {
//使用ai提取当前要请求的论文主题
const prompt =
"As a topic extraction assistant, you can help me extract the current discussion of the paper topic, I will enter the content of the paper, you extract the paper topic , no more than two, Hyphenated query terms yield no matches (replace it with space to find matches) return format is: topic1 topic2";
const userMessage = getTextBeforeCursor(quill!, 2000);
topic = await sendMessageToOpenAI(
userMessage,
null,
selectedModel!,
apiKey,
upsreamUrl,
prompt,
null,
false,
newController.signal // 传递 AbortSignal
);
console.log("topic in AI before removeSpecialCharacters", topic);
topic = removeSpecialCharacters(topic);
topic = topic.split(" ").slice(0, 2).join(" ");
//如果超过十个字符就截断
if (topic.length > 10) {
topic = topic.slice(0, 10);
}
}
console.log(
"topic in AI:",
topic,
"offset in paper2AI:",
offset,
"limit in paper2AI:",
limit
);
let rawData, dataString, newReferences;
if (selectedSource === "arxiv") {
rawData = await getArxivPapers(topic, limit, offset);
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic,
newController.signal
);
rawData = relevantPapers;
}
console.log("arxiv rawdata:", rawData);
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry: any) => ({
url: entry.id,
title: entry.title,
year: entry.published,
author: entry.authors?.slice(0, 3).join(", "),
}));
dataString = rawData
.map((entry: any) => {
return `ID: ${entry.id}\nTime: ${entry.published}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
} else if (selectedSource === "semanticScholar") {
rawData = await getSemanticPapers(
topic,
`${timeRange}-2024`,
offset,
limit
);
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic,
newController.signal
);
rawData = relevantPapers;
}
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry: any) => ({
url: entry.url,
title: entry.title,
year: entry.year,
author: entry.authors?.slice(0, 3).join(", "),
venue: entry.venue,
journal: formatJournalReference(entry),
doi: entry.externalIds.DOI,
}));
dataString = rawData
.map((entry: any) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
} else if (selectedSource === "pubmed") {
rawData = await fetchPubMedData(
topic,
Number(timeRange)!,
offset,
limit
);
if (!rawData) {
throw new Error("未搜索到文献 from PubMed.");
}
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic,
newController.signal
);
rawData = relevantPapers;
}
newReferences = rawData.map((entry: any) => ({
id: entry.id, // 文章的 PubMed ID
title: entry.title, // 文章的标题
abstract: entry.abstract, // 文章的摘要
author: entry.authors?.slice(0, 3).join(", "), // 文章的作者列表,假设为字符串数组
year: entry.year, // 文章的发表日期
journal: entry.journal, // 文章的发表杂志
url: entry.url, // 文章的 URL
source: "PubMed", // 指示这些引用来自 PubMed
doi: entry.doi, // 文章的 DOI
}));
// 打印 newReferences
console.log(newReferences);
dataString = rawData
.map((entry: any) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
}
// 确保搜索到的论文不超过 3000 个字符
const trimmedMessage =
dataString.length > 3000 ? dataString.slice(0, 3000) : dataString;
// 生成AI PROMPT
const content = `之前用户已经完成的内容上下文:${getTextBeforeCursor(
quill!,
800
)},搜索到的论文内容:${trimmedMessage},${topic},`;
showExpandableToast(`搜索论文完成,搜索到的论文:${trimmedMessage}`);
await sendMessageToOpenAI(
content,
quill!,
selectedModel!,
apiKey,
upsreamUrl,
systemPrompt,
cursorPosition!,
true,
newController.signal // 传递 AbortSignal
);
//在对应的位置添加文献
const nearestNumber = getNumberBeforeCursor(quill!);
dispatch(
addReferencesRedux({
references: newReferences,
position: nearestNumber,
})
);
//修改offset使得按照接下来的顺序进行获取文献
offset += 2;
setGenerateNumber(i + 1);
}
setUserInput(""); // 只有在全部成功之后才清空input内容
}
toast.success(
`AI ${actionType == "write" ? "写作" : "文献获取总结"}完成`,
{
position: "top-center",
autoClose: 2000,
pauseOnHover: true,
console.log("topic in AI", topic);
let rawData, dataString, newReferences;
if (selectedSource === "arxiv") {
rawData = await getArxivPapers(topic);
console.log("arxiv rawdata:", rawData);
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry) => ({
url: entry.id,
title: entry.title,
year: entry.published,
author: entry.authors?.slice(0, 3).join(", "),
}));
dataString = rawData
.map((entry) => {
return `ID: ${entry.id}\nTime: ${entry.published}\nTitle: ${entry.title}\nSummary: ${entry.summary}\n\n`;
})
.join("");
} else if (selectedSource === "semanticScholar") {
rawData = await getSemanticPapers(topic, "2015-2023");
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry) => ({
url: entry.url,
title: entry.title,
year: entry.year,
author: entry.authors?.slice(0, 3).join(", "),
venue: entry.venue,
journal: formatJournalReference(entry),
}));
dataString = rawData
.map((entry) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
} else if (selectedSource === "pubmed") {
rawData = await fetchPubMedData(topic, 2020, 2);
if (!rawData) {
throw new Error("未搜索到文献 from PubMed.");
}
newReferences = rawData.map((entry) => ({
id: entry.id, // 文章的 PubMed ID
title: entry.title, // 文章的标题
abstract: entry.abstract, // 文章的摘要
author: entry.authors?.slice(0, 3).join(", "), // 文章的作者列表,假设为字符串数组
year: entry.year, // 文章的发表日期
journal: entry.journal, // 文章的发表杂志
url: entry.url, // 文章的 URL
source: "PubMed", // 指示这些引用来自 PubMed
}));
// 打印或进一步处理 newReferences
console.log(newReferences);
dataString = rawData
.map((entry) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
}
//在对应的位置添加文献
const nearestNumber = getNumberBeforeCursor(quill);
dispatch(
addReferencesRedux({
references: newReferences,
position: nearestNumber,
})
);
} catch (error) {
toast.error(`AI写作出现错误(持续无法使用请切换deepseek模型): ${error}`, {
position: "top-center",
autoClose: 3000,
pauseOnHover: true,
});
Sentry.captureMessage(`AI写作出现错误: ${error}`, "error");
} finally {
// 通用的后处理逻辑
const updatedContent = quill!.root.innerHTML;
// 确保搜索到的论文不超过 3000 个字符
const trimmedMessage =
dataString.length > 3000 ? dataString.slice(0, 3000) : dataString;
//slate的方法
// const content = `需要完成的论文主题:${topic}, 搜索到的论文内容:${trimmedMessage},之前已经完成的内容上下文:${extractText(
// editorValue
// )}`;
const content = `之前用户已经完成的内容上下文:${getTextBeforeCursor(
quill,
500
)},搜索到的论文内容:${trimmedMessage},${topic},`;
await sendMessageToOpenAI(
content,
quill,
selectedModel,
apiKey,
upsreamUrl,
systemPrompt
);
setUserInput("");
// 重新获取更新后的内容并更新 Redux store
const updatedContent = quill.root.innerHTML;
dispatch(setEditorContent(updatedContent));
if (isVip) {
//在云端同步supabase
@ -538,17 +370,13 @@ const QEditor = ({ lng }) => {
paperNumberRedux
);
}
setOpenProgressBar(false);
setGenerateNumber(0); //总的已经生成的数量设置为0 以便下次使用
} catch (error) {
// console.error("Error fetching data:", error);
// 在处理错误后,再次抛出这个错误
throw new Error(`Paper2AI出现错误: ${error}`);
}
}
const handleStop = () => {
if (controller) {
controller.abort(); // 取消请求
setController(null); // 重置 controller 状态
}
};
return (
<div className="flex flex-col ">
<div id="Qtoolbar" className="space-y-2 flex justify-between">
@ -561,20 +389,19 @@ const QEditor = ({ lng }) => {
)}
/>
<button
onClick={() => handleAIAction(userInput, "write")}
onClick={handleAIWrite}
className="bg-gray-300 hover:bg-gray-400 text-black font-bold py-2 px-4 mr-2 rounded"
>
{t("AI写作")}
</button>
<button
onClick={() => handleAIAction(userInput, "paper2AI")}
onClick={() => paper2AI(userInput)}
className="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-2 px-4 mr-2 rounded"
>
{t("Paper2AI")}
</button>
{/* 论文网站 */}
<select
title={t("选择论文来源")}
value={selectedSource}
onChange={(e) => setSelectedSource(e.target.value)}
className=" border border-gray-300 bg-white py-2 px-3 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
@ -585,65 +412,26 @@ const QEditor = ({ lng }) => {
</select>
{/* AI模型 */}
<select
title={t("选择AI模型")}
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
className=" border border-gray-300 bg-white py-2 px-3 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500 "
className=" border border-gray-300 bg-white py-2 px-3 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
>
<option value="gpt-3.5-turbo">gpt-3.5-turbo</option>
<option value="gpt-4">gpt-4</option>
<option value="deepseek-chat">deepseek-chat</option>
<option value="commandr">commandr</option>
<option value="gemini-pro">gemini-pro</option>
<option value="mixtral-8x7b-32768">mixtral-8x7b-32768</option>
<option value="llama2-70b-4096">llama2-70b-4096</option>
</select>
{/* 进行几轮生成 */}
<input
type="number"
title={t("生成轮数")}
value={generatedPaperNumber}
onChange={handleGeneratedPaperNumberChange}
className="border border-gray-300 text-gray-700 text-sm p-1 rounded w-16"
/>
{/* 时间范围 */}
<input
type="number"
title={t("时间范围")}
value={timeRange}
onChange={(e) => setTimeRange(e.target.value)}
className="border border-gray-300 text-gray-700 text-sm p-1 rounded w-16"
/>
<button
onClick={() => formatTextInEditor(quill)} // 假设 updateIndex 是处理更新操作的函数
className="bg-gray-300 hover:bg-gray-400 text-black font-bold py-2 px-4 rounded"
title={t("更新文中的上标,使得数字顺序排列")}
>
{t("更新索引")}
</button>
</div>
{openProgressBar ? (
<ProgressDisplay
generatedPaperNumber={generatedPaperNumber!}
i={generateNumber}
/>
) : null}
<div>
<div id="editor"></div>
<ReferenceList editor={quill} lng={lng} />
<ExportDocx editor={quill} />
<ExportDocx editor={quill} lng={lng} />
</div>
{/* 停止生成的按钮只有在开始对话之后才会出现 */}
{openProgressBar ? (
<button
onClick={handleStop}
className="fixed bottom-4 left-4 bg-red-500 hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50 active:bg-red-700 text-white font-bold py-2 px-4 rounded transition ease-in-out duration-150 shadow-lg hover:shadow-xl"
>
{t("停止生成")}
</button>
) : null}
<ToastContainer />
</div>
);
};

View File

@ -1,14 +1,8 @@
"use client";
import dynamic from "next/dynamic";
import ReduxProvider from "@/app/store/ReduxProvider";
import LoadingIndicator from "@/components/LoadingIndicator"; // 确保路径正确
// import QEditor from "@/components/QuillEditor";
// 动态导入 QuillEditor 组件,禁用 SSR
const QEditor = dynamic(() => import("@/components/QuillEditor"), {
ssr: false,
loading: () => <LoadingIndicator />,
});
import ReduxProvider from "@/app/store/ReduxProvider";
import QEditor from "@/components/QuillEditor";
export default function QuillWrapper({ lng }) {
return (
<ReduxProvider>

View File

@ -0,0 +1,132 @@
"use client";
import React, { useState, useEffect } from "react";
import ReactQuill from 'react-quill';
import "quill/dist/quill.snow.css";
// 一些工具函数导入
import getArxivPapers from "./GetArxiv";
import sendMessageToOpenAI from "./chatAI";
const QEditor = () => {
const [quill, setQuill] = useState(null);
const [userInput, setUserInput] = useState("");
const [content, setContent] = useState("");
// 处理内容变化
const handleContentChange = (content) => {
setContent(content);
convertToSuperscript();
};
function convertToSuperscript() {
const text = quill.getText();
const regex = /\[\d+\]/g; // 正则表达式匹配 "[数字]" 格式
let match;
while ((match = regex.exec(text)) !== null) {
const startIndex = match.index;
const length = match[0].length;
// 应用上标格式
quill.formatText(startIndex, length, { script: "super" });
// 重置格式(如果需要)
if (startIndex + length < text.length) {
quill.formatText(startIndex + length, 1, "script", false);
}
}
}
// 处理按钮点击事件来插入文本
const handleButtonClick = () => {
if (quill) {
quill.insertText(quill.getLength(), "Hello, World!");
}
};
// 处理用户输入变化
const handleInputChange = (event) => {
setUserInput(event.target.value);
};
const paper2AI = (topic: string) => {
getArxivPapers(topic).then((rawData) => {
// 将每篇文章的信息转换为字符串
const dataString = rawData
.map((entry) => {
return `ID: ${entry.id}\nPublished: ${entry.published}\nTitle: ${entry.title}\nSummary: ${entry.summary}\n\n`;
})
.join("");
// 将处理后的字符串插入到编辑器中
sendMessageToOpenAI(dataString, quill, quill.getText(), topic);
});
};
// 插入论文信息
const insertPapers = async (topic: string) => {
const rawData = await getArxivPapers(topic);
const dataString = rawData
.map((entry) => {
return `ID: ${entry.id}\nPublished: ${entry.published}\nTitle: ${entry.title}\nSummary: ${entry.summary}\n\n`;
})
.join("");
quill.insertText(quill.getLength(), dataString);
};
return (
<div>
<div className="space-y-2">
<button
onClick={handleButtonClick}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
>
Insert Text
</button>
<input
type="text"
value={userInput}
onChange={handleInputChange}
className="shadow appearance-none border rounded py-2 px-3 text-grey-darker"
/>
{/*<button
onClick={handleAIClick}
className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
>
Insert AI Text
</button>*/}
<button
onClick={() => insertPapers("gnn")}
className="bg-indigo-500 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded"
>
Insert Papers
</button>
<button
onClick={() => paper2AI("gnn")}
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
>
Paper2AI
</button>
</div>
<div
id="editor"
style={{
height: "500px",
width: "600px",
minHeight: "150px", // 注意驼峰命名法
maxHeight: "500px",
overflowY: "auto", // overflow-y -> overflowY
border: "1px solid #ccc",
padding: "10px",
}}
></div>
</div>
);
};
export default QEditor;

View File

@ -1,548 +0,0 @@
"use client";
import React, {
useState,
useEffect,
useRef,
useCallback,
useMemo,
} from "react";
import "react-quill/dist/quill.snow.css"; // 导入Quill的snow主题样式
import { useLocalStorage } from "react-use";
import Link from "next/link";
import dynamic from "next/dynamic";
// 一些工具函数导入
import getArxivPapers from "./GetArxiv";
import getSemanticPapers from "./GetSemantic";
import { fetchPubMedData } from "./GetPubMed ";
import { getAI, sendMessageToOpenAI } from "./chatAI";
import {
getTextBeforeCursor,
convertToSuperscript,
removeSpecialCharacters,
formatTextInEditor,
getNumberBeforeCursor,
formatJournalReference,
} from "@/utils/others/quillutils";
import { evaluateTopicMatch } from "@/utils/others/aiutils";
//组件
import ExportDocx from "./Export";
import ReferenceList from "./ReferenceList";
import ProgressDisplay from "./ProgressBar";
//redux
import { useAppDispatch, useAppSelector } from "@/app/store";
import {
addReferencesRedux,
setEditorContent,
} from "@/app/store/slices/authSlice";
import { setContentUpdatedFromNetwork } from "@/app/store/slices/stateSlice";
//类型声明
import { Reference } from "@/utils/global";
//supabase
import { createClient } from "@/utils/supabase/client";
import {
getUserPapers,
getUser,
submitPaper,
} from "@/utils/supabase/supabaseutils";
//debounce
import { debounce } from "lodash";
//i18n
import { useTranslation } from "@/app/i18n/client";
const toolbarOptions = [
["bold", "italic", "underline", "strike"], // 加粗、斜体、下划线和删除线
["blockquote", "code-block"], // 引用和代码块
[{ header: 1 }, { header: 2 }], // 标题
[{ list: "ordered" }, { list: "bullet" }], // 列表
[{ script: "sub" }, { script: "super" }], // 上标/下标
[{ indent: "-1" }, { indent: "+1" }], // 缩进
[{ direction: "rtl" }], // 文字方向
[{ size: ["small", false, "large", "huge"] }], // 字体大小
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }], // 字体颜色和背景色
[{ font: [] }], // 字体
[{ align: [] }], // 对齐方式
["clean"], // 清除格式按钮
];
const QEditor = ({ lng }) => {
//quill初始化
const ReactQuill = useMemo(
() => dynamic(() => import("react-quill"), { ssr: false }),
[]
);
//i18n
const { t } = useTranslation(lng);
//读取redux中的API key
const apiKey = useAppSelector((state: any) => state.auth.apiKey);
const upsreamUrl = useAppSelector((state: any) => state.auth.upsreamUrl);
const isJumpToReference = useAppSelector(
(state) => state.state.isJumpToReference
);
const isEvaluateTopicMatch = useAppSelector(
(state) => state.state.isEvaluateTopicMatch
);
const [quill, setQuill] = useState<any>(null);
const contentUpdatedFromNetwork = useAppSelector(
(state) => state.state.contentUpdatedFromNetwork
);
//vip状态
const isVip = useAppSelector((state) => state.state.isVip);
//询问ai用户输入
const [userInput, setUserInput] = useState("");
//quill编辑器鼠标位置
const [cursorPosition, setCursorPosition] = useLocalStorage<number | null>(
"光标位置",
null
);
//
// 初始化 Quill 编辑器
const isMounted = useRef(false);
const editor = useRef<any>(null);
// 选择论文来源
const [selectedSource, setSelectedSource] = useLocalStorage(
"学术引擎",
"semanticScholar"
); // 默认选项
//选择语言模型
const [selectedModel, setSelectedModel] = useLocalStorage(
"gpt语言模型",
"gpt-4"
); // 默认选项
const [generatedPaperNumber, setGeneratedPaperNumber] = useLocalStorage(
"生成次数",
1
); // 初始值设为1
const [generateNumber, setGenerateNumber] = useState(0); //当前任务的进行数
const [openProgressBar, setOpenProgressBar] = useState(false);
//redux
const dispatch = useAppDispatch();
const references = useAppSelector((state) => state.auth.referencesRedux);
const editorContent = useAppSelector((state) => state.auth.editorContent); // 从 Redux store 中获取编辑器内容
const systemPrompt = useAppSelector((state) => state.auth.systemPrompt);
const paperNumberRedux = useAppSelector(
(state) => state.state.paperNumberRedux
);
//quill配置
const modules = {
toolbar: toolbarOptions,
history: {
delay: 2000,
maxStack: 500, // 调整撤销和重做堆栈的大小
userOnly: false,
},
};
// 监听selection-change事件
const handleSelectionChange = useCallback(
(range: any) => {
if (range) {
// 如果有选区或光标位置变化,则更新光标位置
setCursorPosition(range.index);
} else {
// 没有选区或光标不在编辑器内
console.log("No selection or cursor in the editor.");
}
},
[setCursorPosition]
); // 把setCursorPosition添加到依赖数组中
//supabase
const supabase = createClient();
useEffect(() => {
if (!isMounted.current) {
if (editorContent) {
editor.current.getEditor().root.innerHTML = editorContent;
}
isMounted.current = true;
setQuill(editor.current.getEditor());
// 添加点击事件监听器
const handleEditorClick = (e) => {
if (isJumpToReference) {
const range = quill!.getSelection();
if (range && range.length === 0 && quill) {
const [leaf, offset] = quill.getLeaf(range.index);
if (leaf.text) {
const textWithoutSpaces = leaf.text.replace(/\s+/g, ""); // 去掉所有空格
if (/^\[\d+\]$/.test(textWithoutSpaces)) {
console.log("点击了引用", textWithoutSpaces);
try {
document.getElementById(textWithoutSpaces)!.scrollIntoView();
} catch (e) {
console.log("没有找到对应的引用");
}
}
}
} else {
console.log("No editor in click.");
}
}
};
editor.current
?.getEditor()
.root.addEventListener("click", handleEditorClick);
// 清理函数
// return () => {
// editor.current!.root.removeEventListener("click", handleEditorClick);
// };
}
}, []);
// 监听editorContent变化(redux的变量)并使用Quill API更新内容
useEffect(() => {
if (quill) {
if (editorContent) {
if (contentUpdatedFromNetwork) {
// 清空当前内容
quill.setContents([]);
// 插入新内容
quill.clipboard.dangerouslyPasteHTML(editorContent);
// 重置标志
dispatch(setContentUpdatedFromNetwork(false));
} else {
console.log("No content updated from network in useEffect.");
}
} else {
console.log("No editorContent to update in useEffect.");
}
} else {
console.log("No quill to update in useEffect.");
}
}, [editorContent, contentUpdatedFromNetwork]);
const handleTextChange = debounce(async function (delta, oldDelta, source) {
if (source === "user") {
// 获取编辑器内容
const content = quill!.root.innerHTML; // 或 quill.getText(),或 quill.getContents()
dispatch(setEditorContent(content)); // 更新 Redux store
//在云端同步supabase
// console.log("paperNumberRedux in quill", paperNumberRedux);
if (isVip) {
const data = await submitPaper(
supabase,
content,
undefined,
paperNumberRedux
);
}
setTimeout(() => {
convertToSuperscript(quill!);
}, 0); // 延迟 0 毫秒,即将函数放入事件队列的下一个循环中执行,不然就会因为在改变文字触发整个函数时修改文本内容造成无法找到光标位置
}
}, 1000); // 这里的 1000 是防抖延迟时间,单位为毫秒
useEffect(() => {
if (quill) {
// 设置监听器以处理内容变化
quill.on("text-change", handleTextChange);
// 清理函数
return () => {
quill.off("text-change", handleTextChange);
};
}
}, [quill, dispatch, paperNumberRedux]);
// 处理用户输入变化
const handleInputChange = (event: any) => {
setUserInput(event.target.value);
};
// 处理输入generatedPaperNumber变化的函数
const handleGeneratedPaperNumberChange = (event: any) => {
const newValue = parseInt(event.target.value, 10);
setGeneratedPaperNumber(newValue);
};
// 处理AI写作
const handleAIWrite = async () => {
quill!.setSelection(cursorPosition!, 0); // 将光标移动到原来的位置
const prompt = "请帮助用户完成论文写作,使用用户所说的语言完成";
await sendMessageToOpenAI(
userInput,
quill!,
selectedModel!,
apiKey,
upsreamUrl,
prompt,
cursorPosition!
);
// 清空input内容
setUserInput("");
// 重新获取更新后的内容并更新 Redux store
const updatedContent = quill!.root.innerHTML;
dispatch(setEditorContent(updatedContent));
};
// 处理paper2AI
async function paper2AI(topic: string) {
quill!.setSelection(cursorPosition!, 0); // 将光标移动到原来的位置
let offset = -1;
if (generatedPaperNumber != 1) offset = 0; //如果生成的数量不为1则从0开始
setOpenProgressBar(true); //开启进度条
//如果说要评估主题是否匹配的话,就要多获取一些文献
let limit = 2;
if (isEvaluateTopicMatch) {
limit = 4;
}
for (let i = 0; i < generatedPaperNumber!; i++) {
try {
if (!topic) {
//使用ai提取当前要请求的论文主题
const prompt =
"As a topic extraction assistant, you can help me extract the current discussion of the paper topic, I will enter the content of the paper, you extract the paper topic , no more than two, Hyphenated query terms yield no matches (replace it with space to find matches) return format is: topic1 topic2";
const userMessage = getTextBeforeCursor(quill!, 2000);
topic = await getAI(
userMessage,
prompt,
apiKey,
upsreamUrl,
selectedModel!
);
console.log("topic in AI before removeSpecialCharacters", topic);
topic = removeSpecialCharacters(topic);
topic = topic.split(" ").slice(0, 2).join(" ");
//如果超过十个字符就截断
if (topic.length > 10) {
topic = topic.slice(0, 10);
}
}
console.log("topic in AI", topic);
let rawData, dataString, newReferences;
if (selectedSource === "arxiv") {
rawData = await getArxivPapers(topic, limit, offset);
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic
);
rawData = relevantPapers;
}
console.log("arxiv rawdata:", rawData);
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry: any) => ({
url: entry.id,
title: entry.title,
year: entry.published,
author: entry.authors?.slice(0, 3).join(", "),
}));
dataString = rawData
.map((entry: any) => {
return `ID: ${entry.id}\nTime: ${entry.published}\nTitle: ${entry.title}\nSummary: ${entry.summary}\n\n`;
})
.join("");
} else if (selectedSource === "semanticScholar") {
rawData = await getSemanticPapers(topic, "2015-2023", offset, limit);
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic
);
rawData = relevantPapers;
}
// 将 rawData 转换为引用数组
newReferences = rawData.map((entry: any) => ({
url: entry.url,
title: entry.title,
year: entry.year,
author: entry.authors?.slice(0, 3).join(", "),
venue: entry.venue,
journal: formatJournalReference(entry),
}));
dataString = rawData
.map((entry: any) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
} else if (selectedSource === "pubmed") {
rawData = await fetchPubMedData(topic, 2020, offset, limit);
if (!rawData) {
throw new Error("未搜索到文献 from PubMed.");
}
//判断返回的文献是否跟用户输入的主题相关
if (isEvaluateTopicMatch) {
const { relevantPapers, nonRelevantPapers } =
await evaluateTopicMatch(
rawData,
apiKey,
upsreamUrl,
selectedModel!,
topic
);
rawData = relevantPapers;
}
newReferences = rawData.map((entry: any) => ({
id: entry.id, // 文章的 PubMed ID
title: entry.title, // 文章的标题
abstract: entry.abstract, // 文章的摘要
author: entry.authors?.slice(0, 3).join(", "), // 文章的作者列表,假设为字符串数组
year: entry.year, // 文章的发表日期
journal: entry.journal, // 文章的发表杂志
url: entry.url, // 文章的 URL
source: "PubMed", // 指示这些引用来自 PubMed
}));
// 打印 newReferences
console.log(newReferences);
dataString = rawData
.map((entry: any) => {
return `Time: ${entry.year}\nTitle: ${entry.title}\nSummary: ${entry.abstract}\n\n`;
})
.join("");
}
// 确保搜索到的论文不超过 3000 个字符
const trimmedMessage =
dataString.length > 3000 ? dataString.slice(0, 3000) : dataString;
//slate的方法
// const content = `需要完成的论文主题:${topic}, 搜索到的论文内容:${trimmedMessage},之前已经完成的内容上下文:${extractText(
// editorValue
// )}`;
const content = `之前用户已经完成的内容上下文:${getTextBeforeCursor(
quill!,
900
)},搜索到的论文内容:${trimmedMessage},${topic},`;
await sendMessageToOpenAI(
content,
quill!,
selectedModel!,
apiKey,
upsreamUrl,
systemPrompt,
cursorPosition!
);
setUserInput("");
// 重新获取更新后的内容并更新 Redux store
const updatedContent = quill!.root.innerHTML;
dispatch(setEditorContent(updatedContent));
//在对应的位置添加文献
const nearestNumber = getNumberBeforeCursor(quill!);
dispatch(
addReferencesRedux({
references: newReferences,
position: nearestNumber,
})
);
if (isVip) {
//在云端同步supabase
const data = await submitPaper(
supabase,
updatedContent,
references,
paperNumberRedux
);
}
//修改offset使得按照接下来的顺序进行获取文献
offset += 2;
setGenerateNumber(i + 1);
} catch (error) {
// console.error("Error fetching data:", error);
// 在处理错误后,再次抛出这个错误
throw new Error(`Paper2AI出现错误: ${error}`);
}
}
setOpenProgressBar(false);
setGenerateNumber(0); //总的已经生成的数量
}
return (
<div className="flex flex-col ">
<div id="Qtoolbar" className="space-y-2 flex justify-between">
<textarea
value={userInput}
onChange={handleInputChange}
className="textarea-focus-expand flex-grow shadow appearance-none border rounded py-2 px-3 mr-2 text-grey-darker"
placeholder={t(
"点击AI写作就是正常的对话交流点击寻找文献会根据输入的主题词去寻找对应论文"
)}
/>
<button
onClick={handleAIWrite}
className="bg-gray-300 hover:bg-gray-400 text-black font-bold py-2 px-4 mr-2 rounded"
>
{t("AI写作")}
</button>
<button
onClick={() => paper2AI(userInput)}
className="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-2 px-4 mr-2 rounded"
>
{t("Paper2AI")}
</button>
{/* 论文网站 */}
<select
value={selectedSource}
onChange={(e) => setSelectedSource(e.target.value)}
className=" border border-gray-300 bg-white py-2 px-3 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
>
<option value="arxiv">arxiv</option>
<option value="semanticScholar">semantic scholar</option>
<option value="pubmed">pubmed</option>
</select>
{/* AI模型 */}
<select
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
className=" border border-gray-300 bg-white py-2 px-3 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500 "
>
<option value="gpt-3.5-turbo">gpt-3.5-turbo</option>
<option value="gpt-4">gpt-4</option>
<option value="deepseek-chat">deepseek-chat</option>
</select>
<input
type="number"
value={generatedPaperNumber}
onChange={handleGeneratedPaperNumberChange}
className="border border-gray-300 text-gray-700 text-sm p-1 rounded w-16"
/>
<button
onClick={() => formatTextInEditor(quill)} // 假设 updateIndex 是处理更新操作的函数
className="bg-gray-300 hover:bg-gray-400 text-black font-bold py-2 px-4 rounded"
>
{t("更新索引")}
</button>
</div>
{openProgressBar ? (
<ProgressDisplay
generatedPaperNumber={generatedPaperNumber!}
i={generateNumber}
/>
) : null}
<div>
<ReactQuill
id="editor"
ref={editor}
modules={modules}
theme="snow"
onChangeSelection={handleSelectionChange}
/>
<ReferenceList editor={quill} lng={lng} />
<ExportDocx editor={quill} />
</div>
</div>
);
};
export default QEditor;

View File

@ -1,12 +1,10 @@
import React, { useState, useEffect } from "react";
import { useLocalStorage } from "react-use";
import React, { useState } from "react";
import { Reference } from "@/utils/global";
import {
copyToClipboard,
getFullReference,
renderCitation,
getAllFullReferences,
formatReferenceForCopy,
formatAllReferencesForCopy,
delteIndexUpdateBracketNumbersInDeltaKeepSelection,
} from "@/utils/others/quillutils";
//删除文献按钮
@ -19,9 +17,7 @@ import {
removeReferenceRedux,
clearReferencesRedux,
swapReferencesRedux,
setReferencesRedux,
} from "@/app/store/slices/authSlice";
import { setCitationStyle } from "@/app/store/slices/stateSlice";
//supabase
import { submitPaper } from "@/utils/supabase/supabaseutils";
import { createClient } from "@/utils/supabase/client";
@ -31,22 +27,10 @@ type ReferenceListProps = {
editor: any;
lng: string;
};
//引用转换
import Cite from "citation-js";
const citationStyles = [
{ name: "中文", template: "custom-chinese" }, // 假设你有一个自定义的“中文”格式
{ name: "APA", template: "apa" },
{ name: "MLA", template: "mla" },
{ name: "Chicago", template: "chicago" },
{ name: "Harvard", template: "harvard" },
{ name: "Vancouver", template: "vancouver" },
{ name: "IEEE", template: "ieee" },
];
function ReferenceList({ editor, lng }: ReferenceListProps) {
//i18n
const { t } = useTranslation(lng);
//自定义文献
const [newTitle, setNewTitle] = useState("");
const [newAuthor, setNewAuthor] = useState("");
const [newYear, setNewYear] = useState("");
@ -59,7 +43,6 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
(state) => state.state.paperNumberRedux
);
const isVip = useAppSelector((state) => state.state.isVip);
const citationStyle = useAppSelector((state) => state.state.citationStyle);
//supabase
const supabase = createClient();
@ -112,44 +95,27 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
}
}, [references]);
async function generateCitation(doi, style) {
try {
const citation = await Cite.async(doi);
const output = citation.format("bibliography", {
format: "text",
template: style,
lang: "en-US",
});
return output;
} catch (error) {
console.error("Error generating citation:", error);
return ""; // Return an empty string in case of error
function formatReference(reference: Reference) {
if (reference.journal) {
return `[J]. ${reference.journal}. `;
} else if (reference.journalReference) {
return `[J]. ${reference.journalReference}`;
} else {
return `${reference.venue}, ${reference.year}.`;
}
}
useEffect(() => {
const fetchCitations = async () => {
const updatedReferences = await Promise.all(
references.map(async (ref) => {
// 检查是否已经有当前风格的引用
if (!ref[citationStyle]) {
// 如果没有,则生成新的引用
const citationText = await generateCitation(ref.doi, citationStyle);
return { ...ref, [citationStyle]: citationText }; // 添加新的引用到对象
}
return ref; // 如果已有引用,则不做改变
})
);
dispatch(setReferencesRedux(updatedReferences));
};
fetchCitations();
}, [citationStyle]);
const handleStyleChange = (event) => {
dispatch(setCitationStyle(event.target.value));
};
function getFullReference(reference: Reference) {
let fullReference = `${reference.author}. ${reference.title}`;
fullReference += formatReference(reference);
return fullReference;
}
function getAllFullReferences(references: Reference[]) {
return references
.map((reference, index) => {
return `[${index + 1}] ${getFullReference(reference)}`;
})
.join("\n");
}
return (
<div className=" mx-auto p-4">
{/* 引用列表显示区域 */}
@ -161,9 +127,7 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
<li key={index} className="mb-3 p-2 border-b">
{/* 显示序号 */}
<span className="font-bold mr-2">[{index + 1}].</span>
{/* {getFullReference(reference)} */}
{/* 根据当前风格渲染引用 */}
{renderCitation(reference, citationStyle)}
{getFullReference(reference)}
{reference.url && (
<a
href={reference.url}
@ -190,9 +154,7 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
</button>
<button
className="bg-gray-500 hover:bg-gray-700 text-white font-bold py-1 px-2 ml-2 rounded"
onClick={() =>
copyToClipboard(renderCitation(reference, citationStyle))
}
onClick={() => copyToClipboard(getFullReference(reference))}
>
{t("复制")}
</button>
@ -277,9 +239,7 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
<button
className="bg-gray-300 hover:bg-gray-400 text-black font-bold py-2 px-4 rounded "
type="button"
onClick={() =>
copyToClipboard(getAllFullReferences(references, citationStyle))
}
onClick={() => copyToClipboard(getAllFullReferences(references))}
>
{t("复制所有引用")}
</button>
@ -291,29 +251,6 @@ function ReferenceList({ editor, lng }: ReferenceListProps) {
>
{t("删除所有引用")}
</button>
{/* 下拉框用于更改引用风格 */}
<div className="mt-4">
<label
htmlFor="citation-style"
className="block text-sm font-medium text-gray-700"
>
:
</label>
<select
id="citation-style"
className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
value={citationStyle}
onChange={handleStyleChange}
>
<option value="apa">APA</option>
<option value="mla">MLA</option>
<option value="chicago">Chicago</option>
<option value="harvard">Harvard</option>
<option value="vancouver">Vancouver</option>
<option value="ieee">IEEE</option>
<option value="custom-chinese"></option>
</select>
</div>
</div>
</div>
</form>

View File

@ -7,63 +7,31 @@ import {
setUpsreamUrl,
setSystemPrompt,
} from "@/app/store/slices/authSlice";
import {
setIsJumpToReference,
setIsEvaluateTopicMatch,
} from "@/app/store/slices/stateSlice";
import { setIsJumpToReference } from "@/app/store/slices/stateSlice";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import Link from "next/link";
import { useLocalStorage } from "react-use";
import { useTranslation } from "@/app/i18n/client";
import { useEffect } from "react";
//公告
// import { ToastContainer, toast } from "react-toastify";
// import "react-toastify/dist/ReactToastify.css";
const Settings = ({ lng }: { lng: string }) => {
//i18n
const { t } = useTranslation(lng);
const CONFIG_OPTIONS = [
// {
// name: t("configurations.蒙恬大将军"),
// apiKey: "sk-jokVJ90l5Swxr5dt2f3b0988C8A442A69f97Ee4eAf7aDcF4",
// upstreamUrl: "https://freeapi.iil.im",
// },
// {
// name: t("configurations.coze"),
// apiKey: "MTIwMjE2ODMyODA1NTk1MTM2MA",
// upstreamUrl: "https://coze.paperai.life",
// },
{
name: t("configurations.cocopilot-gpt4"),
apiKey: "_pXVxLPBzcvCjSvG0Mv4K7G9ffw3xsM2ZKolZ",
upstreamUrl: "https://proxy.cocopilot.org",
},
{
name: t("configurations.deepseek-chat"),
apiKey: "sk-ffe19ebe9fa44d00884330ff1c18cf82",
upstreamUrl: "https://api.deepseek.com",
},
// {
// name: t("configurations.caifree"),
// apiKey: "sk-MaEuOo9qIeWKK3PRCdCb9b3d47E64e36Ad6022724b780592",
// upstreamUrl: "https://one.caifree.com",
// },
// {
// name: t("configurations.官网反代"),
// apiKey: "3b73ec02-3255-4b27-a202-42ab9a6e85ba",
// upstreamUrl: "https://plus.liuweiqing.top",
// },
// {
// name: t("configurations.vv佬"),
// apiKey: "nk-23118",
// upstreamUrl: "https://cocopilot-pool.aivvm.com",
// },
// {
// name: t("configurations.linuxdo"),
// apiKey: "nk-2311676378",
// upstreamUrl: "https://chat.flss.world/api/openai",
// },
{
name: t("configurations.oneapi"),
apiKey: "sk-GHuPUV6ERD8wVmmr36FeB8D809D34d93Bb857c009f6aF9Fe",
upstreamUrl: "https://one.paperai.life",
name: t("configurations.caifree"),
apiKey: "sk-aiHrrRLYUUelHstX69E9484509254dBf92061d6744FfFaD1",
upstreamUrl: "https://one.caifree.com",
},
{
name: t("configurations.custom"),
@ -71,7 +39,6 @@ const Settings = ({ lng }: { lng: string }) => {
upstreamUrl: "",
},
];
//https://freeapi.iil.im sk-GdUOBeCCCpeB16G877C8C62b849c4653A561550bEb79Fe7e
//redux
const dispatch = useAppDispatch();
const apiKey = useAppSelector((state) => state.auth.apiKey);
@ -80,29 +47,15 @@ const Settings = ({ lng }: { lng: string }) => {
const isJumpToReference = useAppSelector(
(state) => state.state.isJumpToReference
);
const isEvaluateTopicMatch = useAppSelector(
(state) => state.state.isEvaluateTopicMatch
);
//state
const [userConfigNumber, setUserConfigNumber] = useLocalStorage(
"userConfigNumber",
"2"
);
const toggleSwitch = (currentState: any, setState: any) => {
setState(!currentState);
};
// useEffect(() => {
// toast("这是一个公告消息!", {
// position: "top-center",
// autoClose: 5000, // 持续时间
// hideProgressBar: false,
// closeOnClick: true,
// pauseOnHover: true,
// draggable: true,
// progress: undefined,
// });
// }, []);
const toggleSwitch = () => {
dispatch(setIsJumpToReference(!isJumpToReference));
};
return (
<div className="max-w-md rounded overflow-hidden shadow-lg bg-blue-gray-100 z-1000 mx-auto ">
<h1 className="font-bold text-3xl">settings</h1>
@ -152,7 +105,6 @@ const Settings = ({ lng }: { lng: string }) => {
<input
id="api-key"
type="password"
autoComplete="off"
value={apiKey}
onChange={(event) => dispatch(setApiKey(event.target.value))}
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
@ -195,11 +147,7 @@ const Settings = ({ lng }: { lng: string }) => {
type="checkbox"
className="sr-only peer"
checked={isJumpToReference}
onChange={() =>
toggleSwitch(isJumpToReference, (value: any) =>
dispatch(setIsJumpToReference(value))
)
}
onChange={toggleSwitch}
/>
<div className="w-10 h-4 bg-gray-200 rounded-full peer-checked:bg-blue-600 peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 transition-colors ease-in-out duration-200"></div>
<span
@ -209,26 +157,6 @@ const Settings = ({ lng }: { lng: string }) => {
></span>
{t("鼠标点击段落中的上标跳转到文献引用?")}
</label>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={isEvaluateTopicMatch}
onChange={() =>
toggleSwitch(isEvaluateTopicMatch, (value: any) =>
dispatch(setIsEvaluateTopicMatch(value))
)
}
/>
<div className="w-10 h-4 bg-gray-200 rounded-full peer-checked:bg-blue-600 peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 transition-colors ease-in-out duration-200"></div>
<span
className={`absolute block bg-white w-3 h-3 rounded-full transition ease-in-out duration-200 transform ${
isJumpToReference ? "translate-x-6" : "translate-x-1"
} -translate-y-1/2 top-1/2`}
></span>
{t("是否检查文献与主题相关性(如果不相关则不会传给AI引用)")}
</label>
{/* <ToastContainer /> */}
</div>
);
};

View File

@ -1,70 +0,0 @@
// components/SignInWithProvider.tsx
"use client";
import { insertUserProfile } from "@/utils/supabase/supabaseutils";
import { createClient } from "@/utils/supabase/client";
import { useEffect } from "react";
import * as Sentry from "@sentry/react";
import { FaGithub, FaGoogle } from "react-icons/fa";
export function SignInWithProvider({ provider, redirectTo }) {
useEffect(() => {
const supabase = createClient();
const { data } = supabase.auth.onAuthStateChange(async (event, session) => {
if (session && session.provider_token) {
// 用户登录成功,执行后续操作
await insertUserProfile(session.user, supabase);
Sentry.captureMessage(`${provider}登录成功`, "info");
console.log(`${provider}登录成功`);
} else {
Sentry.captureMessage(
`${provider}登录中的其它的event${event}`,
"warning"
);
console.log(`${provider}登录中的其它的event`, event);
}
});
return () => data.subscription.unsubscribe();
}, [provider]);
function getProviderIcon(provider) {
switch (provider) {
case "github":
return <FaGithub />;
case "google":
return <FaGoogle />;
default:
return null;
}
}
const signIn = async () => {
const supabase = createClient();
const { data, error } = await supabase.auth.signInWithOAuth({
provider: provider,
options: {
// redirectTo: redirectTo,
queryParams: {
access_type: "offline",
prompt: "consent",
},
},
});
if (error) {
console.error(`${provider} authentication failed:`, error.message);
}
//profiles表 插入用户信息
await insertUserProfile(data, supabase);
};
return (
<button
onClick={signIn}
className="bg-black text-white rounded-md px-4 py-2 mb-2 flex items-center justify-center gap-2 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white transition ease-in duration-200 w-full"
>
{getProviderIcon(provider)} Sign In with{" "}
{provider.charAt(0).toUpperCase() + provider.slice(1)}
</button>
);
}

View File

@ -1,9 +1,9 @@
import Quill from "quill";
import { Transforms } from "slate";
import { Editor } from "slate";
import { extractText } from "@/utils/others/slateutils";
import {
updateBracketNumbersInDeltaKeepSelection,
convertToSuperscript,
deleteSameBracketNumber,
} from "@/utils/others/quillutils";
//redux不能在普通函数使用
@ -20,14 +20,11 @@ function isValidApiKey(apiKey: string) {
const sendMessageToOpenAI = async (
content: string,
editor: Quill | null,
selectedModel: string,
editor: Editor,
selectedModel: "gpt3.5",
apiKey: string,
upsreamUrl: string,
prompt: string,
cursorPosition: number | null,
useEditorFlag = true, // 新增的标志,用于决定操作
signal: AbortSignal
prompt?: string
) => {
//识别应该使用的模型
let model = selectedModel;
@ -35,7 +32,6 @@ const sendMessageToOpenAI = async (
// 设置API请求参数
const requestOptions = {
method: "POST",
signal: signal,
headers: {
"Content-Type": "application/json",
// "Upstream-Url": upsreamUrl,
@ -47,7 +43,7 @@ const sendMessageToOpenAI = async (
},
body: JSON.stringify({
model: model,
stream: useEditorFlag, // 根据标志确定是否使用streaming
stream: true,
messages: [
{
role: "system",
@ -58,7 +54,7 @@ const sendMessageToOpenAI = async (
2.使 [1]***[1]*
3.
4.
5.使
5.使,
6.
...[1],...[2]`,
@ -74,59 +70,79 @@ const sendMessageToOpenAI = async (
// 发送API请求
let response;
let responseClone = null; // 用于保存响应内容的变量
try {
response = await fetch(
(upsreamUrl || process.env.NEXT_PUBLIC_AI_URL) + "/v1/chat/completions",
requestOptions
);
// 检查响应状态码是否为429
if (response.status === 429) {
// 可以在这里处理429错误例如通过UI通知用户
throw new Error("请求过于频繁,请稍后再试。");
} else if (!response.ok) {
// 处理其他类型的HTTP错误
throw new Error(`HTTP错误状态码${response.status}`);
if (!response.ok || !response.body) {
throw new Error("");
}
// 克隆响应以备后用
responseClone = response.clone();
if (useEditorFlag && editor && cursorPosition !== null) {
const reader = response.body!.getReader();
const decoder = new TextDecoder();
//开始前先进行换行
// editor.focus();
editor.insertText(editor.getSelection(true).index, "\n");
await processResult(reader, decoder, editor);
//搜索是否有相同的括号编号,如果有相同的则删除到只剩一个
convertToSuperscript(editor);
deleteSameBracketNumber(editor, cursorPosition);
updateBracketNumbersInDeltaKeepSelection(editor);
} else {
// 直接返回结果的逻辑
const data = await response.json();
const content = data.choices[0].message.content;
return content; // 或根据需要处理并返回数据
}
} catch (error: any) {
if (error.name === "AbortError") {
console.log("Fetch operation was aborted");
//这里不用产生报错因为是手动停止
return;
}
console.error("Error:", error);
const reader = response.body.getReader();
const decoder = new TextDecoder();
//开始前先进行换行
// editor.focus();
editor.insertText(editor.getSelection(true).index, "\n");
await processResult(reader, decoder, editor);
// 根据是否成功读取响应体来抛出错误
if (responseClone) {
const textResponse = await responseClone.text(); // 从克隆的响应中读取数据
throw new Error(
`请求发生错误: ${error.message}, Response: ${textResponse}`
);
} else {
throw new Error(`请求发生错误: ${error.message}`);
convertToSuperscript(editor);
updateBracketNumbersInDeltaKeepSelection(editor);
} catch (error) {
console.error("Error:", error);
// 如果有响应,返回响应的原始内容
if (response) {
const rawResponse = await response.text();
throw new Error(`请求发生错误: ${error}, Response: ${rawResponse}`);
}
// 如果没有响应,只抛出错误
throw error;
}
};
const getTopicFromAI = async (
userMessage: string,
prompt: string,
apiKey: string
) => {
// 设置API请求参数
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization:
"Bearer " +
(isValidApiKey(apiKey)
? apiKey
: process.env.NEXT_PUBLIC_OPENAI_API_KEY),
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
stream: false,
messages: [
{
role: "system",
content: prompt,
},
{
role: "user",
content: userMessage,
},
],
}),
};
const response = await fetch(
process.env.NEXT_PUBLIC_AI_URL + "/v1/chat/completions",
requestOptions
);
const data = await response.json();
const topic = data.choices[0].message.content;
return topic; // 获取并返回回复
};
// 给getTopicFromAI函数创建别名
// export const getFromAI = sendMessageToOpenAI;
async function processResult(reader, decoder, editor) {
let buffer = "";
while (true) {
@ -158,8 +174,8 @@ async function processResult(reader, decoder, editor) {
// 处理 dataObject 中的 content
if (dataObject.choices && dataObject.choices.length > 0) {
let content =
dataObject.choices[0].delta?.content ??
dataObject.choices[0].message?.content;
dataObject.choices[0].message?.content ||
dataObject.choices[0].delta?.content;
if (content) {
// 在当前光标位置插入文本
// editor.focus();
@ -168,6 +184,13 @@ async function processResult(reader, decoder, editor) {
}
}
} catch (error) {
// console.error(
// "there is a error in parse JSON object:",
// jsonStr,
// "error reason",
// error
// );
// break;
throw new Error(`
there is a error in parse JSON object: ${jsonStr},
error reason: ${error}`);
@ -179,4 +202,4 @@ async function processResult(reader, decoder, editor) {
}
}
export { sendMessageToOpenAI };
export { getTopicFromAI, sendMessageToOpenAI };

View File

@ -1,11 +0,0 @@
version: "3.8" # 使用 Docker Compose 文件版本 3.8,根据需要可以更改
services:
paperai:
image: 14790897/paperai:latest
container_name: paperai_app
ports:
- "3000:3000" # 映射宿主机和容器的端口
# environment: # 设置环境变量
# NEXT_PUBLIC_AI_URL: "自定义AI模型地址"
# NEXT_PUBLIC_OPENAI_API_KEY: "自定义API KEY"
restart: unless-stopped # 容器退出时重启策略

View File

@ -69,6 +69,6 @@ export const config = {
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|twitter-image.png|opengraph-image.png|manifest.json|site.webmanifest|favicon-32x32.png|favicon-16x16.png|apple-touch-icon.png|android-chrome-512x512.png|android-chrome-192x192.png|service-worker.js|serviceregister.js|global.css|sitemap.xml|robots.txt|api/oauth/callback).*)",
"/((?!_next/static|_next/image|favicon.png).*)",
],
};

View File

@ -6,18 +6,14 @@ const nextConfig = {
};
module.exports = nextConfig;
// 配置 @next/bundle-analyzer
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
// 首先使用withBundleAnalyzer包装nextConfig
const enhancedConfig = withBundleAnalyzer(nextConfig);
// Injected content via Sentry wizard below
const { withSentryConfig } = require("@sentry/nextjs");
// 然后使用withSentryConfig包装已增强的配置
module.exports = withSentryConfig(
enhancedConfig,
module.exports,
{
// For all available options, see:
// https://github.com/getsentry/sentry-webpack-plugin#options
@ -25,7 +21,7 @@ module.exports = withSentryConfig(
// Suppresses source map uploading logs during build
silent: true,
org: "liuweiqing-limited",
project: "paperai",
project: "javascript-nextjs",
},
{
// For all available options, see:

1549
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,14 +13,12 @@
"@lemonsqueezy/lemonsqueezy.js": "^2.0.0",
"@next/third-parties": "^14.1.0",
"@reduxjs/toolkit": "^2.0.1",
"@sentry/nextjs": "^7.101.1",
"@sentry/nextjs": "^7.100.1",
"@supabase/ssr": "latest",
"@supabase/supabase-js": "latest",
"@types/react-toastify": "^4.1.0",
"add": "^2.0.6",
"autoprefixer": "10.4.15",
"axios": "^1.6.5",
"citation-js": "^0.7.8",
"file-saver": "^2.0.5",
"geist": "^1.0.0",
"i": "^0.3.7",
@ -32,8 +30,7 @@
"next": "latest",
"next-redux-wrapper": "^8.1.0",
"openai": "^4.24.3",
"postcss": "8.4.35",
"punycode": "^2.3.1",
"postcss": "8.4.31",
"quill": "^1.3.7",
"quill-to-word": "^1.3.0",
"raw-body": "^2.5.2",
@ -41,21 +38,23 @@
"react-cookie": "^7.0.2",
"react-dom": "^18.2.0",
"react-i18next": "^14.0.5",
"react-icons": "^5.0.1",
"react-quill": "^2.0.0",
"react-redux": "^9.1.0",
"react-toastify": "^10.0.4",
"react-transition-group": "^4.4.5",
"react-use": "^17.4.3",
"redux": "^5.0.1",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"sweetalert2": "^11.10.6",
"slate": "^0.101.5",
"slate-history": "^0.100.0",
"slate-hyperscript": "^0.100.0",
"slate-react": "^0.101.5",
"sweetalert2": "^11.10.4",
"tailwindcss": "3.3.3",
"typescript": "5.1.3",
"xml2js": "^0.6.2"
},
"devDependencies": {
"@next/bundle-analyzer": "^14.1.0",
"@types/file-saver": "^2.0.7",
"@types/negotiator": "^0.6.3",
"@types/node": "^20.3.1",
@ -65,5 +64,5 @@
"@types/redux-logger": "^3.0.12",
"encoding": "^0.1.13"
},
"version": "1.9.0"
"version": "1.5.1"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 766 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

View File

@ -1,52 +0,0 @@
{
"short_name": "Paper AI",
"name": "paper ai 使用真实文献让AI完成论文",
"start_url": "/",
"display": "standalone",
"theme_color": "#ffffff",
"background_color": "#ffffff",
"description": "写论文最高效的方式",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/apple-touch-icon.png",
"sizes": "180x180",
"type": "image/png",
"purpose": "any"
},
{
"src": "/favicon-16x16.png",
"sizes": "16x16",
"type": "image/png",
"purpose": "any"
},
{
"src": "/favicon-32x32.png",
"sizes": "32x32",
"type": "image/png",
"purpose": "any"
},
{
"src": "/favicon.ico",
"sizes": "48x48",
"type": "image/x-icon",
"purpose": "any"
}
],
"dir": "ltr",
"scope": "/",
"orientation": "any",
"related_applications": [],
"prefer_related_applications": false
}

View File

@ -1,58 +0,0 @@
const cacheName = "v1";
const preCacheResources = [
// 添加需要预缓存的资源列表
"/.next/static",
"/public",
"/",
"/index.html",
"/styles/main.css",
"/scripts/main.js",
// 更多资源...
];
// 安装事件:预缓存关键资源
self.addEventListener("install", (e) => {
console.log("Service Worker: Installed");
e.waitUntil(
caches
.open(cacheName)
.then((cache) => {
console.log("Service Worker: Caching Files");
cache.addAll(preCacheResources);
})
.then(() => self.skipWaiting())
);
});
// 激活事件:清理旧缓存
self.addEventListener("activate", (e) => {
console.log("Service Worker: Activated");
e.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) {
console.log("Service Worker: Clearing Old Cache");
return caches.delete(cache);
}
})
);
})
);
});
// 尝试从网络获取资源,并将响应克隆到缓存
const cacheClone = async (e) => {
const res = await fetch(e.request);
const resClone = res.clone();
const cache = await caches.open(cacheName);
await cache.put(e.request, resClone);
return res;
};
// Fetch 事件:网络优先,然后缓存
self.addEventListener("fetch", (e) => {
e.respondWith(
cacheClone(e)
.catch(() => caches.match(e.request))
.then((res) => res || fetch(e.request))
);
});

View File

@ -1,17 +0,0 @@
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/service-worker.js").then(
(registration) => {
// 注册成功
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope
);
},
(err) => {
// 注册失败
console.log("ServiceWorker registration failed: ", err);
}
);
});
}

View File

@ -1 +0,0 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}

View File

@ -3,35 +3,32 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
if (process.env.NODE_ENV === "production") {
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
replaysOnErrorSampleRate: 1.0,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
replaysSessionSampleRate: 0.1,
beforeSend(event, hint) {
// 检查事件是否为通过 `captureMessage` 发送的
if (event.logger === "javascript" && event.message) {
return event; // 允许发送消息事件
}
return null; // 过滤掉其他类型的事件
},
// You can remove this option if you're not planning to use the Sentry Session Replay feature:
integrations: [
Sentry.replayIntegration({
// Additional Replay configuration goes in here, for example:
maskAllText: true,
blockAllMedia: true,
}),
],
});
}
replaysOnErrorSampleRate: 1.0,
// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
replaysSessionSampleRate: 0.1,
// You can remove this option if you're not planning to use the Sentry Session Replay feature:
integrations: [
Sentry.replayIntegration({
// Additional Replay configuration goes in here, for example:
maskAllText: true,
blockAllMedia: true,
}),
Sentry.feedbackIntegration({
// Additional SDK configuration goes in here, for example:
colorScheme: "light",
}),
],
});

View File

@ -4,14 +4,13 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
if (process.env.NODE_ENV === "production") {
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});
}
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});

View File

@ -3,14 +3,13 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
if (process.env.NODE_ENV === "production") {
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
Sentry.init({
dsn: "https://523c4056ba48d012c62a377dfc49f647@o4506728662564864.ingest.sentry.io/4506728672264192",
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});
}
// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});

View File

@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Confirm Your Signup</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
.container {
background-color: #fff;
max-width: 600px;
margin: 0 auto;
padding: 20px;
text-align: center;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
p {
color: #666;
}
.button {
display: inline-block;
margin-top: 20px;
padding: 10px 20px;
background-color: #28a745;
color: #ffffff;
text-decoration: none;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to PaperAI!</h1>
<p>
You're almost ready to start exploring all the powerful features of
PaperAI, including AI writing, literature search, and more.
</p>
<p>
Please click the button below to confirm your signup and activate your
account:
</p>
<a href="{{ .ConfirmationURL }}" class="button">Confirm Signup</a>
<p>
If you didn't sign up for a PaperAI account, please ignore this email.
</p>
</div>
</body>
</html>

View File

@ -18,15 +18,6 @@ module.exports = {
},
gold: "#FFD700",
},
animation: {
spin: "spin 1s linear infinite",
},
keyframes: {
spin: {
"0%": { transform: "rotate(0deg)" },
"100%": { transform: "rotate(360deg)" },
},
},
},
},
plugins: [],

View File

@ -1,154 +0,0 @@
// // Path: utils/others/aiutils.ts
// import { sendMessageToOpenAI } from "@/components/chatAI";
// //判断返回的文献是否跟用户输入的主题相关
// export async function evaluateTopicMatch(
// userMessage: any[],
// apiKey: string,
// upsreamUrl: string,
// selectedModel: string,
// topic: string
// ): Promise<{ relevantPapers: string[]; nonRelevantPapers: string[] }> {
// const prompt = "请判断文献是否跟用户输入的主题相关,只需要返回true或者false";
// let relevantPapers: string[] = []; // 存储相关论文的数组
// let nonRelevantPapers: string[] = []; // 存储不相关论文的数组
// for (const paper of userMessage) {
// if (relevantPapers.length >= 2) {
// console.log("已找到两篇相关文献,停止处理剩余文献。");
// break; // 如果已经有两篇相关文献,则停止处理
// }
// // 检查是否存在 abstract如果不存在直接将论文添加到 nonRelevantPapers
// if (!paper.abstract) {
// nonRelevantPapers.push(paper);
// console.log(
// `Paper titled "${paper.title}" has no abstract and was added to non-relevant papers.`
// );
// continue; // 跳过当前迭代,继续下一个论文
// }
// const input = `user's topic:${topic}, \n paper's title: ${paper.title}, \n paper's abstract: ${paper.abstract}`;
// const isRelevantResult = await sendMessageToOpenAI(
// input,
// null,
// selectedModel!,
// apiKey,
// upsreamUrl,
// prompt,
// null,
// false
// );
// console.log("isRelevantResult", isRelevantResult);
// // 尝试解析 JSON 结果,如果无法解析则直接使用结果字符串
// let isRelevant;
// try {
// const parsedResult = JSON.parse(isRelevantResult);
// isRelevant =
// parsedResult === true || parsedResult.toLowerCase() === "true";
// } catch {
// isRelevant =
// isRelevantResult.includes("true") || isRelevantResult.includes("True");
// }
// if (isRelevant) {
// relevantPapers.push(paper); // 如果论文相关,则添加到数组中
// } else {
// nonRelevantPapers.push(paper); // 如果论文不相关,则添加到不相关论文数组中
// }
// }
// console.log(
// `这次有${nonRelevantPapers.length}篇文献没有通过相关性检查`,
// nonRelevantPapers
// );
// //如果相关文献大于两片则缩减到两篇
// // if (relevantPapers.length > 2) {
// // relevantPapers = relevantPapers.slice(0, 2);
// // console.log("文献太多了,只取前两篇");
// // }
// return { relevantPapers, nonRelevantPapers };
// }
// Path: utils/others/aiutils.ts
import { sendMessageToOpenAI } from "@/components/chatAI";
//判断返回的文献是否跟用户输入的主题相关
export async function evaluateTopicMatch(
userMessage: any[],
apiKey: string,
upsreamUrl: string,
selectedModel: string,
topic: string,
signal: AbortSignal
): Promise<{ relevantPapers: string[]; nonRelevantPapers: string[] }> {
const prompt =
"请判断文献是否跟用户输入的主题相关,只需要返回true或false的数组";
let relevantPapers: string[] = []; // 存储相关论文的数组
let nonRelevantPapers: string[] = []; // 存储不相关论文的数组
// 修改循环逻辑,每次处理两篇文献
for (let i = 0; i < userMessage.length; i += 2) {
// 检查是否已有足够的相关论文
if (relevantPapers.length >= 2) {
console.log("已找到两篇相关文献,停止处理剩余文献。");
break;
}
let inputs = [];
let papersToEvaluate = userMessage.slice(i, i + 2); // 获取当前迭代的两篇文献
for (const paper of papersToEvaluate) {
// 检查是否存在 abstract如果不存在直接将论文添加到 nonRelevantPapers
if (!paper.abstract) {
nonRelevantPapers.push(paper);
console.log(
`Paper titled "${paper.title}" has no abstract and was added to non-relevant papers.`
);
continue; // 跳过当前论文,继续下一个论文
}
// 准备输入数据
const input = `user's topic: ${topic}, \n paper's title: ${paper.title}, \n paper's abstract: ${paper.abstract}`;
inputs.push(input);
}
// 如果有需要评估的文献,则发送请求
if (inputs.length > 0) {
const combinedInput = inputs.join("\n\n");
const isRelevantResults = await sendMessageToOpenAI(
combinedInput,
null,
selectedModel!,
apiKey,
upsreamUrl,
prompt,
null,
false,
signal
);
console.log("isrelevantResults in 相关性检查", isRelevantResults);
// 处理每篇文献的相关性结果
papersToEvaluate.forEach((paper, index) => {
let isRelevant;
try {
const parsedResults = JSON.parse(isRelevantResults); // 将字符串解析成数组
isRelevant =
parsedResults[index] === true ||
parsedResults[index].toString().toLowerCase() === "true";
} catch {
console.log("Error parsing isRelevantResults or accessing index");
}
if (isRelevant) {
relevantPapers.push(paper);
console.log(`Paper titled "${paper.title}" is relevant.`);
} else {
nonRelevantPapers.push(paper);
console.log(`Paper titled "${paper.title}" is not relevant.`);
}
});
}
}
console.log(
`这次有${nonRelevantPapers.length}篇文献没有通过相关性检查`,
nonRelevantPapers
);
return { relevantPapers, nonRelevantPapers };
}

View File

@ -183,67 +183,6 @@ function convertToSuperscript(quill: Quill) {
}
}
function removeDuplicateBracketNumbersInDelta(delta: any) {
let seenNumbers = new Set(); // 用于记录已经看到的编号
const updatedOps = delta.ops.map((op: any) => {
if (typeof op.insert === "string") {
// 使用正则表达式和replace方法来找到并处理[数字]
return {
...op,
insert: op.insert.replace(/\[\d+\]/g, (match) => {
const number = match.slice(1, -1); // 提取括号中的数字
if (seenNumbers.has(number)) {
// 如果这个编号已经处理过,就删除它(用空字符串替换)
return "";
} else {
// 如果是首次见到这个编号,就记录并保留它
seenNumbers.add(number);
console.log("seenNumbers", seenNumbers);
return match;
}
}),
};
}
return op;
});
return { ops: updatedOps };
}
export function deleteSameBracketNumber(
quill: Quill,
cursorOldPosition: number
) {
//搜索是否有相同的括号编号,如果有相同的则删除到只剩一个
const selection = quill.getSelection(true);
if (selection) {
// 获取整个文档的内容
const delta = quill.getContents();
// 仅获取选区中的Delta片段
const selectionDelta = delta.slice(cursorOldPosition, selection.index);
console.log("cursorOldPosition", cursorOldPosition);
console.log("selection.index", selection.index);
console.log("selectionDelta", selectionDelta);
// 对选区中的Delta片段进行处理移除重复的括号编号
const updatedSelectionDelta =
removeDuplicateBracketNumbersInDelta(selectionDelta);
// 构建一个新的Delta包括未修改的选区前部分和处理后的选区后部分
const updatedDelta = delta
.slice(0, cursorOldPosition)
.concat(updatedSelectionDelta)
.concat(delta.slice(selection.index));
// 设置更新后的内容
quill.setContents(updatedDelta);
// 恢复选区
quill.setSelection(selection.index, selection.length);
}
}
function getRandomOffset(max: number) {
return Math.floor(Math.random() * max);
}
@ -287,7 +226,6 @@ export function formatTextInEditor(editor: Quill) {
updateBracketNumbersInDeltaKeepSelection(editor);
}
//这个是格式化semantic scholar的
export function formatJournalReference(entry: any) {
if (!entry.journal) {
return ""; // 如果没有期刊信息,直接返回空字符串
@ -309,39 +247,6 @@ export function formatJournalReference(entry: any) {
return reference;
}
function formatReference(reference: Reference) {
if (reference.journal) {
return `[J]. ${reference.journal}. `;
} else if (reference.journalReference) {
return `[J]. ${reference.journalReference}`;
} else {
return `${reference.venue}, ${reference.year}.`;
}
}
export function getFullReference(reference: Reference) {
let fullReference = `${reference.author}. ${reference.title}`;
fullReference += formatReference(reference);
return fullReference;
}
export function getAllFullReferences(references: Reference[], style: string) {
return references
.map((reference, index) => {
return `[${index + 1}] ${renderCitation(reference, style)}`;
})
.join("\n");
}
export function renderCitation(reference: any, style: string) {
// 检查当前的引用风格
if (style === "custom-chinese") {
// 如果是“custom-chinese”则调用 getFullReference 来渲染引用
return getFullReference(reference);
} else {
// 否则,返回引用对象中对应风格的引用文本
return reference[style];
}
}
export {
getTextBeforeCursor,
updateBracketNumbersInDelta,

View File

@ -0,0 +1,10 @@
"use server";
import { cookies } from "next/headers";
import { createClient } from "@/utils/supabase/server";
export const signOut = async () => {
const cookieStore = cookies();
const supabase = createClient(cookieStore);
await supabase.auth.signOut();
};

View File

@ -1,47 +0,0 @@
import { NextResponse } from "next/server";
import { SupabaseClient } from "@supabase/supabase-js";
export async function setVip(
supabaseAdmin: SupabaseClient,
userId: string,
isVip = true,
source = "Linuxdo",
startDate = new Date(),
endDate = new Date()
) {
if (!userId)
return NextResponse.json({ message: "No user found" }, { status: 403 });
const { data, error } = await supabaseAdmin.from("vip_statuses").upsert(
{
user_id: userId,
is_vip: isVip,
source: source,
start_date: startDate,
end_date: endDate,
},
{ onConflict: "user_id" }
);
if (error) {
console.error("设置 VIP 失败:", error);
return NextResponse.json(
{ message: "Failed to set VIP 设置 VIP 状态失败" },
{ status: 403 }
);
}
return NextResponse.json({ message: "Success VIP 状态已更新:" });
}
async function getUserId(supabaseAdmin: SupabaseClient, email: string) {
const { data, error } = await supabaseAdmin
.from("profiles")
.select("id")
.eq("email", email)
.single();
if (error) {
console.error("查询用户 ID 失败:", error);
return null;
}
return data.id;
}

View File

@ -7,9 +7,6 @@ import { Reference } from "@/utils/global";
//supabase
const supabase = createClient();
import { createClient } from "@/utils/supabase/client";
//sentry
import * as Sentry from "@sentry/nextjs";
//获取用户id
export async function getUser() {
const { data, error } = await supabase.auth.getSession();
@ -175,39 +172,3 @@ export async function fetchUserVipStatus(userId: string) {
return false;
}
}
//profiles表 插入用户信息
export async function insertUserProfile(data: any, supabase: SupabaseClient) {
let user;
if (data.user) {
user = data.user;
} else {
user = data;
}
if (user) {
// console.log("user in insertUserProfile:", user);
const currentTime = new Date().toISOString(); // 生成ISO格式的时间字符串
const { data, error: profileError } = await supabase
.from("profiles")
.upsert([
{
id: user.id,
email: user.email,
created_at: currentTime, // 添加创建时间
},
]);
if (profileError) {
console.error("Failed to create user profile:", profileError);
Sentry.captureException(profileError);
}
Sentry.setUser({
email: user.email,
id: user.id,
ip_address: "{{auto}}",
});
}
}