Spaces:
Sleeping
Sleeping
Upload 80 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .dockerignore +57 -0
- .gitattributes +35 -35
- .gitignore +330 -0
- Dockerfile +41 -0
- LICENSE +21 -0
- README.md +66 -10
- data/active_sessions.json +12 -0
- data/users.json +24 -0
- docker-compose.yml +35 -0
- logs/deployment.log +883 -0
- logs/development.log +318 -0
- logs/manager.log +224 -0
- logs/setup.log +0 -0
- main.py +724 -0
- projects.json +0 -0
- src/components/__init__.py +26 -0
- src/components/__pycache__/__init__.cpython-311.pyc +0 -0
- src/components/__pycache__/__init__.cpython-313.pyc +0 -0
- src/components/__pycache__/arxiv_fetcher.cpython-311.pyc +0 -0
- src/components/__pycache__/auth.cpython-311.pyc +0 -0
- src/components/__pycache__/citation_network.cpython-311.pyc +0 -0
- src/components/__pycache__/config.cpython-311.pyc +0 -0
- src/components/__pycache__/config.cpython-313.pyc +0 -0
- src/components/__pycache__/groq_processor.cpython-311.pyc +0 -0
- src/components/__pycache__/groq_processor.cpython-313.pyc +0 -0
- src/components/__pycache__/pdf_processor.cpython-311.pyc +0 -0
- src/components/__pycache__/rag_system.cpython-311.pyc +0 -0
- src/components/__pycache__/research_assistant.cpython-311.pyc +0 -0
- src/components/__pycache__/trend_monitor.cpython-311.pyc +0 -0
- src/components/__pycache__/unified_fetcher.cpython-311.pyc +0 -0
- src/components/arxiv_fetcher.py +371 -0
- src/components/auth.py +297 -0
- src/components/citation_network.py +295 -0
- src/components/config.py +125 -0
- src/components/groq_processor.py +326 -0
- src/components/pdf_processor.py +479 -0
- src/components/rag_system.py +408 -0
- src/components/research_assistant.py +704 -0
- src/components/trend_monitor.py +517 -0
- src/components/unified_fetcher.py +938 -0
- src/scripts/__init__.py +20 -0
- src/scripts/__pycache__/__init__.cpython-311.pyc +0 -0
- src/scripts/__pycache__/__init__.cpython-313.pyc +0 -0
- src/scripts/__pycache__/deploy.cpython-311.pyc +0 -0
- src/scripts/__pycache__/deploy.cpython-313.pyc +0 -0
- src/scripts/__pycache__/dev_server.cpython-311.pyc +0 -0
- src/scripts/__pycache__/manager.cpython-311.pyc +0 -0
- src/scripts/__pycache__/setup.cpython-311.pyc +0 -0
- src/scripts/deploy.py +416 -0
- src/scripts/dev_server.py +358 -0
.dockerignore
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Docker ignore file for ResearchMate
|
2 |
+
# Ignore unnecessary files and directories
|
3 |
+
|
4 |
+
# Git
|
5 |
+
.git
|
6 |
+
.gitignore
|
7 |
+
|
8 |
+
# Python
|
9 |
+
__pycache__
|
10 |
+
*.pyc
|
11 |
+
*.pyo
|
12 |
+
*.pyd
|
13 |
+
.Python
|
14 |
+
*.so
|
15 |
+
.pytest_cache
|
16 |
+
|
17 |
+
# Virtual environments
|
18 |
+
venv/
|
19 |
+
env/
|
20 |
+
ENV/
|
21 |
+
|
22 |
+
# IDE
|
23 |
+
.vscode/
|
24 |
+
.idea/
|
25 |
+
*.swp
|
26 |
+
*.swo
|
27 |
+
|
28 |
+
# OS
|
29 |
+
.DS_Store
|
30 |
+
Thumbs.db
|
31 |
+
desktop.ini
|
32 |
+
|
33 |
+
# Data directories (will be mounted as volumes)
|
34 |
+
data/
|
35 |
+
logs/
|
36 |
+
chroma_persist/
|
37 |
+
chroma_db/
|
38 |
+
Notebook/
|
39 |
+
uploads/
|
40 |
+
|
41 |
+
|
42 |
+
# Development files
|
43 |
+
test_*.py
|
44 |
+
debug_*.py
|
45 |
+
*.bak
|
46 |
+
*.tmp
|
47 |
+
|
48 |
+
# Documentation
|
49 |
+
README.md
|
50 |
+
*.md
|
51 |
+
|
52 |
+
# Environment files (will be passed as env vars)
|
53 |
+
.env
|
54 |
+
|
55 |
+
# Backup files
|
56 |
+
backups/
|
57 |
+
tmp/
|
.gitattributes
CHANGED
@@ -1,35 +1,35 @@
|
|
1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
*.egg-info/
|
24 |
+
.installed.cfg
|
25 |
+
*.egg
|
26 |
+
MANIFEST
|
27 |
+
|
28 |
+
# PyInstaller
|
29 |
+
# Usually these files are written by a python script from a template
|
30 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
31 |
+
*.manifest
|
32 |
+
*.spec
|
33 |
+
|
34 |
+
# Installer logs
|
35 |
+
pip-log.txt
|
36 |
+
pip-delete-this-directory.txt
|
37 |
+
|
38 |
+
# Unit test / coverage reports
|
39 |
+
htmlcov/
|
40 |
+
.tox/
|
41 |
+
.coverage
|
42 |
+
.coverage.*
|
43 |
+
.cache
|
44 |
+
nosetests.xml
|
45 |
+
coverage.xml
|
46 |
+
*.cover
|
47 |
+
.hypothesis/
|
48 |
+
.pytest_cache/
|
49 |
+
|
50 |
+
# Translations
|
51 |
+
*.mo
|
52 |
+
*.pot
|
53 |
+
|
54 |
+
# Django stuff:
|
55 |
+
*.log
|
56 |
+
local_settings.py
|
57 |
+
db.sqlite3
|
58 |
+
|
59 |
+
# Flask stuff:
|
60 |
+
instance/
|
61 |
+
.webassets-cache
|
62 |
+
|
63 |
+
# Scrapy stuff:
|
64 |
+
.scrapy
|
65 |
+
|
66 |
+
# Sphinx documentation
|
67 |
+
docs/_build/
|
68 |
+
|
69 |
+
# PyBuilder
|
70 |
+
target/
|
71 |
+
|
72 |
+
# Jupyter Notebook
|
73 |
+
.ipynb_checkpoints
|
74 |
+
*.ipynb
|
75 |
+
|
76 |
+
# pyenv
|
77 |
+
.python-version
|
78 |
+
|
79 |
+
# celery beat schedule file
|
80 |
+
celerybeat-schedule
|
81 |
+
|
82 |
+
# SageMath parsed files
|
83 |
+
*.sage.py
|
84 |
+
|
85 |
+
# Environments
|
86 |
+
.env
|
87 |
+
.venv
|
88 |
+
env/
|
89 |
+
venv/
|
90 |
+
ENV/
|
91 |
+
env.bak/
|
92 |
+
venv.bak/
|
93 |
+
|
94 |
+
# Spyder project settings
|
95 |
+
.spyderproject
|
96 |
+
.spyproject
|
97 |
+
|
98 |
+
# Rope project settings
|
99 |
+
.ropeproject
|
100 |
+
|
101 |
+
# mkdocs documentation
|
102 |
+
/site
|
103 |
+
|
104 |
+
# mypy
|
105 |
+
.mypy_cache/
|
106 |
+
.dmypy.json
|
107 |
+
dmypy.json
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
# Development files
|
112 |
+
|
113 |
+
test_*.html
|
114 |
+
test_*.json
|
115 |
+
debug_*.py
|
116 |
+
quick_test.py
|
117 |
+
migrate_*.py
|
118 |
+
init_*.py
|
119 |
+
|
120 |
+
# Backup and temporary files
|
121 |
+
*.bak
|
122 |
+
*.tmp
|
123 |
+
|
124 |
+
# IDE files
|
125 |
+
.vscode/
|
126 |
+
.idea/
|
127 |
+
*.swp
|
128 |
+
*.swo
|
129 |
+
*~
|
130 |
+
|
131 |
+
# OS files
|
132 |
+
.DS_Store
|
133 |
+
Thumbs.db
|
134 |
+
desktop.ini
|
135 |
+
|
136 |
+
# Configuration files with secrets
|
137 |
+
config/secrets.json
|
138 |
+
config/api_keys.json
|
139 |
+
|
140 |
+
# Additional exclusions
|
141 |
+
*.sqlite
|
142 |
+
*.db
|
143 |
+
.coverage.*
|
144 |
+
*.cover
|
145 |
+
.hypothesis/
|
146 |
+
|
147 |
+
# ResearchMate runtime files
|
148 |
+
*.pid
|
149 |
+
*.sock
|
150 |
+
|
151 |
+
# PyInstaller
|
152 |
+
# Usually these files are written by a python script from a template
|
153 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
154 |
+
*.manifest
|
155 |
+
*.spec
|
156 |
+
|
157 |
+
# Installer logs
|
158 |
+
pip-log.txt
|
159 |
+
pip-delete-this-directory.txt
|
160 |
+
|
161 |
+
# Unit test / coverage reports
|
162 |
+
htmlcov/
|
163 |
+
.tox/
|
164 |
+
.nox/
|
165 |
+
.coverage
|
166 |
+
.coverage.*
|
167 |
+
.cache
|
168 |
+
nosetests.xml
|
169 |
+
coverage.xml
|
170 |
+
*.cover
|
171 |
+
*.py.cover
|
172 |
+
.hypothesis/
|
173 |
+
.pytest_cache/
|
174 |
+
cover/
|
175 |
+
|
176 |
+
# Translations
|
177 |
+
*.mo
|
178 |
+
*.pot
|
179 |
+
|
180 |
+
# Django stuff:
|
181 |
+
*.log
|
182 |
+
local_settings.py
|
183 |
+
db.sqlite3
|
184 |
+
db.sqlite3-journal
|
185 |
+
|
186 |
+
# Flask stuff:
|
187 |
+
instance/
|
188 |
+
.webassets-cache
|
189 |
+
|
190 |
+
# Scrapy stuff:
|
191 |
+
.scrapy
|
192 |
+
|
193 |
+
# Sphinx documentation
|
194 |
+
docs/_build/
|
195 |
+
|
196 |
+
# PyBuilder
|
197 |
+
.pybuilder/
|
198 |
+
target/
|
199 |
+
|
200 |
+
# Jupyter Notebook
|
201 |
+
.ipynb_checkpoints
|
202 |
+
|
203 |
+
# IPython
|
204 |
+
profile_default/
|
205 |
+
ipython_config.py
|
206 |
+
|
207 |
+
# pyenv
|
208 |
+
# For a library or package, you might want to ignore these files since the code is
|
209 |
+
# intended to run in multiple environments; otherwise, check them in:
|
210 |
+
# .python-version
|
211 |
+
|
212 |
+
# pipenv
|
213 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
214 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
215 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
216 |
+
# install all needed dependencies.
|
217 |
+
#Pipfile.lock
|
218 |
+
|
219 |
+
# UV
|
220 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
221 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
222 |
+
# commonly ignored for libraries.
|
223 |
+
#uv.lock
|
224 |
+
|
225 |
+
# poetry
|
226 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
227 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
228 |
+
# commonly ignored for libraries.
|
229 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
230 |
+
#poetry.lock
|
231 |
+
#poetry.toml
|
232 |
+
|
233 |
+
# pdm
|
234 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
235 |
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
236 |
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
237 |
+
#pdm.lock
|
238 |
+
#pdm.toml
|
239 |
+
.pdm-python
|
240 |
+
.pdm-build/
|
241 |
+
|
242 |
+
# pixi
|
243 |
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
244 |
+
#pixi.lock
|
245 |
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
246 |
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
247 |
+
.pixi
|
248 |
+
|
249 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
250 |
+
__pypackages__/
|
251 |
+
|
252 |
+
# Celery stuff
|
253 |
+
celerybeat-schedule
|
254 |
+
celerybeat.pid
|
255 |
+
|
256 |
+
# SageMath parsed files
|
257 |
+
*.sage.py
|
258 |
+
|
259 |
+
# Environments
|
260 |
+
.env
|
261 |
+
.envrc
|
262 |
+
.venv
|
263 |
+
env/
|
264 |
+
venv/
|
265 |
+
ENV/
|
266 |
+
env.bak/
|
267 |
+
venv.bak/
|
268 |
+
|
269 |
+
# Spyder project settings
|
270 |
+
.spyderproject
|
271 |
+
.spyproject
|
272 |
+
|
273 |
+
# Rope project settings
|
274 |
+
.ropeproject
|
275 |
+
|
276 |
+
# mkdocs documentation
|
277 |
+
/site
|
278 |
+
|
279 |
+
# mypy
|
280 |
+
.mypy_cache/
|
281 |
+
.dmypy.json
|
282 |
+
dmypy.json
|
283 |
+
|
284 |
+
# Pyre type checker
|
285 |
+
.pyre/
|
286 |
+
|
287 |
+
# pytype static type analyzer
|
288 |
+
.pytype/
|
289 |
+
|
290 |
+
# Cython debug symbols
|
291 |
+
cython_debug/
|
292 |
+
|
293 |
+
# PyCharm
|
294 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
295 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
296 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
297 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
298 |
+
#.idea/
|
299 |
+
|
300 |
+
# Abstra
|
301 |
+
# Abstra is an AI-powered process automation framework.
|
302 |
+
# Ignore directories containing user credentials, local state, and settings.
|
303 |
+
# Learn more at https://abstra.io/docs
|
304 |
+
.abstra/
|
305 |
+
|
306 |
+
# Visual Studio Code
|
307 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
308 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
309 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
310 |
+
# you could uncomment the following to ignore the entire vscode folder
|
311 |
+
# .vscode/
|
312 |
+
|
313 |
+
# Ruff stuff:
|
314 |
+
.ruff_cache/
|
315 |
+
|
316 |
+
# PyPI configuration file
|
317 |
+
.pypirc
|
318 |
+
|
319 |
+
# Cursor
|
320 |
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
321 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
322 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
323 |
+
.cursorignore
|
324 |
+
.cursorindexingignore
|
325 |
+
|
326 |
+
# Marimo
|
327 |
+
marimo/_static/
|
328 |
+
marimo/_lsp/
|
329 |
+
__marimo__/
|
330 |
+
|
Dockerfile
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.11-slim
|
2 |
+
|
3 |
+
WORKDIR /app
|
4 |
+
|
5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
6 |
+
ENV PYTHONUNBUFFERED=1
|
7 |
+
|
8 |
+
# Install system dependencies
|
9 |
+
RUN apt-get update && apt-get install -y \
|
10 |
+
build-essential \
|
11 |
+
curl \
|
12 |
+
&& rm -rf /var/lib/apt/lists/*
|
13 |
+
|
14 |
+
# Copy requirements and install
|
15 |
+
COPY requirements.txt .
|
16 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
17 |
+
pip install --no-cache-dir -r requirements.txt
|
18 |
+
|
19 |
+
# Pre-download embedding models
|
20 |
+
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')"
|
21 |
+
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-mpnet-base-v2')"
|
22 |
+
|
23 |
+
# Copy application code
|
24 |
+
COPY . .
|
25 |
+
|
26 |
+
# Create necessary directories with proper permissions
|
27 |
+
RUN mkdir -p /app/data /app/logs /app/chroma_persist /app/uploads /app/tmp /app/config /app/chroma_db && \
|
28 |
+
chmod -R 755 /app/data /app/logs /app/chroma_persist /app/uploads /app/tmp /app/config /app/chroma_db
|
29 |
+
|
30 |
+
# Create tmp directory in standard location as well
|
31 |
+
RUN mkdir -p /tmp/researchmate && chmod 755 /tmp/researchmate
|
32 |
+
|
33 |
+
# Spaces uses port 7860
|
34 |
+
EXPOSE 7860
|
35 |
+
|
36 |
+
# Health check
|
37 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
38 |
+
CMD curl -f http://localhost:7860/health || exit 1
|
39 |
+
|
40 |
+
# Start the application
|
41 |
+
CMD ["python", "main.py"]
|
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2025 Ananthakrishnan K
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
README.md
CHANGED
@@ -1,10 +1,66 @@
|
|
1 |
-
---
|
2 |
-
title: ResearchMate
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
-
sdk: docker
|
7 |
-
|
8 |
-
---
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: ResearchMate
|
3 |
+
emoji: 🔬
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: green
|
6 |
+
sdk: docker
|
7 |
+
app_port: 7860
|
8 |
+
---
|
9 |
+
|
10 |
+
# ResearchMate 🔬
|
11 |
+
|
12 |
+
An AI-powered research assistant that helps you search, analyze, and manage academic papers using advanced language models.
|
13 |
+
|
14 |
+
## Features ✨
|
15 |
+
|
16 |
+
- **🔍 Smart Paper Search**: Search academic papers using natural language queries
|
17 |
+
- **🧠 AI-Powered Analysis**: Analyze papers and generate insights using Groq Llama 3.3 70B
|
18 |
+
- **📚 Project Management**: Organize research into projects with automatic literature management
|
19 |
+
- **📊 Citation Network Analysis**: Visualize and analyze citation networks
|
20 |
+
- **📈 Research Trend Monitoring**: Track and monitor research trends over time
|
21 |
+
- **📄 PDF Processing**: Extract and process text from PDF papers with advanced cleaning
|
22 |
+
- **🔐 User Authentication**: Secure user management with JWT tokens
|
23 |
+
- **💾 Vector Storage**: Efficient paper storage and retrieval using ChromaDB
|
24 |
+
|
25 |
+
## How to Use 🚀
|
26 |
+
|
27 |
+
### 1. **Getting Started**
|
28 |
+
- Click the app link above to access ResearchMate
|
29 |
+
- Register for a new account or login if you have one
|
30 |
+
- Wait for the loading screen to complete (ResearchMate initialization)
|
31 |
+
|
32 |
+
### 2. **Create a Project**
|
33 |
+
- Click "Projects" in the navigation
|
34 |
+
- Create a new research project with your research question
|
35 |
+
- Add relevant keywords to help focus your research
|
36 |
+
|
37 |
+
### 3. **Search Papers**
|
38 |
+
- Use natural language queries like "machine learning in healthcare"
|
39 |
+
- Filter by date range, categories, or specific journals
|
40 |
+
- Browse results with abstracts and metadata
|
41 |
+
|
42 |
+
### 4. **Upload & Analyze PDFs**
|
43 |
+
- Upload your own research papers
|
44 |
+
- Get AI-powered analysis and insights
|
45 |
+
- Extract key information and summaries
|
46 |
+
|
47 |
+
### 5. **Explore Citations**
|
48 |
+
- View citation networks and paper relationships
|
49 |
+
- Discover related research and trending topics
|
50 |
+
- Track research evolution over time
|
51 |
+
|
52 |
+
## Technology Stack 🛠️
|
53 |
+
|
54 |
+
- **Backend**: FastAPI + Python 3.11
|
55 |
+
- **AI Model**: Groq Llama 3.3 70B Instruct
|
56 |
+
- **Embeddings**: SentenceTransformers (all-MiniLM-L6-v2, all-mpnet-base-v2)
|
57 |
+
- **Vector Database**: ChromaDB for efficient similarity search
|
58 |
+
- **Frontend**: HTML/CSS/JavaScript with Bootstrap
|
59 |
+
- **Authentication**: JWT tokens with secure session management
|
60 |
+
- **PDF Processing**: Advanced text extraction and cleaning
|
61 |
+
- **Search**: ArXiv API integration with intelligent filtering
|
62 |
+
|
63 |
+
## Configuration ⚙️
|
64 |
+
|
65 |
+
### Environment Variables
|
66 |
+
Set the following in your Space settings:
|
data/active_sessions.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"admin_user": {
|
3 |
+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYWRtaW5fdXNlciIsInVzZXJuYW1lIjoiYWRtaW4iLCJleHAiOjE3NTI0MjY2NDV9.Csfsds7stWuRB_NcJKMZQB40PFBqUpg6X2EFmjoAmUE",
|
4 |
+
"created_at": "2025-07-13T14:40:45.815582",
|
5 |
+
"last_activity": "2025-07-13T14:49:54.108574"
|
6 |
+
},
|
7 |
+
"user_3": {
|
8 |
+
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidXNlcl8zIiwidXNlcm5hbWUiOiJhbmFudGh1IiwiZXhwIjoxNzUyNDI3MzMyfQ.GSrJR06gLnNW5whgYok7_gV1YJSbfd0Lpia7Z8z6jak",
|
9 |
+
"created_at": "2025-07-13T14:52:12.892422",
|
10 |
+
"last_activity": "2025-07-13T14:52:23.475883"
|
11 |
+
}
|
12 |
+
}
|
data/users.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"admin": {
|
3 |
+
"user_id": "admin_user",
|
4 |
+
"email": "[email protected]",
|
5 |
+
"password_hash": "$2b$12$/TYP5F17vDrP7.zOxr9lXe9rJvaxb0/mzwbH1xE565BKDqqewQkbi",
|
6 |
+
"created_at": "2025-07-10T19:51:03.507661",
|
7 |
+
"is_active": true,
|
8 |
+
"is_admin": true
|
9 |
+
},
|
10 |
+
"testuser": {
|
11 |
+
"user_id": "user_2",
|
12 |
+
"email": "[email protected]",
|
13 |
+
"password_hash": "$2b$12$fRl89gGOIcmEsvB1YpB4Geh0qYgU2NzJJc0y6PxznSIdK.EABInfm",
|
14 |
+
"created_at": "2025-07-11T13:49:43.931414",
|
15 |
+
"is_active": true
|
16 |
+
},
|
17 |
+
"ananthu": {
|
18 |
+
"user_id": "user_3",
|
19 |
+
"email": "[email protected]",
|
20 |
+
"password_hash": "$2b$12$0cFYqNGPCuohv4QjagqkPeRPPfpJo.WZ94h3SyEx0a/92jJnAz.3.",
|
21 |
+
"created_at": "2025-07-12T00:17:09.904328",
|
22 |
+
"is_active": true
|
23 |
+
}
|
24 |
+
}
|
docker-compose.yml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: '3.8'
|
2 |
+
|
3 |
+
services:
|
4 |
+
researchmate:
|
5 |
+
build: .
|
6 |
+
container_name: researchmate-app
|
7 |
+
ports:
|
8 |
+
- "8000:8000"
|
9 |
+
environment:
|
10 |
+
- GROQ_API_KEY=${GROQ_API_KEY}
|
11 |
+
- PYTHONPATH=/app
|
12 |
+
volumes:
|
13 |
+
- ./data:/app/data
|
14 |
+
- ./logs:/app/logs
|
15 |
+
- ./chroma_persist:/app/chroma_persist
|
16 |
+
- ./uploads:/app/uploads
|
17 |
+
restart: unless-stopped
|
18 |
+
healthcheck:
|
19 |
+
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
|
20 |
+
interval: 30s
|
21 |
+
timeout: 10s
|
22 |
+
retries: 3
|
23 |
+
start_period: 40s
|
24 |
+
networks:
|
25 |
+
- researchmate-network
|
26 |
+
|
27 |
+
networks:
|
28 |
+
researchmate-network:
|
29 |
+
driver: bridge
|
30 |
+
|
31 |
+
volumes:
|
32 |
+
data:
|
33 |
+
logs:
|
34 |
+
uploads:
|
35 |
+
chroma_persist:
|
logs/deployment.log
ADDED
@@ -0,0 +1,883 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
2025-07-09 12:16:18,745 - INFO - Starting ResearchMate deployment
|
2 |
+
2025-07-09 12:16:18,745 - INFO - Running: Checking Python version
|
3 |
+
2025-07-09 12:16:18,745 - INFO - Python version 3.11 is compatible
|
4 |
+
2025-07-09 12:16:18,746 - INFO - Running: Creating virtual environment
|
5 |
+
2025-07-09 12:16:18,746 - INFO - Virtual environment already exists
|
6 |
+
2025-07-09 12:16:18,747 - INFO - Running: Installing dependencies
|
7 |
+
2025-07-09 12:16:23,056 - ERROR - Failed to install dependencies: Command '['D:\\ResearchMate\\venv\\Scripts\\pip.exe', 'install', '--upgrade', 'pip']' returned non-zero exit status 1.
|
8 |
+
2025-07-09 12:16:23,056 - ERROR - Failed at step: Installing dependencies
|
9 |
+
2025-07-09 12:19:07,301 - INFO - Starting ResearchMate deployment
|
10 |
+
2025-07-09 12:19:07,323 - INFO - Running: Checking Python version
|
11 |
+
2025-07-09 12:19:07,323 - INFO - Python version 3.11 is compatible
|
12 |
+
2025-07-09 12:19:07,326 - INFO - Running: Creating virtual environment
|
13 |
+
2025-07-09 12:19:07,326 - INFO - Virtual environment already exists
|
14 |
+
2025-07-09 12:19:07,327 - INFO - Running: Installing dependencies
|
15 |
+
2025-07-09 12:19:07,409 - INFO - Upgrading pip...
|
16 |
+
2025-07-09 12:19:07,410 - ERROR - Unexpected error during dependency installation: [WinError 2] The system cannot find the file specified
|
17 |
+
2025-07-09 12:19:07,410 - ERROR - Failed at step: Installing dependencies
|
18 |
+
2025-07-09 15:08:53,823 - INFO - Starting ResearchMate deployment
|
19 |
+
2025-07-09 15:08:53,838 - INFO - Running: Checking Python version
|
20 |
+
2025-07-09 15:08:53,839 - INFO - Python version 3.11 is compatible
|
21 |
+
2025-07-09 15:08:53,839 - INFO - Running: Creating virtual environment
|
22 |
+
2025-07-09 15:08:53,841 - INFO - Virtual environment already exists
|
23 |
+
2025-07-09 15:08:53,841 - INFO - Running: Installing dependencies
|
24 |
+
2025-07-09 15:08:53,842 - INFO - Installing dependencies...
|
25 |
+
2025-07-09 15:08:53,843 - INFO - Upgrading pip...
|
26 |
+
2025-07-09 15:08:53,845 - ERROR - Unexpected error during dependency installation: [WinError 2] The system cannot find the file specified
|
27 |
+
2025-07-09 15:08:53,845 - ERROR - Failed at step: Installing dependencies
|
28 |
+
2025-07-09 15:10:19,237 - INFO - Starting ResearchMate deployment
|
29 |
+
2025-07-09 15:10:19,238 - INFO - Running: Checking Python version
|
30 |
+
2025-07-09 15:10:19,239 - INFO - Python version 3.11 is compatible
|
31 |
+
2025-07-09 15:10:19,239 - INFO - Running: Creating virtual environment
|
32 |
+
2025-07-09 15:10:19,241 - INFO - Virtual environment already exists
|
33 |
+
2025-07-09 15:10:19,241 - INFO - Running: Installing dependencies
|
34 |
+
2025-07-09 15:10:19,242 - INFO - Installing dependencies...
|
35 |
+
2025-07-09 15:10:19,242 - INFO - Upgrading pip...
|
36 |
+
2025-07-09 15:10:19,244 - ERROR - Unexpected error during dependency installation: [WinError 2] The system cannot find the file specified
|
37 |
+
2025-07-09 15:10:19,246 - ERROR - Failed at step: Installing dependencies
|
38 |
+
2025-07-09 15:10:32,863 - INFO - Starting ResearchMate deployment
|
39 |
+
2025-07-09 15:10:32,864 - INFO - Running: Checking Python version
|
40 |
+
2025-07-09 15:10:32,865 - INFO - Python version 3.11 is compatible
|
41 |
+
2025-07-09 15:10:32,866 - INFO - Running: Creating virtual environment
|
42 |
+
2025-07-09 15:10:32,867 - INFO - Virtual environment already exists
|
43 |
+
2025-07-09 15:10:32,867 - INFO - Running: Installing dependencies
|
44 |
+
2025-07-09 15:10:32,868 - INFO - Installing dependencies...
|
45 |
+
2025-07-09 15:10:32,869 - INFO - Upgrading pip...
|
46 |
+
2025-07-09 15:10:32,871 - ERROR - Unexpected error during dependency installation: [WinError 2] The system cannot find the file specified
|
47 |
+
2025-07-09 15:10:32,871 - ERROR - Failed at step: Installing dependencies
|
48 |
+
2025-07-09 16:17:37,389 - INFO - Running tests...
|
49 |
+
2025-07-09 16:17:37,392 - INFO - Found 3 test files
|
50 |
+
2025-07-09 16:17:37,394 - INFO - Using Python executable: D:\ResearchMate\venv\python.exe
|
51 |
+
2025-07-09 16:17:37,395 - INFO - Python executable exists: True
|
52 |
+
2025-07-09 16:17:37,395 - INFO - Running: test_arxiv_fetcher.py
|
53 |
+
2025-07-09 16:17:37,396 - INFO - Full test path: D:\ResearchMate\src\tests\test_arxiv_fetcher.py
|
54 |
+
2025-07-09 16:17:38,749 - INFO - PASS: test_arxiv_fetcher.py
|
55 |
+
2025-07-09 16:17:38,750 - INFO - Output:
|
56 |
+
PASS: ArXiv fetcher import test passed
|
57 |
+
PASS: ArXiv fetcher creation test passed
|
58 |
+
All ArXiv fetcher tests passed!
|
59 |
+
|
60 |
+
2025-07-09 16:17:38,751 - INFO - Running: test_config.py
|
61 |
+
2025-07-09 16:17:38,751 - INFO - Full test path: D:\ResearchMate\src\tests\test_config.py
|
62 |
+
2025-07-09 16:17:39,614 - INFO - PASS: test_config.py
|
63 |
+
2025-07-09 16:17:39,614 - INFO - Output:
|
64 |
+
PASS: Settings loading test passed
|
65 |
+
PASS: Default settings test passed
|
66 |
+
PASS: Settings types test passed
|
67 |
+
All configuration tests passed!
|
68 |
+
|
69 |
+
2025-07-09 16:17:39,615 - INFO - Running: test_pdf_processor.py
|
70 |
+
2025-07-09 16:17:39,615 - INFO - Full test path: D:\ResearchMate\src\tests\test_pdf_processor.py
|
71 |
+
2025-07-09 16:17:41,349 - INFO - PASS: test_pdf_processor.py
|
72 |
+
2025-07-09 16:17:41,350 - INFO - Output:
|
73 |
+
PASS: PDF processor import test passed
|
74 |
+
PDF Processor initialized with libraries: ['PyPDF2', 'pdfplumber', 'PyMuPDF']
|
75 |
+
PASS: PDF processor creation test passed
|
76 |
+
All PDF processor tests passed!
|
77 |
+
|
78 |
+
2025-07-09 16:17:41,350 - INFO - All tests passed successfully!
|
79 |
+
2025-07-09 16:17:55,109 - INFO - Starting ResearchMate deployment
|
80 |
+
2025-07-09 16:17:55,110 - INFO - Running: Checking Python version
|
81 |
+
2025-07-09 16:17:55,110 - INFO - Python version 3.11 is compatible
|
82 |
+
2025-07-09 16:17:55,110 - INFO - Running: Creating virtual environment
|
83 |
+
2025-07-09 16:17:55,112 - INFO - Virtual environment already exists
|
84 |
+
2025-07-09 16:17:55,112 - INFO - Running: Installing dependencies
|
85 |
+
2025-07-09 16:17:55,112 - INFO - Installing dependencies...
|
86 |
+
2025-07-09 16:17:55,113 - INFO - Upgrading pip...
|
87 |
+
2025-07-09 16:17:55,114 - ERROR - Unexpected error during dependency installation: [WinError 2] The system cannot find the file specified
|
88 |
+
2025-07-09 16:17:55,115 - ERROR - Failed at step: Installing dependencies
|
89 |
+
2025-07-09 16:21:19,167 - INFO - Starting ResearchMate deployment
|
90 |
+
2025-07-09 16:21:19,167 - INFO - Running: Checking Python version
|
91 |
+
2025-07-09 16:21:19,168 - INFO - Python version 3.11 is compatible
|
92 |
+
2025-07-09 16:21:19,168 - INFO - Running: Creating virtual environment
|
93 |
+
2025-07-09 16:21:19,169 - INFO - Virtual environment already exists
|
94 |
+
2025-07-09 16:21:19,170 - WARNING - Virtual environment exists but Python executable not found, recreating...
|
95 |
+
2025-07-09 16:21:58,044 - INFO - Starting ResearchMate deployment
|
96 |
+
2025-07-09 16:21:58,045 - INFO - Running: Checking Python version
|
97 |
+
2025-07-09 16:21:58,045 - INFO - Python version 3.11 is compatible
|
98 |
+
2025-07-09 16:21:58,046 - INFO - Running: Creating virtual environment
|
99 |
+
2025-07-09 16:21:58,047 - INFO - Virtual environment already exists
|
100 |
+
2025-07-09 16:21:58,048 - WARNING - Running from within virtual environment, cannot recreate. Assuming it's properly set up.
|
101 |
+
2025-07-09 16:21:58,048 - INFO - Running: Installing dependencies
|
102 |
+
2025-07-09 16:21:58,049 - INFO - Installing dependencies...
|
103 |
+
2025-07-09 16:21:58,050 - ERROR - Python executable not found at: D:\ResearchMate\venv\Scripts\python.exe
|
104 |
+
2025-07-09 16:21:58,051 - ERROR - Failed at step: Installing dependencies
|
105 |
+
2025-07-09 16:24:34,162 - INFO - Starting ResearchMate deployment
|
106 |
+
2025-07-09 16:24:34,164 - INFO - Running: Checking Python version
|
107 |
+
2025-07-09 16:24:34,164 - INFO - Python version 3.11 is compatible
|
108 |
+
2025-07-09 16:24:34,164 - INFO - Running: Creating virtual environment
|
109 |
+
2025-07-09 16:24:34,165 - INFO - Virtual environment already exists
|
110 |
+
2025-07-09 16:24:34,166 - WARNING - Running from within virtual environment, cannot recreate. Assuming it's properly set up.
|
111 |
+
2025-07-09 16:24:34,168 - INFO - Running: Installing dependencies
|
112 |
+
2025-07-09 16:24:34,168 - INFO - Installing dependencies...
|
113 |
+
2025-07-09 16:24:34,168 - ERROR - Python executable not found at: D:\ResearchMate\venv\Scripts\python.exe
|
114 |
+
2025-07-09 16:24:34,169 - ERROR - Failed at step: Installing dependencies
|
115 |
+
2025-07-09 16:28:16,541 - INFO - Starting ResearchMate deployment
|
116 |
+
2025-07-09 16:28:16,564 - INFO - Running: Checking Python version
|
117 |
+
2025-07-09 16:28:16,565 - INFO - Python version 3.11 is compatible
|
118 |
+
2025-07-09 16:28:16,565 - INFO - Running: Creating virtual environment
|
119 |
+
2025-07-09 16:28:16,566 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
120 |
+
2025-07-09 16:28:16,566 - INFO - Running: Installing dependencies
|
121 |
+
2025-07-09 16:28:16,566 - INFO - Installing dependencies...
|
122 |
+
2025-07-09 16:28:16,567 - INFO - Running from within virtual environment, using current Python executable
|
123 |
+
2025-07-09 16:28:16,568 - INFO - Conda environment detected: D:\ResearchMate\venv
|
124 |
+
2025-07-09 16:28:16,568 - INFO - Upgrading pip...
|
125 |
+
2025-07-09 16:28:21,559 - WARNING - Pip upgrade failed, continuing with current version: Traceback (most recent call last):
|
126 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
127 |
+
File "<frozen runpy>", line 88, in _run_code
|
128 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\__main__.py", line 24, in <module>
|
129 |
+
sys.exit(_main())
|
130 |
+
^^^^^^^
|
131 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\main.py", line 77, in main
|
132 |
+
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
|
133 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
134 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\__init__.py", line 119, in create_command
|
135 |
+
module = importlib.import_module(module_path)
|
136 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
137 |
+
File "D:\ResearchMate\venv\Lib\importlib\__init__.py", line 126, in import_module
|
138 |
+
return _bootstrap._gcd_import(name[level:], package, level)
|
139 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
140 |
+
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
|
141 |
+
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
|
142 |
+
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
|
143 |
+
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
|
144 |
+
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
|
145 |
+
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
|
146 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\install.py", line 20, in <module>
|
147 |
+
import pip._internal.self_outdated_check # noqa: F401
|
148 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
149 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\self_outdated_check.py", line 19, in <module>
|
150 |
+
from pip._internal.index.package_finder import PackageFinder
|
151 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\index\package_finder.py", line 41, in <module>
|
152 |
+
from pip._internal.req import InstallRequirement
|
153 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\__init__.py", line 6, in <module>
|
154 |
+
from pip._internal.cli.progress_bars import get_install_progress_renderer
|
155 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 20, in <module>
|
156 |
+
from pip._internal.req.req_install import InstallRequirement
|
157 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\req_install.py", line 40, in <module>
|
158 |
+
from pip._internal.operations.install.wheel import install_wheel
|
159 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\operations\install\wheel.py", line 39, in <module>
|
160 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
161 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\scripts.py", line 16, in <module>
|
162 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
163 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\compat.py", line 81, in <module>
|
164 |
+
import xmlrpc.client as xmlrpclib
|
165 |
+
File "D:\ResearchMate\venv\Lib\xmlrpc\client.py", line 138, in <module>
|
166 |
+
from xml.parsers import expat
|
167 |
+
File "D:\ResearchMate\venv\Lib\xml\parsers\expat.py", line 4, in <module>
|
168 |
+
from pyexpat import *
|
169 |
+
ModuleNotFoundError: No module named 'pyexpat'
|
170 |
+
|
171 |
+
2025-07-09 16:28:21,562 - INFO - Installing requirements from requirements.txt...
|
172 |
+
2025-07-09 16:28:23,230 - ERROR - Failed to install dependencies: Traceback (most recent call last):
|
173 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
174 |
+
File "<frozen runpy>", line 88, in _run_code
|
175 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\__main__.py", line 24, in <module>
|
176 |
+
sys.exit(_main())
|
177 |
+
^^^^^^^
|
178 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\main.py", line 77, in main
|
179 |
+
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
|
180 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
181 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\__init__.py", line 119, in create_command
|
182 |
+
module = importlib.import_module(module_path)
|
183 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
184 |
+
File "D:\ResearchMate\venv\Lib\importlib\__init__.py", line 126, in import_module
|
185 |
+
return _bootstrap._gcd_import(name[level:], package, level)
|
186 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
187 |
+
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
|
188 |
+
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
|
189 |
+
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
|
190 |
+
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
|
191 |
+
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
|
192 |
+
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
|
193 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\install.py", line 20, in <module>
|
194 |
+
import pip._internal.self_outdated_check # noqa: F401
|
195 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
196 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\self_outdated_check.py", line 19, in <module>
|
197 |
+
from pip._internal.index.package_finder import PackageFinder
|
198 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\index\package_finder.py", line 41, in <module>
|
199 |
+
from pip._internal.req import InstallRequirement
|
200 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\__init__.py", line 6, in <module>
|
201 |
+
from pip._internal.cli.progress_bars import get_install_progress_renderer
|
202 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 20, in <module>
|
203 |
+
from pip._internal.req.req_install import InstallRequirement
|
204 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\req_install.py", line 40, in <module>
|
205 |
+
from pip._internal.operations.install.wheel import install_wheel
|
206 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\operations\install\wheel.py", line 39, in <module>
|
207 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
208 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\scripts.py", line 16, in <module>
|
209 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
210 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\compat.py", line 81, in <module>
|
211 |
+
import xmlrpc.client as xmlrpclib
|
212 |
+
File "D:\ResearchMate\venv\Lib\xmlrpc\client.py", line 138, in <module>
|
213 |
+
from xml.parsers import expat
|
214 |
+
File "D:\ResearchMate\venv\Lib\xml\parsers\expat.py", line 4, in <module>
|
215 |
+
from pyexpat import *
|
216 |
+
ModuleNotFoundError: No module named 'pyexpat'
|
217 |
+
|
218 |
+
2025-07-09 16:28:23,232 - ERROR - Failed at step: Installing dependencies
|
219 |
+
2025-07-09 16:29:45,953 - INFO - Starting ResearchMate deployment
|
220 |
+
2025-07-09 16:29:45,954 - INFO - Running: Checking Python version
|
221 |
+
2025-07-09 16:29:45,954 - INFO - Python version 3.11 is compatible
|
222 |
+
2025-07-09 16:29:45,954 - INFO - Running: Creating virtual environment
|
223 |
+
2025-07-09 16:29:45,955 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
224 |
+
2025-07-09 16:29:45,955 - INFO - Running: Installing dependencies
|
225 |
+
2025-07-09 16:29:45,956 - INFO - Installing dependencies...
|
226 |
+
2025-07-09 16:29:45,956 - INFO - Running from within virtual environment, using current Python executable
|
227 |
+
2025-07-09 16:29:45,957 - INFO - Conda environment detected: D:\ResearchMate\venv
|
228 |
+
2025-07-09 16:29:45,957 - INFO - Upgrading pip...
|
229 |
+
2025-07-09 16:29:47,972 - WARNING - Pip upgrade failed, continuing with current version: Traceback (most recent call last):
|
230 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
231 |
+
File "<frozen runpy>", line 88, in _run_code
|
232 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\__main__.py", line 24, in <module>
|
233 |
+
sys.exit(_main())
|
234 |
+
^^^^^^^
|
235 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\main.py", line 77, in main
|
236 |
+
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
|
237 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
238 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\__init__.py", line 119, in create_command
|
239 |
+
module = importlib.import_module(module_path)
|
240 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
241 |
+
File "D:\ResearchMate\venv\Lib\importlib\__init__.py", line 126, in import_module
|
242 |
+
return _bootstrap._gcd_import(name[level:], package, level)
|
243 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
244 |
+
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
|
245 |
+
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
|
246 |
+
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
|
247 |
+
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
|
248 |
+
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
|
249 |
+
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
|
250 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\install.py", line 20, in <module>
|
251 |
+
import pip._internal.self_outdated_check # noqa: F401
|
252 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
253 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\self_outdated_check.py", line 19, in <module>
|
254 |
+
from pip._internal.index.package_finder import PackageFinder
|
255 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\index\package_finder.py", line 41, in <module>
|
256 |
+
from pip._internal.req import InstallRequirement
|
257 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\__init__.py", line 6, in <module>
|
258 |
+
from pip._internal.cli.progress_bars import get_install_progress_renderer
|
259 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 20, in <module>
|
260 |
+
from pip._internal.req.req_install import InstallRequirement
|
261 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\req_install.py", line 40, in <module>
|
262 |
+
from pip._internal.operations.install.wheel import install_wheel
|
263 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\operations\install\wheel.py", line 39, in <module>
|
264 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
265 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\scripts.py", line 16, in <module>
|
266 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
267 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\compat.py", line 81, in <module>
|
268 |
+
import xmlrpc.client as xmlrpclib
|
269 |
+
File "D:\ResearchMate\venv\Lib\xmlrpc\client.py", line 138, in <module>
|
270 |
+
from xml.parsers import expat
|
271 |
+
File "D:\ResearchMate\venv\Lib\xml\parsers\expat.py", line 4, in <module>
|
272 |
+
from pyexpat import *
|
273 |
+
ModuleNotFoundError: No module named 'pyexpat'
|
274 |
+
|
275 |
+
2025-07-09 16:29:47,975 - INFO - Installing requirements from requirements.txt...
|
276 |
+
2025-07-09 16:29:49,762 - ERROR - Failed to install dependencies: Traceback (most recent call last):
|
277 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
278 |
+
File "<frozen runpy>", line 88, in _run_code
|
279 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\__main__.py", line 24, in <module>
|
280 |
+
sys.exit(_main())
|
281 |
+
^^^^^^^
|
282 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\main.py", line 77, in main
|
283 |
+
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
|
284 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
285 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\__init__.py", line 119, in create_command
|
286 |
+
module = importlib.import_module(module_path)
|
287 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
288 |
+
File "D:\ResearchMate\venv\Lib\importlib\__init__.py", line 126, in import_module
|
289 |
+
return _bootstrap._gcd_import(name[level:], package, level)
|
290 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
291 |
+
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
|
292 |
+
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
|
293 |
+
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
|
294 |
+
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
|
295 |
+
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
|
296 |
+
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
|
297 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\install.py", line 20, in <module>
|
298 |
+
import pip._internal.self_outdated_check # noqa: F401
|
299 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
300 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\self_outdated_check.py", line 19, in <module>
|
301 |
+
from pip._internal.index.package_finder import PackageFinder
|
302 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\index\package_finder.py", line 41, in <module>
|
303 |
+
from pip._internal.req import InstallRequirement
|
304 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\__init__.py", line 6, in <module>
|
305 |
+
from pip._internal.cli.progress_bars import get_install_progress_renderer
|
306 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 20, in <module>
|
307 |
+
from pip._internal.req.req_install import InstallRequirement
|
308 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\req_install.py", line 40, in <module>
|
309 |
+
from pip._internal.operations.install.wheel import install_wheel
|
310 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\operations\install\wheel.py", line 39, in <module>
|
311 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
312 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\scripts.py", line 16, in <module>
|
313 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
314 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\compat.py", line 81, in <module>
|
315 |
+
import xmlrpc.client as xmlrpclib
|
316 |
+
File "D:\ResearchMate\venv\Lib\xmlrpc\client.py", line 138, in <module>
|
317 |
+
from xml.parsers import expat
|
318 |
+
File "D:\ResearchMate\venv\Lib\xml\parsers\expat.py", line 4, in <module>
|
319 |
+
from pyexpat import *
|
320 |
+
ModuleNotFoundError: No module named 'pyexpat'
|
321 |
+
|
322 |
+
2025-07-09 16:29:49,765 - ERROR - Failed at step: Installing dependencies
|
323 |
+
2025-07-09 16:36:59,244 - INFO - Starting ResearchMate deployment
|
324 |
+
2025-07-09 16:36:59,245 - INFO - Running: Checking Python version
|
325 |
+
2025-07-09 16:36:59,246 - INFO - Python version 3.11 is compatible
|
326 |
+
2025-07-09 16:36:59,247 - INFO - Running: Creating virtual environment
|
327 |
+
2025-07-09 16:36:59,247 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
328 |
+
2025-07-09 16:36:59,248 - INFO - Running: Installing dependencies
|
329 |
+
2025-07-09 16:36:59,248 - INFO - Installing dependencies...
|
330 |
+
2025-07-09 16:36:59,249 - INFO - Running from within virtual environment, using current Python executable
|
331 |
+
2025-07-09 16:36:59,249 - INFO - Conda environment detected: D:\ResearchMate\venv
|
332 |
+
2025-07-09 16:36:59,250 - INFO - Skipping pip upgrade in Conda environment
|
333 |
+
2025-07-09 16:36:59,251 - INFO - Installing requirements from requirements.txt...
|
334 |
+
2025-07-09 16:36:59,251 - INFO - Using --no-deps flag for Conda environment
|
335 |
+
2025-07-09 16:37:01,215 - ERROR - Failed to install dependencies: Traceback (most recent call last):
|
336 |
+
File "<frozen runpy>", line 198, in _run_module_as_main
|
337 |
+
File "<frozen runpy>", line 88, in _run_code
|
338 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\__main__.py", line 24, in <module>
|
339 |
+
sys.exit(_main())
|
340 |
+
^^^^^^^
|
341 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\main.py", line 77, in main
|
342 |
+
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
|
343 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
344 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\__init__.py", line 119, in create_command
|
345 |
+
module = importlib.import_module(module_path)
|
346 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
347 |
+
File "D:\ResearchMate\venv\Lib\importlib\__init__.py", line 126, in import_module
|
348 |
+
return _bootstrap._gcd_import(name[level:], package, level)
|
349 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
350 |
+
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
|
351 |
+
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
|
352 |
+
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
|
353 |
+
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
|
354 |
+
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
|
355 |
+
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
|
356 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\commands\install.py", line 20, in <module>
|
357 |
+
import pip._internal.self_outdated_check # noqa: F401
|
358 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
359 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\self_outdated_check.py", line 19, in <module>
|
360 |
+
from pip._internal.index.package_finder import PackageFinder
|
361 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\index\package_finder.py", line 41, in <module>
|
362 |
+
from pip._internal.req import InstallRequirement
|
363 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\__init__.py", line 6, in <module>
|
364 |
+
from pip._internal.cli.progress_bars import get_install_progress_renderer
|
365 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 20, in <module>
|
366 |
+
from pip._internal.req.req_install import InstallRequirement
|
367 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\req\req_install.py", line 40, in <module>
|
368 |
+
from pip._internal.operations.install.wheel import install_wheel
|
369 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_internal\operations\install\wheel.py", line 39, in <module>
|
370 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
371 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\scripts.py", line 16, in <module>
|
372 |
+
from .compat import sysconfig, detect_encoding, ZipFile
|
373 |
+
File "D:\ResearchMate\venv\Lib\site-packages\pip\_vendor\distlib\compat.py", line 81, in <module>
|
374 |
+
import xmlrpc.client as xmlrpclib
|
375 |
+
File "D:\ResearchMate\venv\Lib\xmlrpc\client.py", line 138, in <module>
|
376 |
+
from xml.parsers import expat
|
377 |
+
File "D:\ResearchMate\venv\Lib\xml\parsers\expat.py", line 4, in <module>
|
378 |
+
from pyexpat import *
|
379 |
+
ModuleNotFoundError: No module named 'pyexpat'
|
380 |
+
|
381 |
+
2025-07-09 16:37:01,217 - INFO - Attempting fallback installation of critical packages...
|
382 |
+
2025-07-09 16:37:01,218 - INFO - Installing critical packages individually...
|
383 |
+
2025-07-09 16:37:03,079 - WARNING - Failed to install fastapi: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'fastapi', '--no-deps']' returned non-zero exit status 1.
|
384 |
+
2025-07-09 16:37:05,052 - WARNING - Failed to install uvicorn: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'uvicorn', '--no-deps']' returned non-zero exit status 1.
|
385 |
+
2025-07-09 16:37:07,125 - WARNING - Failed to install pydantic: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'pydantic', '--no-deps']' returned non-zero exit status 1.
|
386 |
+
2025-07-09 16:37:08,896 - WARNING - Failed to install jinja2: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'jinja2', '--no-deps']' returned non-zero exit status 1.
|
387 |
+
2025-07-09 16:37:10,698 - WARNING - Failed to install python-dotenv: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'python-dotenv', '--no-deps']' returned non-zero exit status 1.
|
388 |
+
2025-07-09 16:37:12,589 - WARNING - Failed to install groq: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'groq', '--no-deps']' returned non-zero exit status 1.
|
389 |
+
2025-07-09 16:37:14,272 - WARNING - Failed to install requests: Command '['D:\\ResearchMate\\venv\\python.exe', '-m', 'pip', 'install', 'requests', '--no-deps']' returned non-zero exit status 1.
|
390 |
+
2025-07-09 16:37:14,274 - INFO - Running: Creating directories
|
391 |
+
2025-07-09 16:37:14,275 - INFO - Creating directories...
|
392 |
+
2025-07-09 16:37:14,276 - INFO - Created directory: uploads
|
393 |
+
2025-07-09 16:37:14,277 - INFO - Created directory: chroma_db
|
394 |
+
2025-07-09 16:37:14,278 - INFO - Created directory: chroma_persist
|
395 |
+
2025-07-09 16:37:14,280 - INFO - Created directory: logs
|
396 |
+
2025-07-09 16:37:14,285 - INFO - Created directory: static/uploads
|
397 |
+
2025-07-09 16:37:14,289 - INFO - Created directory: data
|
398 |
+
2025-07-09 16:37:14,291 - INFO - Running: Checking environment variables
|
399 |
+
2025-07-09 16:37:14,292 - INFO - Checking environment variables...
|
400 |
+
2025-07-09 16:37:14,294 - WARNING - Missing environment variables:
|
401 |
+
2025-07-09 16:37:14,295 - WARNING - - GROQ_API_KEY
|
402 |
+
2025-07-09 16:37:14,296 - INFO - Please set the missing variables:
|
403 |
+
2025-07-09 16:37:14,297 - INFO - set GROQ_API_KEY=your_value_here
|
404 |
+
2025-07-09 16:37:14,298 - INFO - Get your Groq API key from: https://console.groq.com/keys
|
405 |
+
2025-07-09 16:37:14,298 - ERROR - Failed at step: Checking environment variables
|
406 |
+
2025-07-09 17:04:51,797 - INFO - Starting ResearchMate deployment
|
407 |
+
2025-07-09 17:04:51,817 - INFO - Running: Checking Python version
|
408 |
+
2025-07-09 17:04:51,817 - INFO - Python version 3.11 is compatible
|
409 |
+
2025-07-09 17:04:51,817 - INFO - Running: Creating virtual environment
|
410 |
+
2025-07-09 17:04:51,817 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
411 |
+
2025-07-09 17:04:51,821 - INFO - Running: Installing dependencies
|
412 |
+
2025-07-09 17:04:51,821 - INFO - Installing dependencies...
|
413 |
+
2025-07-09 17:04:51,821 - INFO - Running from within virtual environment, using current Python executable
|
414 |
+
2025-07-09 17:04:51,822 - INFO - Conda environment detected: D:\ResearchMate\venv
|
415 |
+
2025-07-09 17:04:51,822 - INFO - Skipping pip upgrade in Conda environment
|
416 |
+
2025-07-09 17:04:51,822 - INFO - Installing requirements from requirements.txt...
|
417 |
+
2025-07-09 17:04:51,822 - INFO - Using --no-deps flag for Conda environment
|
418 |
+
2025-07-09 17:04:56,929 - INFO - Requirements installed successfully
|
419 |
+
2025-07-09 17:04:56,929 - INFO - Dependencies installed successfully
|
420 |
+
2025-07-09 17:04:56,935 - INFO - Running: Creating directories
|
421 |
+
2025-07-09 17:04:56,935 - INFO - Creating directories...
|
422 |
+
2025-07-09 17:04:56,935 - INFO - Created directory: uploads
|
423 |
+
2025-07-09 17:04:56,936 - INFO - Created directory: chroma_db
|
424 |
+
2025-07-09 17:04:56,936 - INFO - Created directory: chroma_persist
|
425 |
+
2025-07-09 17:04:56,936 - INFO - Created directory: logs
|
426 |
+
2025-07-09 17:04:56,936 - INFO - Created directory: static/uploads
|
427 |
+
2025-07-09 17:04:56,936 - INFO - Created directory: data
|
428 |
+
2025-07-09 17:04:56,936 - INFO - Running: Checking environment variables
|
429 |
+
2025-07-09 17:04:56,936 - INFO - Checking environment variables...
|
430 |
+
2025-07-09 17:04:56,936 - WARNING - Missing environment variables:
|
431 |
+
2025-07-09 17:04:56,936 - WARNING - - GROQ_API_KEY
|
432 |
+
2025-07-09 17:04:56,936 - INFO - Please set the missing variables:
|
433 |
+
2025-07-09 17:04:56,936 - INFO - set GROQ_API_KEY=your_value_here
|
434 |
+
2025-07-09 17:04:56,936 - INFO - Get your Groq API key from: https://console.groq.com/keys
|
435 |
+
2025-07-09 17:04:56,936 - ERROR - Failed at step: Checking environment variables
|
436 |
+
2025-07-09 17:26:48,433 - INFO - Starting ResearchMate deployment
|
437 |
+
2025-07-09 17:26:48,438 - INFO - Running: Checking Python version
|
438 |
+
2025-07-09 17:26:48,438 - INFO - Python version 3.11 is compatible
|
439 |
+
2025-07-09 17:26:48,438 - INFO - Running: Creating virtual environment
|
440 |
+
2025-07-09 17:26:48,438 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
441 |
+
2025-07-09 17:26:48,438 - INFO - Running: Installing dependencies
|
442 |
+
2025-07-09 17:26:48,438 - INFO - Installing dependencies...
|
443 |
+
2025-07-09 17:26:48,438 - INFO - Running from within virtual environment, using current Python executable
|
444 |
+
2025-07-09 17:26:48,438 - INFO - Conda environment detected: D:\ResearchMate\venv
|
445 |
+
2025-07-09 17:26:48,438 - INFO - Skipping pip upgrade in Conda environment
|
446 |
+
2025-07-09 17:26:48,438 - INFO - Installing requirements from requirements.txt...
|
447 |
+
2025-07-09 17:26:48,438 - INFO - Using --no-deps flag for Conda environment
|
448 |
+
2025-07-09 17:26:50,812 - INFO - Requirements installed successfully
|
449 |
+
2025-07-09 17:26:50,812 - INFO - Dependencies installed successfully
|
450 |
+
2025-07-09 17:26:50,812 - INFO - Running: Creating directories
|
451 |
+
2025-07-09 17:26:50,824 - INFO - Creating directories...
|
452 |
+
2025-07-09 17:26:50,824 - INFO - Created directory: uploads
|
453 |
+
2025-07-09 17:26:50,827 - INFO - Created directory: chroma_db
|
454 |
+
2025-07-09 17:26:50,827 - INFO - Created directory: chroma_persist
|
455 |
+
2025-07-09 17:26:50,828 - INFO - Created directory: logs
|
456 |
+
2025-07-09 17:26:50,828 - INFO - Created directory: backups
|
457 |
+
2025-07-09 17:26:50,829 - INFO - Created directory: config
|
458 |
+
2025-07-09 17:26:50,829 - INFO - Verified src/static directory exists
|
459 |
+
2025-07-09 17:26:50,830 - INFO - Running: Checking environment variables
|
460 |
+
2025-07-09 17:26:50,830 - INFO - Checking environment variables...
|
461 |
+
2025-07-09 17:26:50,830 - WARNING - Missing environment variables:
|
462 |
+
2025-07-09 17:26:50,831 - WARNING - - GROQ_API_KEY
|
463 |
+
2025-07-09 17:26:50,831 - INFO - Please set the missing variables:
|
464 |
+
2025-07-09 17:26:50,831 - INFO - set GROQ_API_KEY=your_value_here
|
465 |
+
2025-07-09 17:26:50,831 - INFO - Get your Groq API key from: https://console.groq.com/keys
|
466 |
+
2025-07-09 17:26:50,831 - ERROR - Failed at step: Checking environment variables
|
467 |
+
2025-07-09 17:33:49,684 - INFO - Loaded environment variables from D:\ResearchMate\.env
|
468 |
+
2025-07-09 17:33:49,693 - INFO - Starting ResearchMate deployment
|
469 |
+
2025-07-09 17:33:49,693 - INFO - Running: Checking Python version
|
470 |
+
2025-07-09 17:33:49,693 - INFO - Python version 3.11 is compatible
|
471 |
+
2025-07-09 17:33:49,693 - INFO - Running: Creating virtual environment
|
472 |
+
2025-07-09 17:33:49,693 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
473 |
+
2025-07-09 17:33:49,693 - INFO - Running: Installing dependencies
|
474 |
+
2025-07-09 17:33:49,693 - INFO - Installing dependencies...
|
475 |
+
2025-07-09 17:33:49,693 - INFO - Running from within virtual environment, using current Python executable
|
476 |
+
2025-07-09 17:33:49,693 - INFO - Conda environment detected: D:\ResearchMate\venv
|
477 |
+
2025-07-09 17:33:49,693 - INFO - Skipping pip upgrade in Conda environment
|
478 |
+
2025-07-09 17:33:49,697 - INFO - Installing requirements from requirements.txt...
|
479 |
+
2025-07-09 17:33:49,697 - INFO - Using --no-deps flag for Conda environment
|
480 |
+
2025-07-09 17:33:53,686 - INFO - Requirements installed successfully
|
481 |
+
2025-07-09 17:33:53,686 - INFO - Dependencies installed successfully
|
482 |
+
2025-07-09 17:33:53,686 - INFO - Running: Creating directories
|
483 |
+
2025-07-09 17:33:53,687 - INFO - Creating directories...
|
484 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: uploads
|
485 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: chroma_db
|
486 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: chroma_persist
|
487 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: logs
|
488 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: backups
|
489 |
+
2025-07-09 17:33:53,687 - INFO - Created directory: config
|
490 |
+
2025-07-09 17:33:53,687 - INFO - Verified src/static directory exists
|
491 |
+
2025-07-09 17:33:53,687 - INFO - Running: Checking environment variables
|
492 |
+
2025-07-09 17:33:53,687 - INFO - Checking environment variables...
|
493 |
+
2025-07-09 17:33:53,687 - INFO - All required environment variables are set
|
494 |
+
2025-07-09 17:33:53,687 - INFO - Running: Testing imports
|
495 |
+
2025-07-09 17:33:53,687 - INFO - Testing imports...
|
496 |
+
2025-07-09 17:33:53,913 - ERROR - Import test failed: Traceback (most recent call last):
|
497 |
+
File "D:\ResearchMate\src\components\config.py", line 121, in <module>
|
498 |
+
print("\u2705 Configuration validated successfully")
|
499 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
500 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
501 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
502 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 0: character maps to <undefined>
|
503 |
+
|
504 |
+
During handling of the above exception, another exception occurred:
|
505 |
+
|
506 |
+
Traceback (most recent call last):
|
507 |
+
File "<string>", line 5, in <module>
|
508 |
+
File "D:\ResearchMate\src\components\__init__.py", line 6, in <module>
|
509 |
+
from .config import Config
|
510 |
+
File "D:\ResearchMate\src\components\config.py", line 123, in <module>
|
511 |
+
print(f"\u274c Configuration error: {e}")
|
512 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
513 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
514 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
515 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u274c' in position 0: character maps to <undefined>
|
516 |
+
|
517 |
+
2025-07-09 17:33:53,913 - ERROR - Failed at step: Testing imports
|
518 |
+
2025-07-09 17:34:47,863 - INFO - Loaded environment variables from D:\ResearchMate\.env
|
519 |
+
2025-07-09 17:34:47,863 - INFO - Starting ResearchMate deployment
|
520 |
+
2025-07-09 17:34:47,863 - INFO - Running: Checking Python version
|
521 |
+
2025-07-09 17:34:47,864 - INFO - Python version 3.11 is compatible
|
522 |
+
2025-07-09 17:34:47,864 - INFO - Running: Creating virtual environment
|
523 |
+
2025-07-09 17:34:47,864 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
524 |
+
2025-07-09 17:34:47,864 - INFO - Running: Installing dependencies
|
525 |
+
2025-07-09 17:34:47,864 - INFO - Installing dependencies...
|
526 |
+
2025-07-09 17:34:47,865 - INFO - Running from within virtual environment, using current Python executable
|
527 |
+
2025-07-09 17:34:47,865 - INFO - Conda environment detected: D:\ResearchMate\venv
|
528 |
+
2025-07-09 17:34:47,865 - INFO - Skipping pip upgrade in Conda environment
|
529 |
+
2025-07-09 17:34:47,865 - INFO - Installing requirements from requirements.txt...
|
530 |
+
2025-07-09 17:34:47,865 - INFO - Using --no-deps flag for Conda environment
|
531 |
+
2025-07-09 17:34:49,404 - INFO - Requirements installed successfully
|
532 |
+
2025-07-09 17:34:49,404 - INFO - Dependencies installed successfully
|
533 |
+
2025-07-09 17:34:49,404 - INFO - Running: Creating directories
|
534 |
+
2025-07-09 17:34:49,404 - INFO - Creating directories...
|
535 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: uploads
|
536 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: chroma_db
|
537 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: chroma_persist
|
538 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: logs
|
539 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: backups
|
540 |
+
2025-07-09 17:34:49,406 - INFO - Created directory: config
|
541 |
+
2025-07-09 17:34:49,406 - INFO - Verified src/static directory exists
|
542 |
+
2025-07-09 17:34:49,409 - INFO - Running: Checking environment variables
|
543 |
+
2025-07-09 17:34:49,409 - INFO - Checking environment variables...
|
544 |
+
2025-07-09 17:34:49,409 - INFO - All required environment variables are set
|
545 |
+
2025-07-09 17:34:49,409 - INFO - Running: Testing imports
|
546 |
+
2025-07-09 17:34:49,409 - INFO - Testing imports...
|
547 |
+
2025-07-09 17:34:57,899 - ERROR - Import test failed:
|
548 |
+
2025-07-09 17:34:57,899 - ERROR - Failed at step: Testing imports
|
549 |
+
2025-07-09 17:38:29,124 - INFO - Loaded environment variables from D:\ResearchMate\.env
|
550 |
+
2025-07-09 17:38:29,124 - INFO - Starting ResearchMate deployment
|
551 |
+
2025-07-09 17:38:29,124 - INFO - Running: Checking Python version
|
552 |
+
2025-07-09 17:38:29,124 - INFO - Python version 3.11 is compatible
|
553 |
+
2025-07-09 17:38:29,128 - INFO - Running: Creating virtual environment
|
554 |
+
2025-07-09 17:38:29,128 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
555 |
+
2025-07-09 17:38:29,128 - INFO - Running: Installing dependencies
|
556 |
+
2025-07-09 17:38:29,128 - INFO - Installing dependencies...
|
557 |
+
2025-07-09 17:38:29,128 - INFO - Running from within virtual environment, using current Python executable
|
558 |
+
2025-07-09 17:38:29,128 - INFO - Conda environment detected: D:\ResearchMate\venv
|
559 |
+
2025-07-09 17:38:29,128 - INFO - Skipping pip upgrade in Conda environment
|
560 |
+
2025-07-09 17:38:29,128 - INFO - Installing requirements from requirements.txt...
|
561 |
+
2025-07-09 17:38:29,128 - INFO - Using --no-deps flag for Conda environment
|
562 |
+
2025-07-09 17:38:30,738 - INFO - Requirements installed successfully
|
563 |
+
2025-07-09 17:38:30,738 - INFO - Dependencies installed successfully
|
564 |
+
2025-07-09 17:38:30,738 - INFO - Running: Creating directories
|
565 |
+
2025-07-09 17:38:30,738 - INFO - Creating directories...
|
566 |
+
2025-07-09 17:38:30,738 - INFO - Created directory: uploads
|
567 |
+
2025-07-09 17:38:30,743 - INFO - Created directory: chroma_db
|
568 |
+
2025-07-09 17:38:30,743 - INFO - Created directory: chroma_persist
|
569 |
+
2025-07-09 17:38:30,743 - INFO - Created directory: logs
|
570 |
+
2025-07-09 17:38:30,744 - INFO - Created directory: backups
|
571 |
+
2025-07-09 17:38:30,744 - INFO - Created directory: config
|
572 |
+
2025-07-09 17:38:30,744 - INFO - Verified src/static directory exists
|
573 |
+
2025-07-09 17:38:30,744 - INFO - Running: Checking environment variables
|
574 |
+
2025-07-09 17:38:30,745 - INFO - Checking environment variables...
|
575 |
+
2025-07-09 17:38:30,745 - INFO - All required environment variables are set
|
576 |
+
2025-07-09 17:38:30,745 - INFO - Running: Testing imports
|
577 |
+
2025-07-09 17:38:30,745 - INFO - Testing imports...
|
578 |
+
2025-07-09 17:38:34,277 - INFO - All imports successful
|
579 |
+
2025-07-09 17:38:34,280 - INFO - Deployment completed successfully!
|
580 |
+
2025-07-09 17:38:34,280 - INFO - Web Interface: http://localhost:8000
|
581 |
+
2025-07-09 17:38:34,280 - INFO - API Documentation: http://localhost:8000/docs
|
582 |
+
2025-07-09 17:38:34,280 - INFO - Use Ctrl+C to stop the server
|
583 |
+
2025-07-09 17:38:34,290 - INFO - Starting server on 0.0.0.0:8000
|
584 |
+
2025-07-09 17:39:52,314 - INFO - Server stopped by user
|
585 |
+
2025-07-09 17:39:55,924 - INFO - Starting ResearchMate development server
|
586 |
+
2025-07-09 17:39:55,924 - ERROR - Virtual environment not found. Please run deployment first.
|
587 |
+
2025-07-09 17:39:55,924 - INFO - Run: python scripts/deploy.py
|
588 |
+
2025-07-09 17:42:49,815 - INFO - Starting ResearchMate development server
|
589 |
+
2025-07-09 17:42:49,815 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
590 |
+
2025-07-09 17:42:49,815 - INFO - Starting server on 127.0.0.1:8000
|
591 |
+
2025-07-09 17:42:49,826 - INFO - File watcher started
|
592 |
+
2025-07-09 17:42:49,826 - INFO - Development server started successfully!
|
593 |
+
2025-07-09 17:42:49,826 - INFO - Web Interface: http://127.0.0.1:8000
|
594 |
+
2025-07-09 17:42:49,826 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
595 |
+
2025-07-09 17:42:49,828 - INFO - Auto-reload enabled
|
596 |
+
2025-07-09 17:42:49,828 - INFO - Use Ctrl+C to stop
|
597 |
+
2025-07-09 17:42:53,068 - INFO - Opened browser at http://127.0.0.1:8000
|
598 |
+
2025-07-09 17:48:55,282 - INFO - Received interrupt signal
|
599 |
+
2025-07-09 17:48:55,282 - INFO - Stopping server...
|
600 |
+
2025-07-09 17:48:55,290 - INFO - Development server stopped
|
601 |
+
2025-07-09 17:48:55,290 - INFO - Development server stopped
|
602 |
+
2025-07-09 17:49:29,910 - INFO - Starting ResearchMate development server
|
603 |
+
2025-07-09 17:49:29,910 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
604 |
+
2025-07-09 17:49:29,910 - INFO - Starting server on 127.0.0.1:8000
|
605 |
+
2025-07-09 17:49:29,915 - INFO - File watcher started
|
606 |
+
2025-07-09 17:49:29,920 - INFO - Development server started successfully!
|
607 |
+
2025-07-09 17:49:29,920 - INFO - Web Interface: http://127.0.0.1:8000
|
608 |
+
2025-07-09 17:49:29,920 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
609 |
+
2025-07-09 17:49:29,922 - INFO - Auto-reload enabled
|
610 |
+
2025-07-09 17:49:29,922 - INFO - Use Ctrl+C to stop
|
611 |
+
2025-07-09 17:49:33,109 - INFO - Opened browser at http://127.0.0.1:8000
|
612 |
+
2025-07-09 18:01:55,767 - INFO - Received interrupt signal
|
613 |
+
2025-07-09 18:01:55,772 - INFO - Stopping server...
|
614 |
+
2025-07-09 18:01:55,777 - INFO - Development server stopped
|
615 |
+
2025-07-09 18:01:55,777 - INFO - Development server stopped
|
616 |
+
2025-07-09 18:03:44,913 - INFO - Starting ResearchMate development server
|
617 |
+
2025-07-09 18:03:44,913 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
618 |
+
2025-07-09 18:03:44,913 - INFO - Starting server on 127.0.0.1:8000
|
619 |
+
2025-07-09 18:03:44,921 - INFO - File watcher started
|
620 |
+
2025-07-09 18:03:44,926 - INFO - Development server started successfully!
|
621 |
+
2025-07-09 18:03:44,926 - INFO - Web Interface: http://127.0.0.1:8000
|
622 |
+
2025-07-09 18:03:44,926 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
623 |
+
2025-07-09 18:03:44,927 - INFO - Auto-reload enabled
|
624 |
+
2025-07-09 18:03:44,927 - INFO - Use Ctrl+C to stop
|
625 |
+
2025-07-09 18:03:48,164 - INFO - Opened browser at http://127.0.0.1:8000
|
626 |
+
2025-07-09 18:04:42,230 - INFO - File changed: D:\ResearchMate\src\components\research_assistant.py
|
627 |
+
2025-07-09 18:04:42,232 - INFO - Restarting server...
|
628 |
+
2025-07-09 18:04:42,232 - INFO - Stopping server...
|
629 |
+
2025-07-09 18:04:43,239 - INFO - Starting server on 127.0.0.1:8000
|
630 |
+
2025-07-09 18:04:43,255 - INFO - File changed: D:\ResearchMate\src\components\research_assistant.py
|
631 |
+
2025-07-09 18:04:43,267 - INFO - Restarting server...
|
632 |
+
2025-07-09 18:04:43,267 - INFO - Stopping server...
|
633 |
+
2025-07-09 18:04:44,766 - INFO - Starting server on 127.0.0.1:8000
|
634 |
+
2025-07-09 18:04:59,785 - INFO - Received interrupt signal
|
635 |
+
2025-07-09 18:04:59,785 - INFO - Stopping server...
|
636 |
+
2025-07-09 18:04:59,790 - INFO - Development server stopped
|
637 |
+
2025-07-09 18:04:59,790 - INFO - Development server stopped
|
638 |
+
2025-07-09 18:33:20,103 - INFO - Starting ResearchMate development server
|
639 |
+
2025-07-09 18:33:20,122 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
640 |
+
2025-07-09 18:33:20,122 - INFO - Starting server on 127.0.0.1:8000
|
641 |
+
2025-07-09 18:33:20,133 - INFO - File watcher started
|
642 |
+
2025-07-09 18:33:20,134 - INFO - Development server started successfully!
|
643 |
+
2025-07-09 18:33:20,134 - INFO - Web Interface: http://127.0.0.1:8000
|
644 |
+
2025-07-09 18:33:20,134 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
645 |
+
2025-07-09 18:33:20,135 - INFO - Auto-reload enabled
|
646 |
+
2025-07-09 18:33:20,135 - INFO - Use Ctrl+C to stop
|
647 |
+
2025-07-09 18:33:23,348 - INFO - Opened browser at http://127.0.0.1:8000
|
648 |
+
2025-07-09 18:40:55,495 - INFO - File changed: D:\ResearchMate\src\components\citation_network.py
|
649 |
+
2025-07-09 18:40:55,500 - INFO - Restarting server...
|
650 |
+
2025-07-09 18:40:55,501 - INFO - Stopping server...
|
651 |
+
2025-07-09 18:40:56,514 - INFO - Starting server on 127.0.0.1:8000
|
652 |
+
2025-07-09 18:40:56,529 - INFO - File changed: D:\ResearchMate\src\components\citation_network.py
|
653 |
+
2025-07-09 18:40:56,530 - INFO - Restarting server...
|
654 |
+
2025-07-09 18:40:56,531 - INFO - Stopping server...
|
655 |
+
2025-07-09 18:40:57,609 - INFO - Starting server on 127.0.0.1:8000
|
656 |
+
2025-07-09 18:41:30,376 - INFO - File changed: D:\ResearchMate\main.py
|
657 |
+
2025-07-09 18:41:30,376 - INFO - Restarting server...
|
658 |
+
2025-07-09 18:41:30,377 - INFO - Stopping server...
|
659 |
+
2025-07-09 18:41:31,389 - INFO - Starting server on 127.0.0.1:8000
|
660 |
+
2025-07-09 18:41:31,400 - INFO - File changed: D:\ResearchMate\main.py
|
661 |
+
2025-07-09 18:41:31,401 - INFO - Restarting server...
|
662 |
+
2025-07-09 18:41:31,401 - INFO - Stopping server...
|
663 |
+
2025-07-09 18:41:32,934 - INFO - Starting server on 127.0.0.1:8000
|
664 |
+
2025-07-09 18:41:32,943 - INFO - File changed: D:\ResearchMate\main.py
|
665 |
+
2025-07-09 18:41:32,943 - INFO - Restarting server...
|
666 |
+
2025-07-09 18:41:32,944 - INFO - Stopping server...
|
667 |
+
2025-07-09 18:41:33,949 - INFO - Starting server on 127.0.0.1:8000
|
668 |
+
2025-07-09 18:43:04,033 - INFO - File changed: D:\ResearchMate\main.py
|
669 |
+
2025-07-09 18:43:04,035 - INFO - Restarting server...
|
670 |
+
2025-07-09 18:43:04,035 - INFO - Stopping server...
|
671 |
+
2025-07-09 18:43:05,048 - INFO - Starting server on 127.0.0.1:8000
|
672 |
+
2025-07-09 18:43:05,075 - INFO - File changed: D:\ResearchMate\main.py
|
673 |
+
2025-07-09 18:43:05,076 - INFO - Restarting server...
|
674 |
+
2025-07-09 18:43:05,077 - INFO - Stopping server...
|
675 |
+
2025-07-09 18:43:06,379 - INFO - Starting server on 127.0.0.1:8000
|
676 |
+
2025-07-09 18:56:43,705 - INFO - File changed: D:\ResearchMate\main.py
|
677 |
+
2025-07-09 18:56:43,713 - INFO - Restarting server...
|
678 |
+
2025-07-09 18:56:43,714 - INFO - Stopping server...
|
679 |
+
2025-07-09 18:56:44,730 - INFO - Starting server on 127.0.0.1:8000
|
680 |
+
2025-07-09 18:56:44,760 - INFO - File changed: D:\ResearchMate\main.py
|
681 |
+
2025-07-09 18:56:44,762 - INFO - Restarting server...
|
682 |
+
2025-07-09 18:56:44,763 - INFO - Stopping server...
|
683 |
+
2025-07-09 18:56:46,262 - INFO - Starting server on 127.0.0.1:8000
|
684 |
+
2025-07-09 18:56:46,274 - INFO - File changed: D:\ResearchMate\main.py
|
685 |
+
2025-07-09 18:56:46,276 - INFO - Restarting server...
|
686 |
+
2025-07-09 18:56:46,277 - INFO - Stopping server...
|
687 |
+
2025-07-09 18:56:47,281 - INFO - Starting server on 127.0.0.1:8000
|
688 |
+
2025-07-09 18:56:51,788 - INFO - File changed: D:\ResearchMate\main.py
|
689 |
+
2025-07-09 18:56:51,789 - INFO - Restarting server...
|
690 |
+
2025-07-09 18:56:51,789 - INFO - Stopping server...
|
691 |
+
2025-07-09 18:56:52,800 - INFO - Starting server on 127.0.0.1:8000
|
692 |
+
2025-07-09 18:56:52,808 - INFO - File changed: D:\ResearchMate\main.py
|
693 |
+
2025-07-09 18:56:52,809 - INFO - Restarting server...
|
694 |
+
2025-07-09 18:56:52,809 - INFO - Stopping server...
|
695 |
+
2025-07-09 18:56:53,813 - INFO - Starting server on 127.0.0.1:8000
|
696 |
+
2025-07-09 18:57:05,816 - INFO - File changed: D:\ResearchMate\main.py
|
697 |
+
2025-07-09 18:57:05,817 - INFO - Restarting server...
|
698 |
+
2025-07-09 18:57:05,817 - INFO - Stopping server...
|
699 |
+
2025-07-09 18:57:06,832 - INFO - Starting server on 127.0.0.1:8000
|
700 |
+
2025-07-09 18:57:06,841 - INFO - File changed: D:\ResearchMate\main.py
|
701 |
+
2025-07-09 18:57:06,842 - INFO - Restarting server...
|
702 |
+
2025-07-09 18:57:06,842 - INFO - Stopping server...
|
703 |
+
2025-07-09 18:57:08,163 - INFO - Starting server on 127.0.0.1:8000
|
704 |
+
2025-07-09 18:57:10,333 - INFO - File changed: D:\ResearchMate\main.py
|
705 |
+
2025-07-09 18:57:10,335 - INFO - Restarting server...
|
706 |
+
2025-07-09 18:57:10,336 - INFO - Stopping server...
|
707 |
+
2025-07-09 18:57:11,351 - INFO - Starting server on 127.0.0.1:8000
|
708 |
+
2025-07-09 18:57:11,371 - INFO - File changed: D:\ResearchMate\main.py
|
709 |
+
2025-07-09 18:57:11,372 - INFO - Restarting server...
|
710 |
+
2025-07-09 18:57:11,373 - INFO - Stopping server...
|
711 |
+
2025-07-09 18:57:12,429 - INFO - Starting server on 127.0.0.1:8000
|
712 |
+
2025-07-09 18:57:37,991 - INFO - Received interrupt signal
|
713 |
+
2025-07-09 18:57:38,008 - INFO - Stopping server...
|
714 |
+
2025-07-09 18:57:38,023 - INFO - Development server stopped
|
715 |
+
2025-07-09 18:57:38,024 - INFO - Development server stopped
|
716 |
+
2025-07-09 19:05:11,983 - INFO - Starting ResearchMate development server
|
717 |
+
2025-07-09 19:05:11,992 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
718 |
+
2025-07-09 19:05:11,993 - INFO - Starting server on 127.0.0.1:8000
|
719 |
+
2025-07-09 19:05:12,022 - INFO - File watcher started
|
720 |
+
2025-07-09 19:05:12,025 - INFO - Development server started successfully!
|
721 |
+
2025-07-09 19:05:12,027 - INFO - Web Interface: http://127.0.0.1:8000
|
722 |
+
2025-07-09 19:05:12,031 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
723 |
+
2025-07-09 19:05:12,033 - INFO - Auto-reload enabled
|
724 |
+
2025-07-09 19:05:12,036 - INFO - Use Ctrl+C to stop
|
725 |
+
2025-07-09 19:05:15,763 - INFO - Opened browser at http://127.0.0.1:8000
|
726 |
+
2025-07-09 19:16:14,314 - INFO - File changed: D:\ResearchMate\src\scripts\__init__.py
|
727 |
+
2025-07-09 19:16:14,336 - INFO - Restarting server...
|
728 |
+
2025-07-09 19:16:14,337 - INFO - Stopping server...
|
729 |
+
2025-07-09 19:16:15,408 - INFO - Starting server on 127.0.0.1:8000
|
730 |
+
2025-07-09 19:18:11,305 - INFO - Received interrupt signal
|
731 |
+
2025-07-09 19:18:11,320 - INFO - Stopping server...
|
732 |
+
2025-07-09 19:18:11,338 - INFO - Development server stopped
|
733 |
+
2025-07-09 19:18:11,339 - INFO - Development server stopped
|
734 |
+
2025-07-09 19:45:00,224 - INFO - Starting ResearchMate development server
|
735 |
+
2025-07-09 19:45:00,239 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
736 |
+
2025-07-09 19:45:00,239 - INFO - Starting server on 127.0.0.1:8000
|
737 |
+
2025-07-09 19:45:00,264 - INFO - File watcher started
|
738 |
+
2025-07-09 19:45:00,267 - INFO - Development server started successfully!
|
739 |
+
2025-07-09 19:45:00,267 - INFO - Web Interface: http://127.0.0.1:8000
|
740 |
+
2025-07-09 19:45:00,269 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
741 |
+
2025-07-09 19:45:00,270 - INFO - Auto-reload enabled
|
742 |
+
2025-07-09 19:45:00,274 - INFO - Use Ctrl+C to stop
|
743 |
+
2025-07-09 19:45:03,947 - INFO - Opened browser at http://127.0.0.1:8000
|
744 |
+
2025-07-09 19:47:22,921 - INFO - Received interrupt signal
|
745 |
+
2025-07-09 19:47:22,924 - INFO - Stopping server...
|
746 |
+
2025-07-09 19:47:23,290 - INFO - Development server stopped
|
747 |
+
2025-07-09 19:47:23,291 - INFO - Development server stopped
|
748 |
+
2025-07-09 21:52:47,483 - INFO - Starting ResearchMate development server
|
749 |
+
2025-07-09 21:52:47,493 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
750 |
+
2025-07-09 21:52:47,493 - INFO - Starting server on 127.0.0.1:8000
|
751 |
+
2025-07-09 21:52:47,508 - INFO - File watcher started
|
752 |
+
2025-07-09 21:52:47,509 - INFO - Development server started successfully!
|
753 |
+
2025-07-09 21:52:47,509 - INFO - Web Interface: http://127.0.0.1:8000
|
754 |
+
2025-07-09 21:52:47,509 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
755 |
+
2025-07-09 21:52:47,509 - INFO - Auto-reload enabled
|
756 |
+
2025-07-09 21:52:47,510 - INFO - Use Ctrl+C to stop
|
757 |
+
2025-07-09 21:52:50,729 - INFO - Opened browser at http://127.0.0.1:8000
|
758 |
+
2025-07-09 21:52:56,423 - INFO - File changed: D:\ResearchMate\main.py
|
759 |
+
2025-07-09 21:52:56,423 - INFO - Restarting server...
|
760 |
+
2025-07-09 21:52:56,423 - INFO - Stopping server...
|
761 |
+
2025-07-09 21:52:57,432 - INFO - Starting server on 127.0.0.1:8000
|
762 |
+
2025-07-09 21:55:26,611 - INFO - Received interrupt signal
|
763 |
+
2025-07-09 21:55:26,611 - INFO - Stopping server...
|
764 |
+
2025-07-09 21:55:26,617 - INFO - Development server stopped
|
765 |
+
2025-07-09 21:55:26,617 - INFO - Development server stopped
|
766 |
+
2025-07-09 21:55:54,787 - INFO - Starting ResearchMate development server
|
767 |
+
2025-07-09 21:55:54,787 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
768 |
+
2025-07-09 21:55:54,787 - INFO - Starting server on 127.0.0.1:8000
|
769 |
+
2025-07-09 21:55:54,796 - INFO - File watcher started
|
770 |
+
2025-07-09 21:55:54,796 - INFO - Development server started successfully!
|
771 |
+
2025-07-09 21:55:54,798 - INFO - Web Interface: http://127.0.0.1:8000
|
772 |
+
2025-07-09 21:55:54,798 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
773 |
+
2025-07-09 21:55:54,798 - INFO - Auto-reload enabled
|
774 |
+
2025-07-09 21:55:54,798 - INFO - Use Ctrl+C to stop
|
775 |
+
2025-07-09 21:55:57,994 - INFO - Opened browser at http://127.0.0.1:8000
|
776 |
+
2025-07-09 21:56:03,613 - INFO - Received interrupt signal
|
777 |
+
2025-07-09 21:56:03,613 - INFO - Stopping server...
|
778 |
+
2025-07-09 21:56:03,622 - INFO - Development server stopped
|
779 |
+
2025-07-09 21:56:03,624 - INFO - Development server stopped
|
780 |
+
2025-07-09 21:56:07,902 - INFO - Starting ResearchMate development server
|
781 |
+
2025-07-09 21:56:07,902 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
782 |
+
2025-07-09 21:56:07,902 - INFO - Starting server on 127.0.0.1:8010
|
783 |
+
2025-07-09 21:56:07,913 - INFO - File watcher started
|
784 |
+
2025-07-09 21:56:07,913 - INFO - Development server started successfully!
|
785 |
+
2025-07-09 21:56:07,913 - INFO - Web Interface: http://127.0.0.1:8010
|
786 |
+
2025-07-09 21:56:07,913 - INFO - API Documentation: http://127.0.0.1:8010/docs
|
787 |
+
2025-07-09 21:56:07,913 - INFO - Auto-reload enabled
|
788 |
+
2025-07-09 21:56:07,913 - INFO - Use Ctrl+C to stop
|
789 |
+
2025-07-09 21:56:11,148 - INFO - Opened browser at http://127.0.0.1:8010
|
790 |
+
2025-07-09 21:56:25,967 - INFO - Received interrupt signal
|
791 |
+
2025-07-09 21:56:25,967 - INFO - Stopping server...
|
792 |
+
2025-07-09 21:56:25,978 - INFO - Development server stopped
|
793 |
+
2025-07-09 21:56:25,978 - INFO - Development server stopped
|
794 |
+
2025-07-09 21:59:56,405 - INFO - Starting ResearchMate development server
|
795 |
+
2025-07-09 21:59:56,429 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
796 |
+
2025-07-09 21:59:56,429 - INFO - Starting server on 127.0.0.1:8000
|
797 |
+
2025-07-09 21:59:56,436 - INFO - File watcher started
|
798 |
+
2025-07-09 21:59:56,436 - INFO - Development server started successfully!
|
799 |
+
2025-07-09 21:59:56,440 - INFO - Web Interface: http://127.0.0.1:8000
|
800 |
+
2025-07-09 21:59:56,440 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
801 |
+
2025-07-09 21:59:56,440 - INFO - Auto-reload enabled
|
802 |
+
2025-07-09 21:59:56,440 - INFO - Use Ctrl+C to stop
|
803 |
+
2025-07-09 21:59:59,651 - INFO - Opened browser at http://127.0.0.1:8000
|
804 |
+
2025-07-09 22:08:09,270 - INFO - File changed: D:\ResearchMate\test_timing.py
|
805 |
+
2025-07-09 22:08:09,274 - INFO - Restarting server...
|
806 |
+
2025-07-09 22:08:09,275 - INFO - Received interrupt signal
|
807 |
+
2025-07-09 22:08:09,275 - INFO - Stopping server...
|
808 |
+
2025-07-09 22:08:10,282 - INFO - Starting server on 127.0.0.1:8000
|
809 |
+
2025-07-09 22:08:10,297 - INFO - Stopping server...
|
810 |
+
2025-07-09 22:08:10,300 - INFO - Development server stopped
|
811 |
+
2025-07-09 22:08:10,300 - INFO - Development server stopped
|
812 |
+
2025-07-09 22:15:37,874 - INFO - Starting ResearchMate development server
|
813 |
+
2025-07-09 22:15:37,894 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
814 |
+
2025-07-09 22:15:37,894 - INFO - Starting server on 127.0.0.1:8000
|
815 |
+
2025-07-09 22:15:37,907 - INFO - File watcher started
|
816 |
+
2025-07-09 22:15:37,907 - INFO - Development server started successfully!
|
817 |
+
2025-07-09 22:15:37,907 - INFO - Web Interface: http://127.0.0.1:8000
|
818 |
+
2025-07-09 22:15:37,908 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
819 |
+
2025-07-09 22:15:37,908 - INFO - Auto-reload enabled
|
820 |
+
2025-07-09 22:15:37,908 - INFO - Use Ctrl+C to stop
|
821 |
+
2025-07-09 22:15:41,187 - INFO - Opened browser at http://127.0.0.1:8000
|
822 |
+
2025-07-09 22:19:27,211 - INFO - Received interrupt signal
|
823 |
+
2025-07-09 22:19:27,211 - INFO - Stopping server...
|
824 |
+
2025-07-09 22:19:27,224 - INFO - Development server stopped
|
825 |
+
2025-07-09 22:19:27,224 - INFO - Development server stopped
|
826 |
+
2025-07-10 19:09:22,329 - INFO - Starting ResearchMate development server
|
827 |
+
2025-07-10 19:09:22,331 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
828 |
+
2025-07-10 19:09:22,332 - INFO - Starting server on 127.0.0.1:8000
|
829 |
+
2025-07-10 19:09:22,352 - INFO - File watcher started
|
830 |
+
2025-07-10 19:09:22,354 - INFO - Development server started successfully!
|
831 |
+
2025-07-10 19:09:22,358 - INFO - Web Interface: http://127.0.0.1:8000
|
832 |
+
2025-07-10 19:09:22,360 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
833 |
+
2025-07-10 19:09:22,363 - INFO - Auto-reload enabled
|
834 |
+
2025-07-10 19:09:22,365 - INFO - Use Ctrl+C to stop
|
835 |
+
2025-07-10 19:09:25,722 - INFO - Opened browser at http://127.0.0.1:8000
|
836 |
+
2025-07-10 19:10:03,314 - INFO - File changed: D:\ResearchMate\src\components\research_assistant.py
|
837 |
+
2025-07-10 19:10:03,314 - INFO - Restarting server...
|
838 |
+
2025-07-10 19:10:03,314 - INFO - Stopping server...
|
839 |
+
2025-07-10 19:10:04,329 - INFO - Starting server on 127.0.0.1:8000
|
840 |
+
2025-07-10 19:10:04,339 - INFO - File changed: D:\ResearchMate\src\components\research_assistant.py
|
841 |
+
2025-07-10 19:10:04,342 - INFO - Restarting server...
|
842 |
+
2025-07-10 19:10:04,344 - INFO - Stopping server...
|
843 |
+
2025-07-10 19:10:05,354 - INFO - Starting server on 127.0.0.1:8000
|
844 |
+
2025-07-10 19:11:59,603 - INFO - Received interrupt signal
|
845 |
+
2025-07-10 19:11:59,603 - INFO - Stopping server...
|
846 |
+
2025-07-10 19:11:59,618 - INFO - Development server stopped
|
847 |
+
2025-07-10 19:11:59,618 - INFO - Development server stopped
|
848 |
+
2025-07-13 15:39:30,252 - INFO - Loaded environment variables from D:\ResearchMate\.env
|
849 |
+
2025-07-13 15:39:30,268 - INFO - Starting ResearchMate deployment
|
850 |
+
2025-07-13 15:39:30,268 - INFO - Running: Checking Python version
|
851 |
+
2025-07-13 15:39:30,268 - INFO - Python version 3.11 is compatible
|
852 |
+
2025-07-13 15:39:30,268 - INFO - Running: Creating virtual environment
|
853 |
+
2025-07-13 15:39:30,268 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
854 |
+
2025-07-13 15:39:30,268 - INFO - Running: Installing dependencies
|
855 |
+
2025-07-13 15:39:30,268 - INFO - Installing dependencies...
|
856 |
+
2025-07-13 15:39:30,268 - INFO - Running from within virtual environment, using current Python executable
|
857 |
+
2025-07-13 15:39:30,268 - INFO - Conda environment detected: D:\ResearchMate\venv
|
858 |
+
2025-07-13 15:39:30,268 - INFO - Skipping pip upgrade in Conda environment
|
859 |
+
2025-07-13 15:39:30,268 - INFO - Installing requirements from requirements.txt...
|
860 |
+
2025-07-13 15:39:30,268 - INFO - Using --no-deps flag for Conda environment
|
861 |
+
2025-07-13 15:39:35,338 - INFO - Requirements installed successfully
|
862 |
+
2025-07-13 15:39:35,338 - INFO - Dependencies installed successfully
|
863 |
+
2025-07-13 15:39:35,338 - INFO - Running: Creating directories
|
864 |
+
2025-07-13 15:39:35,338 - INFO - Creating directories...
|
865 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: uploads
|
866 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: chroma_db
|
867 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: chroma_persist
|
868 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: logs
|
869 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: backups
|
870 |
+
2025-07-13 15:39:35,338 - INFO - Created directory: config
|
871 |
+
2025-07-13 15:39:35,338 - INFO - Verified src/static directory exists
|
872 |
+
2025-07-13 15:39:35,338 - INFO - Running: Checking environment variables
|
873 |
+
2025-07-13 15:39:35,338 - INFO - Checking environment variables...
|
874 |
+
2025-07-13 15:39:35,338 - INFO - All required environment variables are set
|
875 |
+
2025-07-13 15:39:35,338 - INFO - Running: Testing imports
|
876 |
+
2025-07-13 15:39:35,338 - INFO - Testing imports...
|
877 |
+
2025-07-13 15:39:41,262 - INFO - All imports successful
|
878 |
+
2025-07-13 15:39:41,263 - INFO - Deployment completed successfully!
|
879 |
+
2025-07-13 15:39:41,263 - INFO - Web Interface: http://localhost:8000
|
880 |
+
2025-07-13 15:39:41,264 - INFO - API Documentation: http://localhost:8000/docs
|
881 |
+
2025-07-13 15:39:41,371 - INFO - Use Ctrl+C to stop the server
|
882 |
+
2025-07-13 15:39:41,414 - INFO - Starting server on 0.0.0.0:8000
|
883 |
+
2025-07-13 15:40:17,023 - INFO - Server stopped by user
|
logs/development.log
ADDED
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
2025-07-09 12:10:44,284 - INFO - Starting ResearchMate development server
|
2 |
+
2025-07-09 12:10:44,284 - ERROR - Virtual environment not found. Please run deployment first.
|
3 |
+
2025-07-09 12:10:44,284 - INFO - Run: python scripts/deploy.py
|
4 |
+
2025-07-09 12:15:38,786 - INFO - Starting ResearchMate development server
|
5 |
+
2025-07-09 12:15:38,786 - ERROR - Virtual environment not found. Please run deployment first.
|
6 |
+
2025-07-09 12:15:38,787 - INFO - Run: python scripts/deploy.py
|
7 |
+
2025-07-13 15:13:09,749 - INFO - Starting ResearchMate development server
|
8 |
+
2025-07-13 15:13:09,749 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
9 |
+
2025-07-13 15:13:09,751 - INFO - Starting server on 127.0.0.1:8000
|
10 |
+
2025-07-13 15:13:09,758 - INFO - File watcher started
|
11 |
+
2025-07-13 15:13:09,759 - INFO - Development server started successfully!
|
12 |
+
2025-07-13 15:13:09,759 - INFO - Web Interface: http://127.0.0.1:8000
|
13 |
+
2025-07-13 15:13:09,760 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
14 |
+
2025-07-13 15:13:09,760 - INFO - Auto-reload enabled
|
15 |
+
2025-07-13 15:13:09,760 - INFO - Use Ctrl+C to stop
|
16 |
+
2025-07-13 15:13:12,966 - INFO - Opened browser at http://127.0.0.1:8000
|
17 |
+
2025-07-13 15:18:08,075 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
18 |
+
2025-07-13 15:18:08,075 - INFO - Restarting server...
|
19 |
+
2025-07-13 15:18:08,076 - INFO - Stopping server...
|
20 |
+
2025-07-13 15:18:09,084 - INFO - Starting server on 127.0.0.1:8000
|
21 |
+
2025-07-13 15:18:09,087 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
22 |
+
2025-07-13 15:18:09,087 - INFO - Restarting server...
|
23 |
+
2025-07-13 15:18:09,087 - INFO - Stopping server...
|
24 |
+
2025-07-13 15:18:10,142 - INFO - Starting server on 127.0.0.1:8000
|
25 |
+
2025-07-13 15:18:17,666 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
26 |
+
2025-07-13 15:18:17,666 - INFO - Restarting server...
|
27 |
+
2025-07-13 15:18:17,666 - INFO - Stopping server...
|
28 |
+
2025-07-13 15:18:18,674 - INFO - Starting server on 127.0.0.1:8000
|
29 |
+
2025-07-13 15:18:18,678 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
30 |
+
2025-07-13 15:18:18,679 - INFO - Restarting server...
|
31 |
+
2025-07-13 15:18:18,679 - INFO - Stopping server...
|
32 |
+
2025-07-13 15:18:19,695 - INFO - Starting server on 127.0.0.1:8000
|
33 |
+
2025-07-13 15:18:26,896 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
34 |
+
2025-07-13 15:18:26,896 - INFO - Restarting server...
|
35 |
+
2025-07-13 15:18:26,896 - INFO - Stopping server...
|
36 |
+
2025-07-13 15:18:27,908 - INFO - Starting server on 127.0.0.1:8000
|
37 |
+
2025-07-13 15:18:27,912 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
38 |
+
2025-07-13 15:18:27,912 - INFO - Restarting server...
|
39 |
+
2025-07-13 15:18:27,912 - INFO - Stopping server...
|
40 |
+
2025-07-13 15:18:28,925 - INFO - Starting server on 127.0.0.1:8000
|
41 |
+
2025-07-13 15:18:36,233 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
42 |
+
2025-07-13 15:18:36,233 - INFO - Restarting server...
|
43 |
+
2025-07-13 15:18:36,234 - INFO - Stopping server...
|
44 |
+
2025-07-13 15:18:37,242 - INFO - Starting server on 127.0.0.1:8000
|
45 |
+
2025-07-13 15:18:37,245 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
46 |
+
2025-07-13 15:18:37,245 - INFO - Restarting server...
|
47 |
+
2025-07-13 15:18:37,245 - INFO - Stopping server...
|
48 |
+
2025-07-13 15:18:38,258 - INFO - Starting server on 127.0.0.1:8000
|
49 |
+
2025-07-13 15:18:59,346 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
50 |
+
2025-07-13 15:18:59,346 - INFO - Restarting server...
|
51 |
+
2025-07-13 15:18:59,346 - INFO - Stopping server...
|
52 |
+
2025-07-13 15:19:00,357 - INFO - Starting server on 127.0.0.1:8000
|
53 |
+
2025-07-13 15:19:00,388 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
54 |
+
2025-07-13 15:19:00,388 - INFO - Restarting server...
|
55 |
+
2025-07-13 15:19:00,388 - INFO - Stopping server...
|
56 |
+
2025-07-13 15:19:01,747 - INFO - Starting server on 127.0.0.1:8000
|
57 |
+
2025-07-13 15:20:05,589 - INFO - Received interrupt signal
|
58 |
+
2025-07-13 15:20:05,900 - INFO - Stopping server...
|
59 |
+
2025-07-13 15:20:05,900 - INFO - Development server stopped
|
60 |
+
2025-07-13 15:20:05,900 - INFO - Development server stopped
|
61 |
+
2025-07-13 15:20:30,529 - INFO - Starting ResearchMate development server
|
62 |
+
2025-07-13 15:20:30,529 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
63 |
+
2025-07-13 15:20:30,529 - INFO - Starting server via main.py
|
64 |
+
2025-07-13 15:20:30,577 - INFO - File watcher started
|
65 |
+
2025-07-13 15:20:30,578 - INFO - Development server started successfully!
|
66 |
+
2025-07-13 15:20:30,578 - INFO - Web Interface: http://127.0.0.1:8000
|
67 |
+
2025-07-13 15:20:30,578 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
68 |
+
2025-07-13 15:20:30,579 - INFO - Auto-reload enabled
|
69 |
+
2025-07-13 15:20:30,579 - INFO - Use Ctrl+C to stop
|
70 |
+
2025-07-13 15:20:34,082 - INFO - Opened browser at http://127.0.0.1:8000
|
71 |
+
2025-07-13 15:21:31,321 - INFO - File changed: D:\ResearchMate\src\scripts\__init__.py
|
72 |
+
2025-07-13 15:21:31,321 - INFO - Restarting server...
|
73 |
+
2025-07-13 15:21:31,336 - INFO - Stopping server...
|
74 |
+
2025-07-13 15:21:32,414 - INFO - Starting server via main.py
|
75 |
+
2025-07-13 15:22:38,268 - INFO - File changed: D:\ResearchMate\src\scripts\setup.py
|
76 |
+
2025-07-13 15:22:38,268 - INFO - Restarting server...
|
77 |
+
2025-07-13 15:22:38,268 - INFO - Stopping server...
|
78 |
+
2025-07-13 15:22:39,363 - INFO - Starting server via main.py
|
79 |
+
2025-07-13 15:23:29,470 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
80 |
+
2025-07-13 15:23:29,470 - INFO - Restarting server...
|
81 |
+
2025-07-13 15:23:29,470 - INFO - Stopping server...
|
82 |
+
2025-07-13 15:23:30,553 - INFO - Starting server via main.py
|
83 |
+
2025-07-13 15:23:30,557 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
84 |
+
2025-07-13 15:23:30,557 - INFO - Restarting server...
|
85 |
+
2025-07-13 15:23:30,557 - INFO - Stopping server...
|
86 |
+
2025-07-13 15:23:31,559 - INFO - Starting server via main.py
|
87 |
+
2025-07-13 15:25:08,387 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
88 |
+
2025-07-13 15:25:08,388 - INFO - Restarting server...
|
89 |
+
2025-07-13 15:25:08,388 - INFO - Stopping server...
|
90 |
+
2025-07-13 15:25:09,479 - INFO - Starting server via main.py
|
91 |
+
2025-07-13 15:25:09,479 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
92 |
+
2025-07-13 15:25:09,484 - INFO - Restarting server...
|
93 |
+
2025-07-13 15:25:09,484 - INFO - Stopping server...
|
94 |
+
2025-07-13 15:25:10,487 - INFO - Starting server via main.py
|
95 |
+
2025-07-13 15:25:25,968 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
96 |
+
2025-07-13 15:25:25,968 - INFO - Restarting server...
|
97 |
+
2025-07-13 15:25:25,968 - INFO - Stopping server...
|
98 |
+
2025-07-13 15:25:27,054 - INFO - Starting server via main.py
|
99 |
+
2025-07-13 15:25:27,054 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
100 |
+
2025-07-13 15:25:27,054 - INFO - Restarting server...
|
101 |
+
2025-07-13 15:25:27,054 - INFO - Stopping server...
|
102 |
+
2025-07-13 15:25:28,059 - INFO - Starting server via main.py
|
103 |
+
2025-07-13 15:25:29,430 - INFO - Starting ResearchMate development server
|
104 |
+
2025-07-13 15:25:29,430 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
105 |
+
2025-07-13 15:25:29,431 - INFO - Starting server via main.py
|
106 |
+
2025-07-13 15:25:29,431 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
107 |
+
2025-07-13 15:25:29,431 - INFO - Working directory: D:\ResearchMate
|
108 |
+
2025-07-13 15:25:29,432 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
109 |
+
2025-07-13 15:25:29,432 - INFO - Python path exists: True
|
110 |
+
2025-07-13 15:25:29,448 - INFO - Python version test: Python 3.11.13
|
111 |
+
2025-07-13 15:25:32,455 - INFO - Server process started successfully
|
112 |
+
2025-07-13 15:25:32,455 - INFO - File watcher started
|
113 |
+
2025-07-13 15:25:32,455 - INFO - Development server started successfully!
|
114 |
+
2025-07-13 15:25:32,455 - INFO - Web Interface: http://127.0.0.1:8000
|
115 |
+
2025-07-13 15:25:32,459 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
116 |
+
2025-07-13 15:25:32,459 - INFO - Auto-reload enabled
|
117 |
+
2025-07-13 15:25:32,459 - INFO - Use Ctrl+C to stop
|
118 |
+
2025-07-13 15:25:34,052 - INFO - Received interrupt signal
|
119 |
+
2025-07-13 15:25:34,059 - INFO - Stopping server...
|
120 |
+
2025-07-13 15:25:34,088 - INFO - Development server stopped
|
121 |
+
2025-07-13 15:25:34,088 - INFO - Development server stopped
|
122 |
+
2025-07-13 15:25:39,940 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
123 |
+
2025-07-13 15:25:39,940 - INFO - Restarting server...
|
124 |
+
2025-07-13 15:25:39,940 - INFO - Stopping server...
|
125 |
+
2025-07-13 15:25:40,981 - INFO - Starting server via main.py
|
126 |
+
2025-07-13 15:25:40,981 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
127 |
+
2025-07-13 15:25:40,981 - INFO - Working directory: D:\ResearchMate
|
128 |
+
2025-07-13 15:25:40,981 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
129 |
+
2025-07-13 15:25:40,981 - INFO - Python path exists: True
|
130 |
+
2025-07-13 15:25:40,981 - INFO - Python version test: Python 3.11.13
|
131 |
+
2025-07-13 15:25:43,999 - INFO - Server process started successfully
|
132 |
+
2025-07-13 15:25:43,999 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
133 |
+
2025-07-13 15:25:43,999 - INFO - Restarting server...
|
134 |
+
2025-07-13 15:25:43,999 - INFO - Stopping server...
|
135 |
+
2025-07-13 15:25:45,012 - INFO - Starting server via main.py
|
136 |
+
2025-07-13 15:25:45,012 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
137 |
+
2025-07-13 15:25:45,012 - INFO - Working directory: D:\ResearchMate
|
138 |
+
2025-07-13 15:25:45,012 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
139 |
+
2025-07-13 15:25:45,012 - INFO - Python path exists: True
|
140 |
+
2025-07-13 15:25:45,014 - INFO - Python version test: Python 3.11.13
|
141 |
+
2025-07-13 15:25:48,030 - INFO - Server process started successfully
|
142 |
+
2025-07-13 15:26:03,475 - INFO - Received interrupt signal
|
143 |
+
2025-07-13 15:26:03,475 - INFO - Stopping server...
|
144 |
+
2025-07-13 15:26:03,475 - INFO - Development server stopped
|
145 |
+
2025-07-13 15:26:03,475 - INFO - Development server stopped
|
146 |
+
2025-07-13 15:26:23,147 - INFO - Starting ResearchMate development server
|
147 |
+
2025-07-13 15:26:23,147 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
148 |
+
2025-07-13 15:26:23,147 - INFO - Starting server via main.py
|
149 |
+
2025-07-13 15:26:23,147 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
150 |
+
2025-07-13 15:26:23,147 - INFO - Working directory: D:\ResearchMate
|
151 |
+
2025-07-13 15:26:23,147 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
152 |
+
2025-07-13 15:26:23,147 - INFO - Python path exists: True
|
153 |
+
2025-07-13 15:26:23,163 - INFO - Python version test: Python 3.11.13
|
154 |
+
2025-07-13 15:26:26,183 - INFO - Server process started successfully
|
155 |
+
2025-07-13 15:26:26,183 - INFO - File watcher started
|
156 |
+
2025-07-13 15:26:26,183 - INFO - Development server started successfully!
|
157 |
+
2025-07-13 15:26:26,183 - INFO - Web Interface: http://127.0.0.1:8000
|
158 |
+
2025-07-13 15:26:26,183 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
159 |
+
2025-07-13 15:26:26,188 - INFO - Auto-reload enabled
|
160 |
+
2025-07-13 15:26:26,188 - INFO - Use Ctrl+C to stop
|
161 |
+
2025-07-13 15:28:08,560 - INFO - Received interrupt signal
|
162 |
+
2025-07-13 15:28:08,560 - INFO - Stopping server...
|
163 |
+
2025-07-13 15:28:08,637 - INFO - Development server stopped
|
164 |
+
2025-07-13 15:28:08,637 - INFO - Development server stopped
|
165 |
+
2025-07-13 15:28:37,538 - INFO - Starting ResearchMate development server
|
166 |
+
2025-07-13 15:28:37,538 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
167 |
+
2025-07-13 15:28:37,538 - INFO - Starting server via main.py
|
168 |
+
2025-07-13 15:28:37,538 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
169 |
+
2025-07-13 15:28:37,538 - INFO - Working directory: D:\ResearchMate
|
170 |
+
2025-07-13 15:28:37,538 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
171 |
+
2025-07-13 15:28:37,538 - INFO - Python path exists: True
|
172 |
+
2025-07-13 15:28:37,547 - INFO - Python version test: Python 3.11.13
|
173 |
+
2025-07-13 15:28:40,560 - INFO - Server process started successfully
|
174 |
+
2025-07-13 15:28:40,560 - INFO - File watcher started
|
175 |
+
2025-07-13 15:28:40,560 - INFO - Development server started successfully!
|
176 |
+
2025-07-13 15:28:40,560 - INFO - Web Interface: http://127.0.0.1:8080
|
177 |
+
2025-07-13 15:28:40,560 - INFO - API Documentation: http://127.0.0.1:8080/docs
|
178 |
+
2025-07-13 15:28:40,560 - INFO - Auto-reload enabled
|
179 |
+
2025-07-13 15:28:40,560 - INFO - Use Ctrl+C to stop
|
180 |
+
2025-07-13 15:28:43,749 - INFO - Opened browser at http://127.0.0.1:8080
|
181 |
+
2025-07-13 15:30:38,593 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
182 |
+
2025-07-13 15:30:38,593 - INFO - Restarting server...
|
183 |
+
2025-07-13 15:30:38,593 - INFO - Stopping server...
|
184 |
+
2025-07-13 15:30:39,678 - INFO - Starting server via main.py
|
185 |
+
2025-07-13 15:30:39,678 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
186 |
+
2025-07-13 15:30:39,678 - INFO - Working directory: D:\ResearchMate
|
187 |
+
2025-07-13 15:30:39,678 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
188 |
+
2025-07-13 15:30:39,678 - INFO - Python path exists: True
|
189 |
+
2025-07-13 15:30:39,681 - INFO - Python version test: Python 3.11.13
|
190 |
+
2025-07-13 15:30:42,697 - INFO - Server process started successfully
|
191 |
+
2025-07-13 15:30:42,697 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
192 |
+
2025-07-13 15:30:42,697 - INFO - Restarting server...
|
193 |
+
2025-07-13 15:30:42,697 - INFO - Stopping server...
|
194 |
+
2025-07-13 15:30:43,715 - INFO - Starting server via main.py
|
195 |
+
2025-07-13 15:30:43,715 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
196 |
+
2025-07-13 15:30:43,715 - INFO - Working directory: D:\ResearchMate
|
197 |
+
2025-07-13 15:30:43,715 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
198 |
+
2025-07-13 15:30:43,715 - INFO - Python path exists: True
|
199 |
+
2025-07-13 15:30:43,729 - INFO - Python version test: Python 3.11.13
|
200 |
+
2025-07-13 15:30:46,734 - INFO - Server process started successfully
|
201 |
+
2025-07-13 15:30:52,676 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
202 |
+
2025-07-13 15:30:52,676 - INFO - Restarting server...
|
203 |
+
2025-07-13 15:30:52,676 - INFO - Stopping server...
|
204 |
+
2025-07-13 15:30:53,728 - INFO - Starting server via main.py
|
205 |
+
2025-07-13 15:30:53,728 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
206 |
+
2025-07-13 15:30:53,728 - INFO - Working directory: D:\ResearchMate
|
207 |
+
2025-07-13 15:30:53,728 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
208 |
+
2025-07-13 15:30:53,731 - INFO - Python path exists: True
|
209 |
+
2025-07-13 15:30:53,743 - INFO - Python version test: Python 3.11.13
|
210 |
+
2025-07-13 15:30:56,747 - INFO - Server process started successfully
|
211 |
+
2025-07-13 15:30:56,747 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
212 |
+
2025-07-13 15:30:56,747 - INFO - Restarting server...
|
213 |
+
2025-07-13 15:30:56,747 - INFO - Stopping server...
|
214 |
+
2025-07-13 15:30:57,764 - INFO - Starting server via main.py
|
215 |
+
2025-07-13 15:30:57,764 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
216 |
+
2025-07-13 15:30:57,764 - INFO - Working directory: D:\ResearchMate
|
217 |
+
2025-07-13 15:30:57,764 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
218 |
+
2025-07-13 15:30:57,764 - INFO - Python path exists: True
|
219 |
+
2025-07-13 15:30:57,778 - INFO - Python version test: Python 3.11.13
|
220 |
+
2025-07-13 15:31:00,782 - INFO - Server process started successfully
|
221 |
+
2025-07-13 15:31:34,519 - INFO - Received interrupt signal
|
222 |
+
2025-07-13 15:31:34,525 - INFO - Stopping server...
|
223 |
+
2025-07-13 15:31:34,590 - INFO - Development server stopped
|
224 |
+
2025-07-13 15:31:34,590 - INFO - Development server stopped
|
225 |
+
2025-07-13 15:31:45,872 - INFO - Starting ResearchMate development server
|
226 |
+
2025-07-13 15:31:45,872 - INFO - Using existing Conda environment: D:\ResearchMate\venv
|
227 |
+
2025-07-13 15:31:45,872 - INFO - Starting server via main.py
|
228 |
+
2025-07-13 15:31:45,872 - INFO - Command: D:\ResearchMate\venv\python.exe main.py
|
229 |
+
2025-07-13 15:31:45,872 - INFO - Working directory: D:\ResearchMate
|
230 |
+
2025-07-13 15:31:45,872 - INFO - Python path: D:\ResearchMate\venv\python.exe
|
231 |
+
2025-07-13 15:31:45,872 - INFO - Python path exists: True
|
232 |
+
2025-07-13 15:31:45,872 - INFO - Setting PORT environment variable to: 8000
|
233 |
+
2025-07-13 15:31:45,895 - INFO - Python version test: Python 3.11.13
|
234 |
+
2025-07-13 15:31:48,902 - INFO - Server process started successfully
|
235 |
+
2025-07-13 15:31:48,902 - INFO - File watcher started
|
236 |
+
2025-07-13 15:31:48,902 - INFO - Development server started successfully!
|
237 |
+
2025-07-13 15:31:48,902 - INFO - Web Interface: http://127.0.0.1:8000
|
238 |
+
2025-07-13 15:31:48,902 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
239 |
+
2025-07-13 15:31:48,902 - INFO - Server is binding to: 0.0.0.0:8000 (accessible via 127.0.0.1:8000)
|
240 |
+
2025-07-13 15:31:48,902 - INFO - Auto-reload enabled
|
241 |
+
2025-07-13 15:31:48,902 - INFO - Use Ctrl+C to stop
|
242 |
+
2025-07-13 15:31:52,083 - INFO - Opened browser at http://127.0.0.1:8000
|
243 |
+
2025-07-13 15:32:27,917 - INFO - Received interrupt signal
|
244 |
+
2025-07-13 15:32:27,921 - INFO - Stopping server...
|
245 |
+
2025-07-13 15:32:27,993 - INFO - Development server stopped
|
246 |
+
2025-07-13 15:32:27,993 - INFO - Development server stopped
|
247 |
+
2025-07-13 15:36:15,615 - INFO - Starting ResearchMate development server
|
248 |
+
2025-07-13 15:36:15,615 - INFO - Successfully imported main application
|
249 |
+
2025-07-13 15:36:15,615 - INFO - Starting server on 127.0.0.1:8000
|
250 |
+
2025-07-13 15:36:17,631 - INFO - Server process started successfully
|
251 |
+
2025-07-13 15:36:17,633 - INFO - File watcher started
|
252 |
+
2025-07-13 15:36:17,648 - INFO - Development server started successfully!
|
253 |
+
2025-07-13 15:36:17,649 - INFO - Web Interface: http://127.0.0.1:8000
|
254 |
+
2025-07-13 15:36:17,649 - INFO - API Documentation: http://127.0.0.1:8000/docs
|
255 |
+
2025-07-13 15:36:17,649 - INFO - File watcher enabled (manual restart required for changes)
|
256 |
+
2025-07-13 15:36:17,649 - INFO - Use Ctrl+C to stop
|
257 |
+
2025-07-13 15:36:20,928 - INFO - Opened browser at http://127.0.0.1:8000
|
258 |
+
2025-07-13 15:36:24,569 - INFO - Load pretrained SentenceTransformer: all-MiniLM-L6-v2
|
259 |
+
2025-07-13 15:36:37,342 - INFO - Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.
|
260 |
+
2025-07-13 15:37:26,506 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
261 |
+
2025-07-13 15:37:26,506 - INFO - File change detected - restarting server...
|
262 |
+
2025-07-13 15:37:26,507 - INFO - Note: For full restart, please stop and start the dev server manually
|
263 |
+
2025-07-13 15:37:42,090 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
264 |
+
2025-07-13 15:37:42,091 - INFO - File change detected - restarting server...
|
265 |
+
2025-07-13 15:37:42,091 - INFO - Note: For full restart, please stop and start the dev server manually
|
266 |
+
2025-07-13 15:37:59,815 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
267 |
+
2025-07-13 15:37:59,816 - INFO - File change detected - restarting server...
|
268 |
+
2025-07-13 15:37:59,816 - INFO - Note: For full restart, please stop and start the dev server manually
|
269 |
+
2025-07-13 15:38:12,203 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
270 |
+
2025-07-13 15:38:12,203 - INFO - File change detected - restarting server...
|
271 |
+
2025-07-13 15:38:12,203 - INFO - Note: For full restart, please stop and start the dev server manually
|
272 |
+
2025-07-13 15:38:49,290 - INFO - File changed: D:\ResearchMate\src\scripts\dev_server.py
|
273 |
+
2025-07-13 15:38:49,298 - INFO - File change detected - restarting server...
|
274 |
+
2025-07-13 15:38:49,298 - INFO - Note: For full restart, please stop and start the dev server manually
|
275 |
+
2025-07-13 15:38:52,994 - INFO - Received interrupt signal
|
276 |
+
2025-07-13 15:38:52,994 - INFO - Stopping server...
|
277 |
+
2025-07-13 15:38:52,994 - INFO - Development server stopped
|
278 |
+
2025-07-13 15:38:52,994 - INFO - Development server stopped
|
279 |
+
2025-07-13 15:40:34,275 - INFO - Starting ResearchMate development server
|
280 |
+
2025-07-13 15:40:34,275 - INFO - Successfully imported main application
|
281 |
+
2025-07-13 15:40:34,275 - WARNING - Port 8000 is already in use on 127.0.0.1
|
282 |
+
2025-07-13 15:40:34,275 - INFO - Using available port 8001 instead
|
283 |
+
2025-07-13 15:40:34,275 - INFO - Starting server on 127.0.0.1:8001
|
284 |
+
2025-07-13 15:40:36,280 - INFO - Server process started successfully
|
285 |
+
2025-07-13 15:40:36,292 - INFO - File watcher started
|
286 |
+
2025-07-13 15:40:36,294 - INFO - Development server started successfully!
|
287 |
+
2025-07-13 15:40:36,294 - INFO - Web Interface: http://127.0.0.1:8001
|
288 |
+
2025-07-13 15:40:36,294 - INFO - API Documentation: http://127.0.0.1:8001/docs
|
289 |
+
2025-07-13 15:40:36,295 - INFO - File watcher enabled (manual restart required for changes)
|
290 |
+
2025-07-13 15:40:36,295 - INFO - Use Ctrl+C to stop
|
291 |
+
2025-07-13 15:40:39,705 - INFO - Opened browser at http://127.0.0.1:8001
|
292 |
+
2025-07-13 15:40:43,673 - INFO - Load pretrained SentenceTransformer: all-MiniLM-L6-v2
|
293 |
+
2025-07-13 15:40:52,393 - INFO - Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.
|
294 |
+
2025-07-13 15:41:12,198 - INFO - Received interrupt signal
|
295 |
+
2025-07-13 15:41:12,198 - INFO - Stopping server...
|
296 |
+
2025-07-13 15:41:12,198 - INFO - Development server stopped
|
297 |
+
2025-07-13 15:41:12,198 - INFO - Development server stopped
|
298 |
+
2025-07-13 15:41:23,874 - INFO - Starting ResearchMate development server
|
299 |
+
2025-07-13 15:41:23,874 - INFO - Successfully imported main application
|
300 |
+
2025-07-13 15:41:23,874 - WARNING - Port 8000 is already in use on 127.0.0.1
|
301 |
+
2025-07-13 15:41:23,874 - INFO - Using available port 8001 instead
|
302 |
+
2025-07-13 15:41:23,874 - INFO - Starting server on 127.0.0.1:8001
|
303 |
+
2025-07-13 15:41:25,885 - INFO - Server process started successfully
|
304 |
+
2025-07-13 15:41:25,885 - INFO - File watcher started
|
305 |
+
2025-07-13 15:41:25,893 - INFO - Development server started successfully!
|
306 |
+
2025-07-13 15:41:25,893 - INFO - Web Interface: http://127.0.0.1:8001
|
307 |
+
2025-07-13 15:41:25,893 - INFO - API Documentation: http://127.0.0.1:8001/docs
|
308 |
+
2025-07-13 15:41:25,893 - INFO - File watcher enabled (manual restart required for changes)
|
309 |
+
2025-07-13 15:41:25,894 - INFO - Use Ctrl+C to stop
|
310 |
+
2025-07-13 15:41:29,203 - INFO - Opened browser at http://127.0.0.1:8001
|
311 |
+
2025-07-13 15:41:32,985 - INFO - Load pretrained SentenceTransformer: all-MiniLM-L6-v2
|
312 |
+
2025-07-13 15:41:37,038 - INFO - Received interrupt signal
|
313 |
+
2025-07-13 15:41:37,038 - INFO - Stopping server...
|
314 |
+
2025-07-13 15:41:37,038 - INFO - Development server stopped
|
315 |
+
2025-07-13 15:41:37,038 - INFO - Development server stopped
|
316 |
+
2025-07-13 15:41:41,982 - INFO - Anonymized telemetry enabled. See https://docs.trychroma.com/telemetry for more information.
|
317 |
+
2025-07-13 15:41:43,806 - INFO - Received interrupt signal
|
318 |
+
2025-07-13 15:41:43,806 - INFO - Development server stopped
|
logs/manager.log
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
2025-07-09 11:39:18,873 - INFO - ResearchMate Management System started
|
2 |
+
2025-07-09 11:39:19,052 - INFO - Found 3 test files
|
3 |
+
2025-07-09 11:39:19,053 - INFO - Running: test_arxiv_fetcher.py
|
4 |
+
2025-07-09 11:39:19,053 - ERROR - Failed to run tests: [WinError 2] The system cannot find the file specified
|
5 |
+
2025-07-09 11:40:11,973 - INFO - ResearchMate Management System started
|
6 |
+
2025-07-09 11:40:11,989 - INFO - Running tests...
|
7 |
+
2025-07-09 11:40:11,989 - INFO - Found 3 test files
|
8 |
+
2025-07-09 11:40:11,989 - INFO - Running: test_arxiv_fetcher.py
|
9 |
+
2025-07-09 11:40:11,989 - ERROR - Failed to run tests: [WinError 2] The system cannot find the file specified
|
10 |
+
2025-07-09 11:40:48,295 - INFO - ResearchMate Management System started
|
11 |
+
2025-07-09 11:40:48,295 - INFO - Running tests...
|
12 |
+
2025-07-09 11:40:48,295 - INFO - Found 3 test files
|
13 |
+
2025-07-09 11:40:48,295 - INFO - Running: test_arxiv_fetcher.py
|
14 |
+
2025-07-09 11:40:48,295 - ERROR - Failed to run tests: [WinError 2] The system cannot find the file specified
|
15 |
+
2025-07-09 11:41:47,175 - INFO - ResearchMate Management System started
|
16 |
+
2025-07-09 11:41:47,191 - INFO - Running tests...
|
17 |
+
2025-07-09 11:41:47,193 - INFO - Found 4 test files
|
18 |
+
2025-07-09 11:41:47,194 - INFO - Running: test_arxiv_fetcher.py
|
19 |
+
2025-07-09 11:41:47,194 - ERROR - Failed to run tests: [WinError 2] The system cannot find the file specified
|
20 |
+
2025-07-09 11:42:04,641 - INFO - ResearchMate Management System started
|
21 |
+
2025-07-09 11:42:04,641 - INFO - Running tests...
|
22 |
+
2025-07-09 11:42:04,641 - INFO - Found 4 test files
|
23 |
+
2025-07-09 11:42:04,641 - INFO - Using Python executable: D:\ResearchMate\venv\Scripts\python.exe
|
24 |
+
2025-07-09 11:42:04,641 - INFO - Python executable exists: False
|
25 |
+
2025-07-09 11:42:04,649 - INFO - Running: test_arxiv_fetcher.py
|
26 |
+
2025-07-09 11:42:04,649 - INFO - Full test path: D:\ResearchMate\src\tests\test_arxiv_fetcher.py
|
27 |
+
2025-07-09 11:42:04,650 - ERROR - Failed to run tests: [WinError 2] The system cannot find the file specified
|
28 |
+
2025-07-09 11:42:31,726 - INFO - ResearchMate Management System started
|
29 |
+
2025-07-09 11:42:31,726 - INFO - Running tests...
|
30 |
+
2025-07-09 11:42:31,726 - INFO - Found 4 test files
|
31 |
+
2025-07-09 11:42:31,726 - INFO - Using Python executable: D:\ResearchMate\venv\python.exe
|
32 |
+
2025-07-09 11:42:31,726 - INFO - Python executable exists: True
|
33 |
+
2025-07-09 11:42:31,726 - INFO - Running: test_arxiv_fetcher.py
|
34 |
+
2025-07-09 11:42:31,726 - INFO - Full test path: D:\ResearchMate\src\tests\test_arxiv_fetcher.py
|
35 |
+
2025-07-09 11:42:32,005 - ERROR - FAIL: test_arxiv_fetcher.py
|
36 |
+
2025-07-09 11:42:32,005 - ERROR - Errors:
|
37 |
+
Traceback (most recent call last):
|
38 |
+
File "D:\ResearchMate\src\tests\test_arxiv_fetcher.py", line 13, in test_arxiv_fetcher_import
|
39 |
+
from src.components.arxiv_fetcher import ArxivFetcher
|
40 |
+
File "D:\ResearchMate\src\components\__init__.py", line 6, in <module>
|
41 |
+
from .config import Config
|
42 |
+
File "D:\ResearchMate\src\components\config.py", line 9, in <module>
|
43 |
+
from ..settings import get_settings
|
44 |
+
File "D:\ResearchMate\src\settings.py", line 13, in <module>
|
45 |
+
from dotenv import load_dotenv
|
46 |
+
ModuleNotFoundError: No module named 'dotenv'
|
47 |
+
|
48 |
+
During handling of the above exception, another exception occurred:
|
49 |
+
|
50 |
+
Traceback (most recent call last):
|
51 |
+
File "D:\ResearchMate\src\tests\test_arxiv_fetcher.py", line 34, in <module>
|
52 |
+
success &= test_arxiv_fetcher_import()
|
53 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
54 |
+
File "D:\ResearchMate\src\tests\test_arxiv_fetcher.py", line 17, in test_arxiv_fetcher_import
|
55 |
+
print(f"\u274c ArXiv fetcher import failed: {e}")
|
56 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
57 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
58 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
59 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u274c' in position 0: character maps to <undefined>
|
60 |
+
|
61 |
+
2025-07-09 11:42:32,005 - INFO - Running: test_basic.py
|
62 |
+
2025-07-09 11:42:32,005 - INFO - Full test path: D:\ResearchMate\src\tests\test_basic.py
|
63 |
+
2025-07-09 11:42:32,088 - ERROR - FAIL: test_basic.py
|
64 |
+
2025-07-09 11:42:32,088 - ERROR - Errors:
|
65 |
+
Traceback (most recent call last):
|
66 |
+
File "D:\ResearchMate\src\tests\test_basic.py", line 15, in test_basic_functionality
|
67 |
+
print("\u2705 Basic functionality test passed")
|
68 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
69 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
70 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
71 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 0: character maps to <undefined>
|
72 |
+
|
73 |
+
During handling of the above exception, another exception occurred:
|
74 |
+
|
75 |
+
Traceback (most recent call last):
|
76 |
+
File "D:\ResearchMate\src\tests\test_basic.py", line 37, in <module>
|
77 |
+
success &= test_basic_functionality()
|
78 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
79 |
+
File "D:\ResearchMate\src\tests\test_basic.py", line 18, in test_basic_functionality
|
80 |
+
print(f"\u274c Basic functionality test failed: {e}")
|
81 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
82 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
83 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
84 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u274c' in position 0: character maps to <undefined>
|
85 |
+
|
86 |
+
2025-07-09 11:42:32,088 - INFO - Running: test_config.py
|
87 |
+
2025-07-09 11:42:32,088 - INFO - Full test path: D:\ResearchMate\src\tests\test_config.py
|
88 |
+
2025-07-09 11:42:32,207 - ERROR - FAIL: test_config.py
|
89 |
+
2025-07-09 11:42:32,207 - ERROR - Errors:
|
90 |
+
Traceback (most recent call last):
|
91 |
+
File "D:\ResearchMate\src\tests\test_config.py", line 10, in <module>
|
92 |
+
from src.settings import Settings
|
93 |
+
File "D:\ResearchMate\src\settings.py", line 13, in <module>
|
94 |
+
from dotenv import load_dotenv
|
95 |
+
ModuleNotFoundError: No module named 'dotenv'
|
96 |
+
|
97 |
+
2025-07-09 11:42:32,207 - INFO - Running: test_pdf_processor.py
|
98 |
+
2025-07-09 11:42:32,207 - INFO - Full test path: D:\ResearchMate\src\tests\test_pdf_processor.py
|
99 |
+
2025-07-09 11:42:32,358 - ERROR - FAIL: test_pdf_processor.py
|
100 |
+
2025-07-09 11:42:32,358 - ERROR - Errors:
|
101 |
+
Traceback (most recent call last):
|
102 |
+
File "D:\ResearchMate\src\tests\test_pdf_processor.py", line 13, in test_pdf_processor_import
|
103 |
+
from src.components.pdf_processor import PDFProcessor
|
104 |
+
File "D:\ResearchMate\src\components\__init__.py", line 6, in <module>
|
105 |
+
from .config import Config
|
106 |
+
File "D:\ResearchMate\src\components\config.py", line 9, in <module>
|
107 |
+
from ..settings import get_settings
|
108 |
+
File "D:\ResearchMate\src\settings.py", line 13, in <module>
|
109 |
+
from dotenv import load_dotenv
|
110 |
+
ModuleNotFoundError: No module named 'dotenv'
|
111 |
+
|
112 |
+
During handling of the above exception, another exception occurred:
|
113 |
+
|
114 |
+
Traceback (most recent call last):
|
115 |
+
File "D:\ResearchMate\src\tests\test_pdf_processor.py", line 34, in <module>
|
116 |
+
success &= test_pdf_processor_import()
|
117 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
118 |
+
File "D:\ResearchMate\src\tests\test_pdf_processor.py", line 17, in test_pdf_processor_import
|
119 |
+
print(f"\u274c PDF processor import failed: {e}")
|
120 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
121 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
122 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
123 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u274c' in position 0: character maps to <undefined>
|
124 |
+
|
125 |
+
2025-07-09 11:42:32,358 - ERROR - Some tests failed!
|
126 |
+
2025-07-09 11:59:32,349 - INFO - ResearchMate Management System started
|
127 |
+
2025-07-09 11:59:32,349 - INFO - Running tests...
|
128 |
+
2025-07-09 11:59:32,349 - INFO - Found 3 test files
|
129 |
+
2025-07-09 11:59:32,349 - INFO - Using Python executable: D:\ResearchMate\venv\python.exe
|
130 |
+
2025-07-09 11:59:32,349 - INFO - Python executable exists: True
|
131 |
+
2025-07-09 11:59:32,349 - INFO - Running: test_arxiv_fetcher.py
|
132 |
+
2025-07-09 11:59:32,349 - INFO - Full test path: D:\ResearchMate\src\tests\test_arxiv_fetcher.py
|
133 |
+
2025-07-09 11:59:33,038 - INFO - PASS: test_arxiv_fetcher.py
|
134 |
+
2025-07-09 11:59:33,038 - INFO - Output:
|
135 |
+
PASS: ArXiv fetcher import test passed
|
136 |
+
PASS: ArXiv fetcher creation test passed
|
137 |
+
All ArXiv fetcher tests passed!
|
138 |
+
|
139 |
+
2025-07-09 11:59:33,038 - INFO - Running: test_config.py
|
140 |
+
2025-07-09 11:59:33,038 - INFO - Full test path: D:\ResearchMate\src\tests\test_config.py
|
141 |
+
2025-07-09 11:59:33,263 - ERROR - FAIL: test_config.py
|
142 |
+
2025-07-09 11:59:33,263 - ERROR - Errors:
|
143 |
+
Traceback (most recent call last):
|
144 |
+
File "D:\ResearchMate\src\tests\test_config.py", line 19, in test_settings_load
|
145 |
+
print("\u2705 Settings loading test passed")
|
146 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
147 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
148 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
149 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 0: character maps to <undefined>
|
150 |
+
|
151 |
+
During handling of the above exception, another exception occurred:
|
152 |
+
|
153 |
+
Traceback (most recent call last):
|
154 |
+
File "D:\ResearchMate\src\tests\test_config.py", line 63, in <module>
|
155 |
+
success &= test_settings_load()
|
156 |
+
^^^^^^^^^^^^^^^^^^^^
|
157 |
+
File "D:\ResearchMate\src\tests\test_config.py", line 22, in test_settings_load
|
158 |
+
print(f"\u274c Settings loading failed: {e}")
|
159 |
+
File "D:\ResearchMate\venv\Lib\encodings\cp1252.py", line 19, in encode
|
160 |
+
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
|
161 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
162 |
+
UnicodeEncodeError: 'charmap' codec can't encode character '\u274c' in position 0: character maps to <undefined>
|
163 |
+
|
164 |
+
2025-07-09 11:59:33,263 - INFO - Running: test_pdf_processor.py
|
165 |
+
2025-07-09 11:59:33,263 - INFO - Full test path: D:\ResearchMate\src\tests\test_pdf_processor.py
|
166 |
+
2025-07-09 11:59:33,846 - ERROR - FAIL: test_pdf_processor.py
|
167 |
+
2025-07-09 11:59:33,846 - ERROR - Output:
|
168 |
+
PASS: PDF processor import test passed
|
169 |
+
FAIL: PDF processor creation failed: 'charmap' codec can't encode character '\U0001f4c4' in position 0: character maps to <undefined>
|
170 |
+
Some tests failed!
|
171 |
+
|
172 |
+
2025-07-09 11:59:33,846 - ERROR - Some tests failed!
|
173 |
+
2025-07-09 12:05:29,920 - INFO - ResearchMate Management System started
|
174 |
+
2025-07-09 12:05:29,927 - INFO - Running tests...
|
175 |
+
2025-07-09 12:05:29,929 - INFO - Found 3 test files
|
176 |
+
2025-07-09 12:05:29,930 - INFO - Using Python executable: D:\ResearchMate\venv\python.exe
|
177 |
+
2025-07-09 12:05:29,930 - INFO - Python executable exists: True
|
178 |
+
2025-07-09 12:05:29,930 - INFO - Running: test_arxiv_fetcher.py
|
179 |
+
2025-07-09 12:05:29,930 - INFO - Full test path: D:\ResearchMate\src\tests\test_arxiv_fetcher.py
|
180 |
+
2025-07-09 12:05:31,045 - INFO - PASS: test_arxiv_fetcher.py
|
181 |
+
2025-07-09 12:05:31,045 - INFO - Output:
|
182 |
+
PASS: ArXiv fetcher import test passed
|
183 |
+
PASS: ArXiv fetcher creation test passed
|
184 |
+
All ArXiv fetcher tests passed!
|
185 |
+
|
186 |
+
2025-07-09 12:05:31,045 - INFO - Running: test_config.py
|
187 |
+
2025-07-09 12:05:31,045 - INFO - Full test path: D:\ResearchMate\src\tests\test_config.py
|
188 |
+
2025-07-09 12:05:31,260 - INFO - PASS: test_config.py
|
189 |
+
2025-07-09 12:05:31,260 - INFO - Output:
|
190 |
+
PASS: Settings loading test passed
|
191 |
+
PASS: Default settings test passed
|
192 |
+
PASS: Settings types test passed
|
193 |
+
All configuration tests passed!
|
194 |
+
|
195 |
+
2025-07-09 12:05:31,260 - INFO - Running: test_pdf_processor.py
|
196 |
+
2025-07-09 12:05:31,260 - INFO - Full test path: D:\ResearchMate\src\tests\test_pdf_processor.py
|
197 |
+
2025-07-09 12:05:33,713 - INFO - PASS: test_pdf_processor.py
|
198 |
+
2025-07-09 12:05:33,713 - INFO - Output:
|
199 |
+
PASS: PDF processor import test passed
|
200 |
+
PDF Processor initialized with libraries: ['PyPDF2', 'pdfplumber', 'PyMuPDF']
|
201 |
+
PASS: PDF processor creation test passed
|
202 |
+
All PDF processor tests passed!
|
203 |
+
|
204 |
+
2025-07-09 12:05:33,714 - INFO - All tests passed successfully!
|
205 |
+
2025-07-09 12:09:47,665 - INFO - ResearchMate Management System started
|
206 |
+
2025-07-09 12:09:47,665 - INFO - Starting development server...
|
207 |
+
2025-07-09 12:10:44,117 - INFO - ResearchMate Management System started
|
208 |
+
2025-07-09 12:10:44,117 - INFO - Starting development server...
|
209 |
+
2025-07-09 12:15:38,602 - INFO - ResearchMate Management System started
|
210 |
+
2025-07-09 12:15:38,603 - INFO - Starting development server...
|
211 |
+
2025-07-09 12:16:06,617 - INFO - ResearchMate Management System started
|
212 |
+
2025-07-09 12:16:18,432 - INFO - ResearchMate Management System started
|
213 |
+
2025-07-09 12:16:18,433 - INFO - Starting production server...
|
214 |
+
2025-07-09 12:19:07,072 - INFO - ResearchMate Management System started
|
215 |
+
2025-07-09 12:19:07,093 - INFO - Starting production server...
|
216 |
+
2025-07-09 15:10:32,398 - INFO - ResearchMate Management System started
|
217 |
+
2025-07-09 15:10:32,492 - INFO - Starting production server...
|
218 |
+
2025-07-13 15:39:12,835 - INFO - ResearchMate Management System started
|
219 |
+
2025-07-13 15:39:29,892 - INFO - ResearchMate Management System started
|
220 |
+
2025-07-13 15:39:29,892 - INFO - Starting production server...
|
221 |
+
2025-07-13 15:40:17,039 - INFO - Server stopped by user
|
222 |
+
2025-07-13 15:40:29,034 - INFO - ResearchMate Management System started
|
223 |
+
2025-07-13 15:40:29,035 - INFO - Starting development server...
|
224 |
+
2025-07-13 15:41:13,529 - INFO - Server stopped by user
|
logs/setup.log
ADDED
File without changes
|
main.py
ADDED
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import json
|
4 |
+
import asyncio
|
5 |
+
from typing import Dict, List, Optional, Any
|
6 |
+
from datetime import datetime
|
7 |
+
from pathlib import Path
|
8 |
+
from contextlib import asynccontextmanager
|
9 |
+
|
10 |
+
# Add the project root to Python path
|
11 |
+
sys.path.append(str(Path(__file__).parent))
|
12 |
+
|
13 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File, Form, Request, Depends
|
14 |
+
from fastapi.staticfiles import StaticFiles
|
15 |
+
from fastapi.templating import Jinja2Templates
|
16 |
+
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, FileResponse
|
17 |
+
from fastapi.middleware.cors import CORSMiddleware
|
18 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
19 |
+
from pydantic import BaseModel, Field
|
20 |
+
import uvicorn
|
21 |
+
|
22 |
+
# Import settings and ResearchMate components
|
23 |
+
from src.components.research_assistant import ResearchMate
|
24 |
+
from src.components.citation_network import CitationNetworkAnalyzer
|
25 |
+
from src.components.auth import AuthManager
|
26 |
+
|
27 |
+
# Initialize only essential components at startup (fast components only)
|
28 |
+
auth_manager = AuthManager()
|
29 |
+
security = HTTPBearer(auto_error=False)
|
30 |
+
|
31 |
+
# Simple settings for development
|
32 |
+
class Settings:
|
33 |
+
def __init__(self):
|
34 |
+
self.server = type('ServerSettings', (), {
|
35 |
+
'debug': False,
|
36 |
+
'host': '0.0.0.0',
|
37 |
+
'port': int(os.environ.get('PORT', 8000))
|
38 |
+
})()
|
39 |
+
self.security = type('SecuritySettings', (), {
|
40 |
+
'cors_origins': ["*"],
|
41 |
+
'cors_methods': ["*"],
|
42 |
+
'cors_headers': ["*"]
|
43 |
+
})()
|
44 |
+
|
45 |
+
def get_static_dir(self):
|
46 |
+
return "src/static"
|
47 |
+
|
48 |
+
def get_templates_dir(self):
|
49 |
+
return "src/templates"
|
50 |
+
|
51 |
+
settings = Settings()
|
52 |
+
|
53 |
+
# Initialize ResearchMate and Citation Analyzer (will be done during loading screen)
|
54 |
+
research_mate = None
|
55 |
+
citation_analyzer = None
|
56 |
+
|
57 |
+
# Global initialization flag
|
58 |
+
research_mate_initialized = False
|
59 |
+
initialization_in_progress = False
|
60 |
+
|
61 |
+
async def initialize_research_mate():
|
62 |
+
"""Initialize ResearchMate and Citation Analyzer in the background"""
|
63 |
+
global research_mate, citation_analyzer, research_mate_initialized, initialization_in_progress
|
64 |
+
|
65 |
+
if initialization_in_progress:
|
66 |
+
return
|
67 |
+
|
68 |
+
initialization_in_progress = True
|
69 |
+
print("🚀 Starting ResearchMate background initialization...")
|
70 |
+
|
71 |
+
try:
|
72 |
+
# Run initialization in thread pool to avoid blocking
|
73 |
+
import concurrent.futures
|
74 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
75 |
+
loop = asyncio.get_event_loop()
|
76 |
+
|
77 |
+
print("📊 Initializing Citation Network Analyzer...")
|
78 |
+
citation_analyzer = await loop.run_in_executor(executor, CitationNetworkAnalyzer)
|
79 |
+
print("✅ Citation Network Analyzer initialized!")
|
80 |
+
|
81 |
+
print("🧠 Initializing ResearchMate core...")
|
82 |
+
research_mate = await loop.run_in_executor(executor, ResearchMate)
|
83 |
+
print("✅ ResearchMate core initialized!")
|
84 |
+
|
85 |
+
research_mate_initialized = True
|
86 |
+
print("🎉 All components initialized successfully!")
|
87 |
+
except Exception as e:
|
88 |
+
print(f"❌ Failed to initialize components: {e}")
|
89 |
+
print("⚠️ Server will start but some features may not work")
|
90 |
+
research_mate = None
|
91 |
+
citation_analyzer = None
|
92 |
+
research_mate_initialized = False
|
93 |
+
finally:
|
94 |
+
initialization_in_progress = False
|
95 |
+
|
96 |
+
# Pydantic models for API
|
97 |
+
class SearchQuery(BaseModel):
|
98 |
+
query: str = Field(..., description="Search query")
|
99 |
+
max_results: int = Field(default=10, ge=1, le=50, description="Maximum number of results")
|
100 |
+
|
101 |
+
class QuestionQuery(BaseModel):
|
102 |
+
question: str = Field(..., description="Research question")
|
103 |
+
|
104 |
+
class ProjectCreate(BaseModel):
|
105 |
+
name: str = Field(..., description="Project name")
|
106 |
+
research_question: str = Field(..., description="Research question")
|
107 |
+
keywords: List[str] = Field(..., description="Keywords")
|
108 |
+
|
109 |
+
class ProjectQuery(BaseModel):
|
110 |
+
project_id: str = Field(..., description="Project ID")
|
111 |
+
question: str = Field(..., description="Question about the project")
|
112 |
+
|
113 |
+
class TrendQuery(BaseModel):
|
114 |
+
topic: str = Field(..., description="Research topic")
|
115 |
+
|
116 |
+
# Authentication models
|
117 |
+
class LoginRequest(BaseModel):
|
118 |
+
username: str = Field(..., description="Username")
|
119 |
+
password: str = Field(..., description="Password")
|
120 |
+
|
121 |
+
class RegisterRequest(BaseModel):
|
122 |
+
username: str = Field(..., description="Username")
|
123 |
+
email: str = Field(..., description="Email address")
|
124 |
+
password: str = Field(..., description="Password")
|
125 |
+
|
126 |
+
# Authentication dependency for API endpoints
|
127 |
+
async def get_current_user_dependency(request: Request, credentials: HTTPAuthorizationCredentials = Depends(security)):
|
128 |
+
user = None
|
129 |
+
|
130 |
+
# Try Authorization header first
|
131 |
+
if credentials:
|
132 |
+
user = auth_manager.verify_token(credentials.credentials)
|
133 |
+
|
134 |
+
# If no user from header, try cookie
|
135 |
+
if not user:
|
136 |
+
token = request.cookies.get('authToken')
|
137 |
+
if token:
|
138 |
+
user = auth_manager.verify_token(token)
|
139 |
+
|
140 |
+
if not user:
|
141 |
+
raise HTTPException(status_code=401, detail="Authentication required")
|
142 |
+
|
143 |
+
return user
|
144 |
+
|
145 |
+
# Authentication for web pages (checks both header and cookie)
|
146 |
+
async def get_current_user_web(request: Request):
|
147 |
+
"""Get current user for web page requests (checks both Authorization header and cookies)"""
|
148 |
+
user = None
|
149 |
+
|
150 |
+
# First try Authorization header
|
151 |
+
try:
|
152 |
+
credentials = await security(request)
|
153 |
+
if credentials:
|
154 |
+
user = auth_manager.verify_token(credentials.credentials)
|
155 |
+
except:
|
156 |
+
pass
|
157 |
+
|
158 |
+
# If no user from header, try cookie
|
159 |
+
if not user:
|
160 |
+
token = request.cookies.get('authToken')
|
161 |
+
if token:
|
162 |
+
user = auth_manager.verify_token(token)
|
163 |
+
|
164 |
+
return user
|
165 |
+
|
166 |
+
# Background task to clean up expired sessions
|
167 |
+
async def cleanup_expired_sessions():
|
168 |
+
while True:
|
169 |
+
try:
|
170 |
+
expired_count = auth_manager.cleanup_expired_sessions()
|
171 |
+
if expired_count > 0:
|
172 |
+
print(f"Cleaned up {expired_count} expired sessions")
|
173 |
+
except Exception as e:
|
174 |
+
print(f"Error cleaning up sessions: {e}")
|
175 |
+
|
176 |
+
# Run cleanup every 30 minutes
|
177 |
+
await asyncio.sleep(30 * 60)
|
178 |
+
|
179 |
+
@asynccontextmanager
|
180 |
+
async def lifespan(app: FastAPI):
|
181 |
+
# Start ResearchMate initialization in background (non-blocking)
|
182 |
+
asyncio.create_task(initialize_research_mate())
|
183 |
+
|
184 |
+
# Start background cleanup task
|
185 |
+
cleanup_task = asyncio.create_task(cleanup_expired_sessions())
|
186 |
+
|
187 |
+
try:
|
188 |
+
yield
|
189 |
+
finally:
|
190 |
+
cleanup_task.cancel()
|
191 |
+
try:
|
192 |
+
await cleanup_task
|
193 |
+
except asyncio.CancelledError:
|
194 |
+
pass
|
195 |
+
|
196 |
+
# Initialize FastAPI app with lifespan
|
197 |
+
app = FastAPI(
|
198 |
+
title="ResearchMate API",
|
199 |
+
description="AI Research Assistant powered by Groq Llama 3.3 70B",
|
200 |
+
version="1.0.0",
|
201 |
+
debug=settings.server.debug,
|
202 |
+
lifespan=lifespan
|
203 |
+
)
|
204 |
+
|
205 |
+
# Add CORS middleware
|
206 |
+
app.add_middleware(
|
207 |
+
CORSMiddleware,
|
208 |
+
allow_origins=settings.security.cors_origins,
|
209 |
+
allow_credentials=True,
|
210 |
+
allow_methods=settings.security.cors_methods,
|
211 |
+
allow_headers=settings.security.cors_headers,
|
212 |
+
)
|
213 |
+
|
214 |
+
# Mount static files with cache control for development
|
215 |
+
static_dir = Path(settings.get_static_dir())
|
216 |
+
static_dir.mkdir(parents=True, exist_ok=True)
|
217 |
+
|
218 |
+
# Custom static files class to add no-cache headers for development
|
219 |
+
class NoCacheStaticFiles(StaticFiles):
|
220 |
+
def file_response(self, full_path, stat_result, scope):
|
221 |
+
response = FileResponse(
|
222 |
+
path=full_path,
|
223 |
+
stat_result=stat_result
|
224 |
+
)
|
225 |
+
# Add no-cache headers for development
|
226 |
+
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
|
227 |
+
response.headers["Pragma"] = "no-cache"
|
228 |
+
response.headers["Expires"] = "0"
|
229 |
+
return response
|
230 |
+
|
231 |
+
app.mount("/static", NoCacheStaticFiles(directory=str(static_dir)), name="static")
|
232 |
+
|
233 |
+
# Templates
|
234 |
+
templates_dir = Path(settings.get_templates_dir())
|
235 |
+
templates_dir.mkdir(parents=True, exist_ok=True)
|
236 |
+
templates = Jinja2Templates(directory=str(templates_dir))
|
237 |
+
|
238 |
+
# Loading page route
|
239 |
+
@app.get("/loading", response_class=HTMLResponse)
|
240 |
+
async def loading_page(request: Request):
|
241 |
+
return templates.TemplateResponse("loading.html", {"request": request})
|
242 |
+
|
243 |
+
# Authentication routes
|
244 |
+
@app.post("/api/auth/register")
|
245 |
+
async def register(request: RegisterRequest):
|
246 |
+
result = auth_manager.create_user(request.username, request.email, request.password)
|
247 |
+
if result["success"]:
|
248 |
+
return {"success": True, "message": "Account created successfully"}
|
249 |
+
else:
|
250 |
+
raise HTTPException(status_code=400, detail=result["error"])
|
251 |
+
|
252 |
+
@app.post("/api/auth/login")
|
253 |
+
async def login(request: LoginRequest):
|
254 |
+
result = auth_manager.authenticate_user(request.username, request.password)
|
255 |
+
if result["success"]:
|
256 |
+
return {
|
257 |
+
"success": True,
|
258 |
+
"token": result["token"],
|
259 |
+
"user_id": result["user_id"],
|
260 |
+
"username": result["username"]
|
261 |
+
}
|
262 |
+
else:
|
263 |
+
raise HTTPException(status_code=401, detail=result["error"])
|
264 |
+
|
265 |
+
@app.get("/login", response_class=HTMLResponse)
|
266 |
+
async def login_page(request: Request):
|
267 |
+
# Check if ResearchMate is initialized
|
268 |
+
global research_mate_initialized
|
269 |
+
if not research_mate_initialized:
|
270 |
+
return RedirectResponse(url="/loading", status_code=302)
|
271 |
+
|
272 |
+
return templates.TemplateResponse("login.html", {"request": request})
|
273 |
+
|
274 |
+
@app.post("/api/auth/logout")
|
275 |
+
async def logout(request: Request):
|
276 |
+
# Get current user to invalidate their session
|
277 |
+
user = await get_current_user_web(request)
|
278 |
+
if user:
|
279 |
+
auth_manager.logout_user(user['user_id'])
|
280 |
+
|
281 |
+
response = JSONResponse({"success": True, "message": "Logged out successfully"})
|
282 |
+
response.delete_cookie("authToken", path="/")
|
283 |
+
return response
|
284 |
+
|
285 |
+
# Web interface routes (protected)
|
286 |
+
@app.get("/", response_class=HTMLResponse)
|
287 |
+
async def home(request: Request):
|
288 |
+
# Check if ResearchMate is initialized first
|
289 |
+
global research_mate_initialized
|
290 |
+
if not research_mate_initialized:
|
291 |
+
return RedirectResponse(url="/loading", status_code=302)
|
292 |
+
|
293 |
+
# Check if user is authenticated
|
294 |
+
user = await get_current_user_web(request)
|
295 |
+
if not user:
|
296 |
+
return RedirectResponse(url="/login", status_code=302)
|
297 |
+
return templates.TemplateResponse("index.html", {"request": request, "user": user})
|
298 |
+
|
299 |
+
@app.get("/search", response_class=HTMLResponse)
|
300 |
+
async def search_page(request: Request):
|
301 |
+
# Check if ResearchMate is initialized first
|
302 |
+
global research_mate_initialized
|
303 |
+
if not research_mate_initialized:
|
304 |
+
return RedirectResponse(url="/loading", status_code=302)
|
305 |
+
|
306 |
+
user = await get_current_user_web(request)
|
307 |
+
if not user:
|
308 |
+
return RedirectResponse(url="/login", status_code=302)
|
309 |
+
return templates.TemplateResponse("search.html", {"request": request, "user": user})
|
310 |
+
|
311 |
+
@app.get("/projects", response_class=HTMLResponse)
|
312 |
+
async def projects_page(request: Request):
|
313 |
+
user = await get_current_user_web(request)
|
314 |
+
if not user:
|
315 |
+
return RedirectResponse(url="/login", status_code=302)
|
316 |
+
return templates.TemplateResponse("projects.html", {"request": request, "user": user})
|
317 |
+
|
318 |
+
@app.get("/trends", response_class=HTMLResponse)
|
319 |
+
async def trends_page(request: Request):
|
320 |
+
user = await get_current_user_web(request)
|
321 |
+
if not user:
|
322 |
+
return RedirectResponse(url="/login", status_code=302)
|
323 |
+
return templates.TemplateResponse("trends.html", {"request": request, "user": user})
|
324 |
+
|
325 |
+
@app.get("/upload", response_class=HTMLResponse)
|
326 |
+
async def upload_page(request: Request):
|
327 |
+
user = await get_current_user_web(request)
|
328 |
+
if not user:
|
329 |
+
return RedirectResponse(url="/login", status_code=302)
|
330 |
+
return templates.TemplateResponse("upload.html", {"request": request, "user": user})
|
331 |
+
|
332 |
+
@app.get("/citation", response_class=HTMLResponse)
|
333 |
+
async def citation_page(request: Request):
|
334 |
+
try:
|
335 |
+
if citation_analyzer is None:
|
336 |
+
# If citation analyzer isn't initialized yet, show empty state
|
337 |
+
summary = {"total_papers": 0, "total_citations": 0, "networks": []}
|
338 |
+
else:
|
339 |
+
summary = citation_analyzer.get_network_summary()
|
340 |
+
return templates.TemplateResponse("citation.html", {"request": request, "summary": summary})
|
341 |
+
except Exception as e:
|
342 |
+
raise HTTPException(status_code=500, detail=str(e))
|
343 |
+
|
344 |
+
@app.get("/test-search", response_class=HTMLResponse)
|
345 |
+
async def test_search_page(request: Request):
|
346 |
+
"""Simple test page for debugging search"""
|
347 |
+
with open("test_search.html", "r") as f:
|
348 |
+
content = f.read()
|
349 |
+
return HTMLResponse(content=content)
|
350 |
+
|
351 |
+
# API endpoints
|
352 |
+
@app.post("/api/search")
|
353 |
+
async def search_papers(query: SearchQuery, current_user: dict = Depends(get_current_user_dependency)):
|
354 |
+
try:
|
355 |
+
if research_mate is None:
|
356 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
357 |
+
rm = research_mate
|
358 |
+
result = rm.search(query.query, query.max_results)
|
359 |
+
if not result.get("success"):
|
360 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Search failed"))
|
361 |
+
papers = result.get("papers", [])
|
362 |
+
if papers and citation_analyzer is not None: # Only add papers if citation analyzer is ready
|
363 |
+
citation_analyzer.add_papers(papers)
|
364 |
+
return result
|
365 |
+
except Exception as e:
|
366 |
+
raise HTTPException(status_code=500, detail=str(e))
|
367 |
+
|
368 |
+
@app.post("/api/ask")
|
369 |
+
async def ask_question(question: QuestionQuery, current_user: dict = Depends(get_current_user_dependency)):
|
370 |
+
try:
|
371 |
+
if research_mate is None:
|
372 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
373 |
+
rm = research_mate
|
374 |
+
result = rm.ask(question.question)
|
375 |
+
if not result.get("success"):
|
376 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Question failed"))
|
377 |
+
return result
|
378 |
+
except Exception as e:
|
379 |
+
raise HTTPException(status_code=500, detail=str(e))
|
380 |
+
|
381 |
+
@app.post("/api/upload")
|
382 |
+
async def upload_pdf(file: UploadFile = File(...), current_user: dict = Depends(get_current_user_dependency)):
|
383 |
+
if research_mate is None:
|
384 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
385 |
+
|
386 |
+
if not file.filename.endswith('.pdf'):
|
387 |
+
raise HTTPException(status_code=400, detail="Only PDF files are supported")
|
388 |
+
|
389 |
+
try:
|
390 |
+
# Save uploaded file
|
391 |
+
upload_dir = Path("uploads")
|
392 |
+
upload_dir.mkdir(exist_ok=True)
|
393 |
+
file_path = upload_dir / file.filename
|
394 |
+
|
395 |
+
with open(file_path, "wb") as buffer:
|
396 |
+
content = await file.read()
|
397 |
+
buffer.write(content)
|
398 |
+
|
399 |
+
# Process PDF
|
400 |
+
result = research_mate.upload_pdf(str(file_path))
|
401 |
+
|
402 |
+
# Clean up file
|
403 |
+
file_path.unlink()
|
404 |
+
|
405 |
+
if not result.get("success"):
|
406 |
+
raise HTTPException(status_code=400, detail=result.get("error", "PDF analysis failed"))
|
407 |
+
|
408 |
+
return result
|
409 |
+
except Exception as e:
|
410 |
+
raise HTTPException(status_code=500, detail=str(e))
|
411 |
+
|
412 |
+
@app.post("/api/projects")
|
413 |
+
async def create_project(project: ProjectCreate, current_user: dict = Depends(get_current_user_dependency)):
|
414 |
+
if research_mate is None:
|
415 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
416 |
+
|
417 |
+
try:
|
418 |
+
user_id = current_user.get("user_id")
|
419 |
+
result = research_mate.create_project(project.name, project.research_question, project.keywords, user_id)
|
420 |
+
if not result.get("success"):
|
421 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Project creation failed"))
|
422 |
+
return result
|
423 |
+
except Exception as e:
|
424 |
+
raise HTTPException(status_code=500, detail=str(e))
|
425 |
+
|
426 |
+
@app.get("/api/projects")
|
427 |
+
async def list_projects(current_user: dict = Depends(get_current_user_dependency)):
|
428 |
+
if research_mate is None:
|
429 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
430 |
+
|
431 |
+
try:
|
432 |
+
user_id = current_user.get("user_id")
|
433 |
+
result = research_mate.list_projects(user_id)
|
434 |
+
if not result.get("success"):
|
435 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Failed to list projects"))
|
436 |
+
return result
|
437 |
+
except Exception as e:
|
438 |
+
raise HTTPException(status_code=500, detail=str(e))
|
439 |
+
|
440 |
+
@app.get("/api/projects/{project_id}")
|
441 |
+
async def get_project(project_id: str, current_user: dict = Depends(get_current_user_dependency)):
|
442 |
+
if research_mate is None:
|
443 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
444 |
+
|
445 |
+
try:
|
446 |
+
user_id = current_user.get("user_id")
|
447 |
+
result = research_mate.get_project(project_id, user_id)
|
448 |
+
if not result.get("success"):
|
449 |
+
raise HTTPException(status_code=404, detail=result.get("error", "Project not found"))
|
450 |
+
return result
|
451 |
+
except Exception as e:
|
452 |
+
raise HTTPException(status_code=500, detail=str(e))
|
453 |
+
|
454 |
+
@app.post("/api/projects/{project_id}/search")
|
455 |
+
async def search_project_literature(project_id: str, max_papers: int = 10, current_user: dict = Depends(get_current_user_dependency)):
|
456 |
+
if research_mate is None:
|
457 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
458 |
+
|
459 |
+
try:
|
460 |
+
user_id = current_user.get("user_id")
|
461 |
+
result = research_mate.search_project_literature(project_id, max_papers, user_id)
|
462 |
+
if not result.get("success"):
|
463 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Literature search failed"))
|
464 |
+
return result
|
465 |
+
except Exception as e:
|
466 |
+
raise HTTPException(status_code=500, detail=str(e))
|
467 |
+
|
468 |
+
@app.post("/api/projects/{project_id}/analyze")
|
469 |
+
async def analyze_project(project_id: str, current_user: dict = Depends(get_current_user_dependency)):
|
470 |
+
if research_mate is None:
|
471 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
472 |
+
|
473 |
+
try:
|
474 |
+
user_id = current_user.get("user_id")
|
475 |
+
result = research_mate.analyze_project(project_id, user_id)
|
476 |
+
if not result.get("success"):
|
477 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Project analysis failed"))
|
478 |
+
return result
|
479 |
+
except Exception as e:
|
480 |
+
raise HTTPException(status_code=500, detail=str(e))
|
481 |
+
|
482 |
+
@app.post("/api/projects/{project_id}/review")
|
483 |
+
async def generate_review(project_id: str, current_user: dict = Depends(get_current_user_dependency)):
|
484 |
+
if research_mate is None:
|
485 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
486 |
+
|
487 |
+
try:
|
488 |
+
user_id = current_user.get("user_id")
|
489 |
+
result = research_mate.generate_review(project_id, user_id)
|
490 |
+
if not result.get("success"):
|
491 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Review generation failed"))
|
492 |
+
return result
|
493 |
+
except Exception as e:
|
494 |
+
raise HTTPException(status_code=500, detail=str(e))
|
495 |
+
|
496 |
+
@app.post("/api/projects/{project_id}/ask")
|
497 |
+
async def ask_project_question(project_id: str, question: QuestionQuery):
|
498 |
+
if research_mate is None:
|
499 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
500 |
+
|
501 |
+
try:
|
502 |
+
result = research_mate.ask_project_question(project_id, question.question)
|
503 |
+
if not result.get("success"):
|
504 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Project question failed"))
|
505 |
+
return result
|
506 |
+
except Exception as e:
|
507 |
+
raise HTTPException(status_code=500, detail=str(e))
|
508 |
+
|
509 |
+
|
510 |
+
|
511 |
+
@app.post("/api/trends")
|
512 |
+
async def get_trends(trend: TrendQuery):
|
513 |
+
if research_mate is None:
|
514 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
515 |
+
|
516 |
+
try:
|
517 |
+
result = research_mate.analyze_trends(trend.topic)
|
518 |
+
if result.get("error"):
|
519 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Trend analysis failed"))
|
520 |
+
return result
|
521 |
+
except Exception as e:
|
522 |
+
raise HTTPException(status_code=500, detail=str(e))
|
523 |
+
|
524 |
+
@app.post("/api/trends/temporal")
|
525 |
+
async def get_temporal_trends(trend: TrendQuery):
|
526 |
+
"""Get temporal trend analysis"""
|
527 |
+
if research_mate is None:
|
528 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
529 |
+
|
530 |
+
try:
|
531 |
+
# Get papers for analysis
|
532 |
+
papers = research_mate.search_papers(trend.topic, 50)
|
533 |
+
if not papers:
|
534 |
+
raise HTTPException(status_code=404, detail="No papers found for temporal analysis")
|
535 |
+
|
536 |
+
# Use advanced trend monitor
|
537 |
+
result = research_mate.trend_monitor.analyze_temporal_trends(papers)
|
538 |
+
if result.get("error"):
|
539 |
+
raise HTTPException(status_code=400, detail=result.get("error"))
|
540 |
+
|
541 |
+
return {
|
542 |
+
"topic": trend.topic,
|
543 |
+
"temporal_analysis": result,
|
544 |
+
"papers_analyzed": len(papers)
|
545 |
+
}
|
546 |
+
except Exception as e:
|
547 |
+
raise HTTPException(status_code=500, detail=str(e))
|
548 |
+
|
549 |
+
@app.post("/api/trends/gaps")
|
550 |
+
async def detect_research_gaps(trend: TrendQuery):
|
551 |
+
"""Detect research gaps for a topic"""
|
552 |
+
if research_mate is None:
|
553 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
554 |
+
|
555 |
+
try:
|
556 |
+
# Get papers for gap analysis
|
557 |
+
papers = research_mate.search_papers(trend.topic, 50)
|
558 |
+
if not papers:
|
559 |
+
raise HTTPException(status_code=404, detail="No papers found for gap analysis")
|
560 |
+
|
561 |
+
# Use advanced trend monitor
|
562 |
+
result = research_mate.trend_monitor.detect_research_gaps(papers)
|
563 |
+
if result.get("error"):
|
564 |
+
raise HTTPException(status_code=400, detail=result.get("error"))
|
565 |
+
|
566 |
+
return {
|
567 |
+
"topic": trend.topic,
|
568 |
+
"gap_analysis": result,
|
569 |
+
"papers_analyzed": len(papers)
|
570 |
+
}
|
571 |
+
except Exception as e:
|
572 |
+
raise HTTPException(status_code=500, detail=str(e))
|
573 |
+
|
574 |
+
@app.get("/api/status")
|
575 |
+
async def get_status(current_user: dict = Depends(get_current_user_dependency)):
|
576 |
+
if research_mate is None:
|
577 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
578 |
+
|
579 |
+
try:
|
580 |
+
result = research_mate.get_status()
|
581 |
+
# Ensure proper structure for frontend
|
582 |
+
if result.get('success'):
|
583 |
+
return {
|
584 |
+
'success': True,
|
585 |
+
'statistics': result.get('statistics', {
|
586 |
+
'rag_documents': 0,
|
587 |
+
'system_version': '2.0.0',
|
588 |
+
'status_check_time': datetime.now().isoformat()
|
589 |
+
}),
|
590 |
+
'components': result.get('components', {})
|
591 |
+
}
|
592 |
+
else:
|
593 |
+
return result
|
594 |
+
except Exception as e:
|
595 |
+
raise HTTPException(status_code=500, detail=str(e))
|
596 |
+
|
597 |
+
# Initialization status endpoint
|
598 |
+
@app.get("/api/init-status")
|
599 |
+
async def get_init_status():
|
600 |
+
"""Check if ResearchMate is initialized"""
|
601 |
+
global research_mate_initialized, initialization_in_progress
|
602 |
+
|
603 |
+
if research_mate_initialized:
|
604 |
+
status = "ready"
|
605 |
+
elif initialization_in_progress:
|
606 |
+
status = "initializing"
|
607 |
+
else:
|
608 |
+
status = "not_started"
|
609 |
+
|
610 |
+
return {
|
611 |
+
"initialized": research_mate_initialized,
|
612 |
+
"in_progress": initialization_in_progress,
|
613 |
+
"timestamp": datetime.now().isoformat(),
|
614 |
+
"status": status
|
615 |
+
}
|
616 |
+
|
617 |
+
# Fast search endpoint that initializes on first call
|
618 |
+
@app.post("/api/search-fast")
|
619 |
+
async def search_papers_fast(query: SearchQuery, current_user: dict = Depends(get_current_user_dependency)):
|
620 |
+
"""Fast search that shows initialization progress"""
|
621 |
+
try:
|
622 |
+
global research_mate
|
623 |
+
if research_mate is None:
|
624 |
+
# Return immediate response indicating initialization
|
625 |
+
return {
|
626 |
+
"initializing": True,
|
627 |
+
"message": "ResearchMate is initializing (this may take 30-60 seconds)...",
|
628 |
+
"query": query.query,
|
629 |
+
"estimated_time": "30-60 seconds"
|
630 |
+
}
|
631 |
+
|
632 |
+
# Use existing search
|
633 |
+
result = research_mate.search(query.query, query.max_results)
|
634 |
+
if not result.get("success"):
|
635 |
+
raise HTTPException(status_code=400, detail=result.get("error", "Search failed"))
|
636 |
+
|
637 |
+
papers = result.get("papers", [])
|
638 |
+
if papers and citation_analyzer is not None:
|
639 |
+
citation_analyzer.add_papers(papers)
|
640 |
+
|
641 |
+
return result
|
642 |
+
except Exception as e:
|
643 |
+
raise HTTPException(status_code=500, detail=str(e))
|
644 |
+
|
645 |
+
@app.get("/api/user/status")
|
646 |
+
async def get_user_status(current_user: dict = Depends(get_current_user_dependency)):
|
647 |
+
"""Get current user's status and statistics"""
|
648 |
+
if research_mate is None:
|
649 |
+
raise HTTPException(status_code=503, detail="ResearchMate not initialized")
|
650 |
+
|
651 |
+
try:
|
652 |
+
user_id = current_user.get("user_id")
|
653 |
+
|
654 |
+
# Get user's projects
|
655 |
+
projects_result = research_mate.list_projects(user_id)
|
656 |
+
if not projects_result.get("success"):
|
657 |
+
raise HTTPException(status_code=400, detail="Failed to get user projects")
|
658 |
+
|
659 |
+
user_projects = projects_result.get("projects", [])
|
660 |
+
total_papers = sum(len(p.get('papers', [])) for p in user_projects)
|
661 |
+
|
662 |
+
return {
|
663 |
+
"success": True,
|
664 |
+
"user_id": user_id,
|
665 |
+
"username": current_user.get("username"),
|
666 |
+
"statistics": {
|
667 |
+
"total_projects": len(user_projects),
|
668 |
+
"total_papers": total_papers,
|
669 |
+
"active_projects": len([p for p in user_projects if p.get('status') == 'active'])
|
670 |
+
},
|
671 |
+
"last_updated": datetime.now().isoformat()
|
672 |
+
}
|
673 |
+
except Exception as e:
|
674 |
+
raise HTTPException(status_code=500, detail=str(e))
|
675 |
+
|
676 |
+
# Trigger initialization endpoint (for testing)
|
677 |
+
@app.post("/api/trigger-init")
|
678 |
+
async def trigger_initialization():
|
679 |
+
"""Manually trigger ResearchMate initialization"""
|
680 |
+
if not initialization_in_progress and not research_mate_initialized:
|
681 |
+
asyncio.create_task(initialize_research_mate())
|
682 |
+
return {"message": "Initialization triggered"}
|
683 |
+
elif initialization_in_progress:
|
684 |
+
return {"message": "Initialization already in progress"}
|
685 |
+
else:
|
686 |
+
return {"message": "Already initialized"}
|
687 |
+
|
688 |
+
# Health check endpoint
|
689 |
+
@app.get("/api/health")
|
690 |
+
async def health_check():
|
691 |
+
"""Health check endpoint"""
|
692 |
+
return {"status": "ok", "timestamp": datetime.now().isoformat()}
|
693 |
+
|
694 |
+
# Update the existing FastAPI app to use lifespan
|
695 |
+
app.router.lifespan_context = lifespan
|
696 |
+
|
697 |
+
# Startup event to ensure initialization begins immediately after server starts
|
698 |
+
@app.on_event("startup")
|
699 |
+
async def startup_event():
|
700 |
+
"""Ensure initialization starts on startup"""
|
701 |
+
print("🌟 Server started, ensuring ResearchMate initialization begins...")
|
702 |
+
# Give the server a moment to fully start, then trigger initialization
|
703 |
+
await asyncio.sleep(1)
|
704 |
+
if not initialization_in_progress and not research_mate_initialized:
|
705 |
+
asyncio.create_task(initialize_research_mate())
|
706 |
+
|
707 |
+
# Run the application
|
708 |
+
if __name__ == "__main__":
|
709 |
+
import os
|
710 |
+
|
711 |
+
# Hugging Face Spaces uses port 7860
|
712 |
+
port = int(os.environ.get('PORT', 7860))
|
713 |
+
host = "0.0.0.0"
|
714 |
+
|
715 |
+
print("Starting ResearchMate on Hugging Face Spaces...")
|
716 |
+
print(f"Web Interface: http://0.0.0.0:{port}")
|
717 |
+
print(f"API Documentation: http://0.0.0.0:{port}/docs")
|
718 |
+
|
719 |
+
uvicorn.run(
|
720 |
+
"main:app",
|
721 |
+
host=host,
|
722 |
+
port=port,
|
723 |
+
log_level="info"
|
724 |
+
)
|
projects.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
src/components/__init__.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
ResearchMate Components Package
|
3 |
+
Modular Python components for the AI research assistant
|
4 |
+
"""
|
5 |
+
|
6 |
+
from .config import Config
|
7 |
+
from .groq_processor import GroqProcessor, GroqLlamaLLM
|
8 |
+
from .rag_system import RAGSystem
|
9 |
+
from .unified_fetcher import ArxivFetcher, PaperFetcher, UnifiedFetcher
|
10 |
+
from .pdf_processor import PDFProcessor
|
11 |
+
from .research_assistant import SimpleResearchAssistant, ResearchMate
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
'Config',
|
15 |
+
'GroqProcessor',
|
16 |
+
'GroqLlamaLLM',
|
17 |
+
'RAGSystem',
|
18 |
+
'ArxivFetcher',
|
19 |
+
'PaperFetcher',
|
20 |
+
'UnifiedFetcher',
|
21 |
+
'PDFProcessor',
|
22 |
+
'SimpleResearchAssistant',
|
23 |
+
'ResearchMate'
|
24 |
+
]
|
25 |
+
|
26 |
+
__version__ = "2.0.0"
|
src/components/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (895 Bytes). View file
|
|
src/components/__pycache__/__init__.cpython-313.pyc
ADDED
Binary file (700 Bytes). View file
|
|
src/components/__pycache__/arxiv_fetcher.cpython-311.pyc
ADDED
Binary file (17.7 kB). View file
|
|
src/components/__pycache__/auth.cpython-311.pyc
ADDED
Binary file (15.7 kB). View file
|
|
src/components/__pycache__/citation_network.cpython-311.pyc
ADDED
Binary file (17.2 kB). View file
|
|
src/components/__pycache__/config.cpython-311.pyc
ADDED
Binary file (7.14 kB). View file
|
|
src/components/__pycache__/config.cpython-313.pyc
ADDED
Binary file (7.04 kB). View file
|
|
src/components/__pycache__/groq_processor.cpython-311.pyc
ADDED
Binary file (18.5 kB). View file
|
|
src/components/__pycache__/groq_processor.cpython-313.pyc
ADDED
Binary file (16 kB). View file
|
|
src/components/__pycache__/pdf_processor.cpython-311.pyc
ADDED
Binary file (21 kB). View file
|
|
src/components/__pycache__/rag_system.cpython-311.pyc
ADDED
Binary file (20.9 kB). View file
|
|
src/components/__pycache__/research_assistant.cpython-311.pyc
ADDED
Binary file (41.1 kB). View file
|
|
src/components/__pycache__/trend_monitor.cpython-311.pyc
ADDED
Binary file (29.6 kB). View file
|
|
src/components/__pycache__/unified_fetcher.cpython-311.pyc
ADDED
Binary file (43.8 kB). View file
|
|
src/components/arxiv_fetcher.py
ADDED
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
ArXiv Fetcher Component
|
3 |
+
Fetches and processes research papers from ArXiv
|
4 |
+
"""
|
5 |
+
|
6 |
+
import re
|
7 |
+
import time
|
8 |
+
import requests
|
9 |
+
from typing import List, Dict, Optional, Any
|
10 |
+
from datetime import datetime, timedelta
|
11 |
+
import arxiv
|
12 |
+
|
13 |
+
|
14 |
+
class ArxivFetcher:
|
15 |
+
"""
|
16 |
+
Fetches research papers from ArXiv
|
17 |
+
Provides search, download, and metadata extraction capabilities
|
18 |
+
"""
|
19 |
+
|
20 |
+
def __init__(self, config = None):
|
21 |
+
# Import Config only when needed to avoid dependency issues
|
22 |
+
if config is None:
|
23 |
+
try:
|
24 |
+
from .config import Config
|
25 |
+
self.config = Config()
|
26 |
+
except ImportError:
|
27 |
+
# Fallback to None if Config cannot be imported
|
28 |
+
self.config = None
|
29 |
+
else:
|
30 |
+
self.config = config
|
31 |
+
self.client = arxiv.Client()
|
32 |
+
|
33 |
+
def search_papers(self,
|
34 |
+
query: str,
|
35 |
+
max_results: int = 10,
|
36 |
+
sort_by: str = "relevance",
|
37 |
+
category: str = None,
|
38 |
+
date_range: int = None) -> List[Dict[str, Any]]:
|
39 |
+
"""
|
40 |
+
Search for papers on ArXiv
|
41 |
+
|
42 |
+
Args:
|
43 |
+
query: Search query
|
44 |
+
max_results: Maximum number of results
|
45 |
+
sort_by: Sort criteria ('relevance', 'lastUpdatedDate', 'submittedDate')
|
46 |
+
category: ArXiv category filter (e.g., 'cs.AI', 'cs.LG')
|
47 |
+
date_range: Days back to search (e.g., 7, 30, 365)
|
48 |
+
|
49 |
+
Returns:
|
50 |
+
List of paper dictionaries
|
51 |
+
"""
|
52 |
+
try:
|
53 |
+
print(f"Searching ArXiv for: '{query}'")
|
54 |
+
|
55 |
+
# Build search query
|
56 |
+
search_query = query
|
57 |
+
if category:
|
58 |
+
search_query = f"cat:{category} AND {query}"
|
59 |
+
|
60 |
+
# Set sort criteria
|
61 |
+
sort_criteria = {
|
62 |
+
"relevance": arxiv.SortCriterion.Relevance,
|
63 |
+
"lastUpdatedDate": arxiv.SortCriterion.LastUpdatedDate,
|
64 |
+
"submittedDate": arxiv.SortCriterion.SubmittedDate
|
65 |
+
}.get(sort_by, arxiv.SortCriterion.Relevance)
|
66 |
+
|
67 |
+
# Create search
|
68 |
+
search = arxiv.Search(
|
69 |
+
query=search_query,
|
70 |
+
max_results=max_results,
|
71 |
+
sort_by=sort_criteria,
|
72 |
+
sort_order=arxiv.SortOrder.Descending
|
73 |
+
)
|
74 |
+
|
75 |
+
papers = []
|
76 |
+
for result in self.client.results(search):
|
77 |
+
# Date filtering
|
78 |
+
if date_range:
|
79 |
+
cutoff_date = datetime.now() - timedelta(days=date_range)
|
80 |
+
if result.published.replace(tzinfo=None) < cutoff_date:
|
81 |
+
continue
|
82 |
+
|
83 |
+
# Extract paper information
|
84 |
+
paper = self._extract_paper_info(result)
|
85 |
+
papers.append(paper)
|
86 |
+
|
87 |
+
print(f"Found {len(papers)} papers")
|
88 |
+
return papers
|
89 |
+
|
90 |
+
except Exception as e:
|
91 |
+
print(f"Error searching ArXiv: {e}")
|
92 |
+
return []
|
93 |
+
|
94 |
+
def get_paper_by_id(self, arxiv_id: str) -> Optional[Dict[str, Any]]:
|
95 |
+
"""
|
96 |
+
Get a specific paper by ArXiv ID
|
97 |
+
|
98 |
+
Args:
|
99 |
+
arxiv_id: ArXiv paper ID (e.g., '2301.12345')
|
100 |
+
|
101 |
+
Returns:
|
102 |
+
Paper dictionary or None
|
103 |
+
"""
|
104 |
+
try:
|
105 |
+
print(f"Fetching paper: {arxiv_id}")
|
106 |
+
|
107 |
+
search = arxiv.Search(id_list=[arxiv_id])
|
108 |
+
results = list(self.client.results(search))
|
109 |
+
|
110 |
+
if results:
|
111 |
+
paper = self._extract_paper_info(results[0])
|
112 |
+
print(f"Retrieved paper: {paper['title']}")
|
113 |
+
return paper
|
114 |
+
else:
|
115 |
+
print(f"Paper not found: {arxiv_id}")
|
116 |
+
return None
|
117 |
+
|
118 |
+
except Exception as e:
|
119 |
+
print(f"Error fetching paper {arxiv_id}: {e}")
|
120 |
+
return None
|
121 |
+
|
122 |
+
def search_by_author(self, author: str, max_results: int = 20) -> List[Dict[str, Any]]:
|
123 |
+
"""
|
124 |
+
Search for papers by author
|
125 |
+
|
126 |
+
Args:
|
127 |
+
author: Author name
|
128 |
+
max_results: Maximum number of results
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
List of paper dictionaries
|
132 |
+
"""
|
133 |
+
query = f"au:{author}"
|
134 |
+
return self.search_papers(query, max_results=max_results, sort_by="lastUpdatedDate")
|
135 |
+
|
136 |
+
def search_by_category(self, category: str, max_results: int = 20) -> List[Dict[str, Any]]:
|
137 |
+
"""
|
138 |
+
Search for papers by category
|
139 |
+
|
140 |
+
Args:
|
141 |
+
category: ArXiv category (e.g., 'cs.AI', 'cs.LG', 'stat.ML')
|
142 |
+
max_results: Maximum number of results
|
143 |
+
|
144 |
+
Returns:
|
145 |
+
List of paper dictionaries
|
146 |
+
"""
|
147 |
+
query = f"cat:{category}"
|
148 |
+
return self.search_papers(query, max_results=max_results, sort_by="lastUpdatedDate")
|
149 |
+
|
150 |
+
def get_trending_papers(self, category: str = "cs.AI", days: int = 7, max_results: int = 10) -> List[Dict[str, Any]]:
|
151 |
+
"""
|
152 |
+
Get trending papers in a category
|
153 |
+
|
154 |
+
Args:
|
155 |
+
category: ArXiv category
|
156 |
+
days: Days back to look for papers
|
157 |
+
max_results: Maximum number of results
|
158 |
+
|
159 |
+
Returns:
|
160 |
+
List of paper dictionaries
|
161 |
+
"""
|
162 |
+
return self.search_by_category(category, max_results=max_results)
|
163 |
+
|
164 |
+
def _extract_paper_info(self, result) -> Dict[str, Any]:
|
165 |
+
"""
|
166 |
+
Extract paper information from ArXiv result
|
167 |
+
|
168 |
+
Args:
|
169 |
+
result: ArXiv search result
|
170 |
+
|
171 |
+
Returns:
|
172 |
+
Paper dictionary
|
173 |
+
"""
|
174 |
+
try:
|
175 |
+
# Extract ArXiv ID
|
176 |
+
arxiv_id = result.entry_id.split('/')[-1]
|
177 |
+
|
178 |
+
# Clean and format data
|
179 |
+
paper = {
|
180 |
+
'arxiv_id': arxiv_id,
|
181 |
+
'title': result.title.strip(),
|
182 |
+
'authors': [author.name for author in result.authors],
|
183 |
+
'summary': result.summary.strip(),
|
184 |
+
'published': result.published.isoformat(),
|
185 |
+
'updated': result.updated.isoformat(),
|
186 |
+
'categories': result.categories,
|
187 |
+
'primary_category': result.primary_category,
|
188 |
+
'pdf_url': result.pdf_url,
|
189 |
+
'entry_id': result.entry_id,
|
190 |
+
'journal_ref': result.journal_ref,
|
191 |
+
'doi': result.doi,
|
192 |
+
'comment': result.comment,
|
193 |
+
'links': [{'title': link.title, 'href': link.href} for link in result.links],
|
194 |
+
'fetched_at': datetime.now().isoformat()
|
195 |
+
}
|
196 |
+
|
197 |
+
# Add formatted metadata
|
198 |
+
paper['authors_str'] = ', '.join(paper['authors'][:3]) + ('...' if len(paper['authors']) > 3 else '')
|
199 |
+
paper['categories_str'] = ', '.join(paper['categories'][:3]) + ('...' if len(paper['categories']) > 3 else '')
|
200 |
+
paper['year'] = result.published.year
|
201 |
+
paper['month'] = result.published.month
|
202 |
+
|
203 |
+
return paper
|
204 |
+
|
205 |
+
except Exception as e:
|
206 |
+
print(f"Error extracting paper info: {e}")
|
207 |
+
return {
|
208 |
+
'arxiv_id': 'unknown',
|
209 |
+
'title': 'Error extracting title',
|
210 |
+
'authors': [],
|
211 |
+
'summary': 'Error extracting summary',
|
212 |
+
'error': str(e)
|
213 |
+
}
|
214 |
+
|
215 |
+
def download_pdf(self, paper: Dict[str, Any], download_dir: str = "downloads") -> Optional[str]:
|
216 |
+
"""
|
217 |
+
Download PDF for a paper
|
218 |
+
|
219 |
+
Args:
|
220 |
+
paper: Paper dictionary
|
221 |
+
download_dir: Directory to save PDF
|
222 |
+
|
223 |
+
Returns:
|
224 |
+
Path to downloaded PDF or None
|
225 |
+
"""
|
226 |
+
try:
|
227 |
+
import os
|
228 |
+
os.makedirs(download_dir, exist_ok=True)
|
229 |
+
|
230 |
+
pdf_url = paper.get('pdf_url')
|
231 |
+
if not pdf_url:
|
232 |
+
print(f"No PDF URL for paper: {paper.get('title', 'Unknown')}")
|
233 |
+
return None
|
234 |
+
|
235 |
+
arxiv_id = paper.get('arxiv_id', 'unknown')
|
236 |
+
filename = f"{arxiv_id}.pdf"
|
237 |
+
filepath = os.path.join(download_dir, filename)
|
238 |
+
|
239 |
+
if os.path.exists(filepath):
|
240 |
+
print(f"PDF already exists: {filepath}")
|
241 |
+
return filepath
|
242 |
+
|
243 |
+
print(f"Downloading PDF: {paper.get('title', 'Unknown')}")
|
244 |
+
|
245 |
+
response = requests.get(pdf_url, timeout=30)
|
246 |
+
response.raise_for_status()
|
247 |
+
|
248 |
+
with open(filepath, 'wb') as f:
|
249 |
+
f.write(response.content)
|
250 |
+
|
251 |
+
print(f"PDF downloaded: {filepath}")
|
252 |
+
return filepath
|
253 |
+
|
254 |
+
except Exception as e:
|
255 |
+
print(f"Error downloading PDF: {e}")
|
256 |
+
return None
|
257 |
+
|
258 |
+
def get_paper_recommendations(self, paper_id: str, max_results: int = 5) -> List[Dict[str, Any]]:
|
259 |
+
"""
|
260 |
+
Get paper recommendations based on a paper's content
|
261 |
+
|
262 |
+
Args:
|
263 |
+
paper_id: ArXiv ID of the base paper
|
264 |
+
max_results: Number of recommendations
|
265 |
+
|
266 |
+
Returns:
|
267 |
+
List of recommended papers
|
268 |
+
"""
|
269 |
+
try:
|
270 |
+
# Get the base paper
|
271 |
+
base_paper = self.get_paper_by_id(paper_id)
|
272 |
+
if not base_paper:
|
273 |
+
return []
|
274 |
+
|
275 |
+
# Extract key terms from title and summary
|
276 |
+
title = base_paper.get('title', '')
|
277 |
+
summary = base_paper.get('summary', '')
|
278 |
+
categories = base_paper.get('categories', [])
|
279 |
+
|
280 |
+
# Simple keyword extraction (can be improved with NLP)
|
281 |
+
keywords = self._extract_keywords(title + ' ' + summary)
|
282 |
+
|
283 |
+
# Search for related papers
|
284 |
+
query = ' '.join(keywords[:5]) # Use top 5 keywords
|
285 |
+
|
286 |
+
related_papers = self.search_papers(
|
287 |
+
query=query,
|
288 |
+
max_results=max_results + 5, # Get more to filter out the original
|
289 |
+
sort_by="relevance"
|
290 |
+
)
|
291 |
+
|
292 |
+
# Filter out the original paper
|
293 |
+
recommendations = [p for p in related_papers if p.get('arxiv_id') != paper_id]
|
294 |
+
|
295 |
+
return recommendations[:max_results]
|
296 |
+
|
297 |
+
except Exception as e:
|
298 |
+
print(f"Error getting recommendations: {e}")
|
299 |
+
return []
|
300 |
+
|
301 |
+
def _extract_keywords(self, text: str) -> List[str]:
|
302 |
+
"""
|
303 |
+
Simple keyword extraction from text
|
304 |
+
|
305 |
+
Args:
|
306 |
+
text: Input text
|
307 |
+
|
308 |
+
Returns:
|
309 |
+
List of keywords
|
310 |
+
"""
|
311 |
+
# Simple implementation - can be improved with NLP libraries
|
312 |
+
import re
|
313 |
+
from collections import Counter
|
314 |
+
|
315 |
+
# Remove common stop words
|
316 |
+
stop_words = {'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'a', 'an', 'as', 'is', 'was', 'are', 'were', 'be', 'been', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those', 'we', 'us', 'our', 'you', 'your', 'he', 'him', 'his', 'she', 'her', 'it', 'its', 'they', 'them', 'their'}
|
317 |
+
|
318 |
+
# Extract words
|
319 |
+
words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower())
|
320 |
+
|
321 |
+
# Filter and count
|
322 |
+
filtered_words = [word for word in words if word not in stop_words]
|
323 |
+
word_counts = Counter(filtered_words)
|
324 |
+
|
325 |
+
# Return most common words
|
326 |
+
return [word for word, count in word_counts.most_common(20)]
|
327 |
+
|
328 |
+
def get_categories(self) -> Dict[str, str]:
|
329 |
+
"""
|
330 |
+
Get available ArXiv categories
|
331 |
+
|
332 |
+
Returns:
|
333 |
+
Dictionary of category codes and descriptions
|
334 |
+
"""
|
335 |
+
return {
|
336 |
+
'cs.AI': 'Artificial Intelligence',
|
337 |
+
'cs.LG': 'Machine Learning',
|
338 |
+
'cs.CV': 'Computer Vision',
|
339 |
+
'cs.CL': 'Computation and Language',
|
340 |
+
'cs.NE': 'Neural and Evolutionary Computing',
|
341 |
+
'cs.RO': 'Robotics',
|
342 |
+
'cs.CR': 'Cryptography and Security',
|
343 |
+
'cs.DC': 'Distributed, Parallel, and Cluster Computing',
|
344 |
+
'cs.DB': 'Databases',
|
345 |
+
'cs.DS': 'Data Structures and Algorithms',
|
346 |
+
'cs.HC': 'Human-Computer Interaction',
|
347 |
+
'cs.IR': 'Information Retrieval',
|
348 |
+
'cs.IT': 'Information Theory',
|
349 |
+
'cs.MM': 'Multimedia',
|
350 |
+
'cs.NI': 'Networking and Internet Architecture',
|
351 |
+
'cs.OS': 'Operating Systems',
|
352 |
+
'cs.PL': 'Programming Languages',
|
353 |
+
'cs.SE': 'Software Engineering',
|
354 |
+
'cs.SY': 'Systems and Control',
|
355 |
+
'stat.ML': 'Machine Learning (Statistics)',
|
356 |
+
'stat.AP': 'Applications (Statistics)',
|
357 |
+
'stat.CO': 'Computation (Statistics)',
|
358 |
+
'stat.ME': 'Methodology (Statistics)',
|
359 |
+
'stat.TH': 'Statistics Theory',
|
360 |
+
'math.ST': 'Statistics Theory (Mathematics)',
|
361 |
+
'math.PR': 'Probability (Mathematics)',
|
362 |
+
'math.OC': 'Optimization and Control',
|
363 |
+
'math.NA': 'Numerical Analysis',
|
364 |
+
'eess.AS': 'Audio and Speech Processing',
|
365 |
+
'eess.IV': 'Image and Video Processing',
|
366 |
+
'eess.SP': 'Signal Processing',
|
367 |
+
'eess.SY': 'Systems and Control',
|
368 |
+
'q-bio.QM': 'Quantitative Methods',
|
369 |
+
'q-bio.NC': 'Neurons and Cognition',
|
370 |
+
'physics.data-an': 'Data Analysis, Statistics and Probability'
|
371 |
+
}
|
src/components/auth.py
ADDED
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Authentication and authorization utilities
|
3 |
+
"""
|
4 |
+
|
5 |
+
import jwt
|
6 |
+
import bcrypt
|
7 |
+
import json
|
8 |
+
import os
|
9 |
+
from datetime import datetime, timedelta
|
10 |
+
from typing import Optional, Dict, Any
|
11 |
+
from functools import wraps
|
12 |
+
|
13 |
+
# Import Flask components only when available
|
14 |
+
try:
|
15 |
+
from flask import request, jsonify, session, redirect, url_for
|
16 |
+
FLASK_AVAILABLE = True
|
17 |
+
except ImportError:
|
18 |
+
FLASK_AVAILABLE = False
|
19 |
+
request = None
|
20 |
+
jsonify = None
|
21 |
+
session = None
|
22 |
+
redirect = None
|
23 |
+
url_for = None
|
24 |
+
|
25 |
+
class AuthManager:
|
26 |
+
def __init__(self, secret_key: str = None):
|
27 |
+
self.secret_key = secret_key or os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
|
28 |
+
self.users_file = 'data/users.json'
|
29 |
+
self.active_sessions = {} # Track active sessions for security
|
30 |
+
self.session_file = 'data/active_sessions.json'
|
31 |
+
self.ensure_users_file()
|
32 |
+
|
33 |
+
def ensure_users_file(self):
|
34 |
+
"""Ensure users file exists"""
|
35 |
+
os.makedirs('data', exist_ok=True)
|
36 |
+
if not os.path.exists(self.users_file):
|
37 |
+
with open(self.users_file, 'w') as f:
|
38 |
+
json.dump({}, f)
|
39 |
+
|
40 |
+
def hash_password(self, password: str) -> str:
|
41 |
+
"""Hash password with bcrypt"""
|
42 |
+
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
43 |
+
|
44 |
+
def verify_password(self, password: str, hashed: str) -> bool:
|
45 |
+
"""Verify password against hash"""
|
46 |
+
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
|
47 |
+
|
48 |
+
def load_users(self) -> Dict[str, Any]:
|
49 |
+
"""Load users from file"""
|
50 |
+
try:
|
51 |
+
with open(self.users_file, 'r') as f:
|
52 |
+
return json.load(f)
|
53 |
+
except:
|
54 |
+
return {}
|
55 |
+
|
56 |
+
def save_users(self, users: Dict[str, Any]):
|
57 |
+
"""Save users to file"""
|
58 |
+
with open(self.users_file, 'w') as f:
|
59 |
+
json.dump(users, f, indent=2)
|
60 |
+
|
61 |
+
def create_user(self, username: str, email: str, password: str) -> Dict[str, Any]:
|
62 |
+
"""Create a new user"""
|
63 |
+
users = self.load_users()
|
64 |
+
|
65 |
+
if username in users:
|
66 |
+
return {'success': False, 'error': 'Username already exists'}
|
67 |
+
|
68 |
+
# Check if email already exists
|
69 |
+
for user_data in users.values():
|
70 |
+
if user_data.get('email') == email:
|
71 |
+
return {'success': False, 'error': 'Email already registered'}
|
72 |
+
|
73 |
+
# Create user
|
74 |
+
user_id = f"user_{len(users) + 1}"
|
75 |
+
users[username] = {
|
76 |
+
'user_id': user_id,
|
77 |
+
'email': email,
|
78 |
+
'password_hash': self.hash_password(password),
|
79 |
+
'created_at': datetime.now().isoformat(),
|
80 |
+
'is_active': True
|
81 |
+
}
|
82 |
+
|
83 |
+
self.save_users(users)
|
84 |
+
return {'success': True, 'user_id': user_id}
|
85 |
+
|
86 |
+
def authenticate_user(self, username: str, password: str) -> Dict[str, Any]:
|
87 |
+
"""Authenticate user credentials"""
|
88 |
+
users = self.load_users()
|
89 |
+
|
90 |
+
if username not in users:
|
91 |
+
return {'success': False, 'error': 'Invalid username or password'}
|
92 |
+
|
93 |
+
user = users[username]
|
94 |
+
if not self.verify_password(password, user['password_hash']):
|
95 |
+
return {'success': False, 'error': 'Invalid username or password'}
|
96 |
+
|
97 |
+
if not user.get('is_active', True):
|
98 |
+
return {'success': False, 'error': 'Account is disabled'}
|
99 |
+
|
100 |
+
# Generate JWT token with shorter expiration for security
|
101 |
+
token = jwt.encode({
|
102 |
+
'user_id': user['user_id'],
|
103 |
+
'username': username,
|
104 |
+
'exp': datetime.utcnow() + timedelta(hours=8) # 8 hours instead of 7 days
|
105 |
+
}, self.secret_key, algorithm='HS256')
|
106 |
+
|
107 |
+
# Track active session
|
108 |
+
self.add_active_session(user['user_id'], token)
|
109 |
+
|
110 |
+
return {
|
111 |
+
'success': True,
|
112 |
+
'token': token,
|
113 |
+
'user_id': user['user_id'],
|
114 |
+
'username': username
|
115 |
+
}
|
116 |
+
|
117 |
+
def verify_token(self, token: str) -> Optional[Dict[str, Any]]:
|
118 |
+
"""Verify JWT token and check active session"""
|
119 |
+
try:
|
120 |
+
payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
|
121 |
+
user_id = payload.get('user_id')
|
122 |
+
|
123 |
+
# Check if session is still active
|
124 |
+
if not self.is_session_active(user_id, token):
|
125 |
+
return None
|
126 |
+
|
127 |
+
# Update session activity
|
128 |
+
self.update_session_activity(user_id)
|
129 |
+
|
130 |
+
return payload
|
131 |
+
except jwt.ExpiredSignatureError:
|
132 |
+
return None
|
133 |
+
except jwt.InvalidTokenError:
|
134 |
+
return None
|
135 |
+
|
136 |
+
def get_current_user(self, request_obj) -> Optional[Dict[str, Any]]:
|
137 |
+
"""Get current user from request"""
|
138 |
+
if not FLASK_AVAILABLE or not request_obj:
|
139 |
+
return None
|
140 |
+
|
141 |
+
# Try Authorization header first
|
142 |
+
auth_header = request_obj.headers.get('Authorization')
|
143 |
+
if auth_header and auth_header.startswith('Bearer '):
|
144 |
+
token = auth_header.split(' ')[1]
|
145 |
+
return self.verify_token(token)
|
146 |
+
|
147 |
+
# Try session
|
148 |
+
if session:
|
149 |
+
token = session.get('auth_token')
|
150 |
+
if token:
|
151 |
+
return self.verify_token(token)
|
152 |
+
|
153 |
+
return None
|
154 |
+
|
155 |
+
def create_default_admin(self) -> Dict[str, Any]:
|
156 |
+
"""Create default admin user if it doesn't exist"""
|
157 |
+
users = self.load_users()
|
158 |
+
|
159 |
+
admin_username = "admin"
|
160 |
+
admin_user_id = "admin_user"
|
161 |
+
|
162 |
+
# Check if admin already exists (by username or user_id)
|
163 |
+
if admin_username in users:
|
164 |
+
return {'success': True, 'message': 'Admin user already exists'}
|
165 |
+
|
166 |
+
# Check if user_id already exists
|
167 |
+
for user_data in users.values():
|
168 |
+
if user_data.get('user_id') == admin_user_id:
|
169 |
+
return {'success': True, 'message': 'Admin user ID already exists'}
|
170 |
+
|
171 |
+
# Create admin user
|
172 |
+
users[admin_username] = {
|
173 |
+
'user_id': admin_user_id,
|
174 |
+
'email': '[email protected]',
|
175 |
+
'password_hash': self.hash_password('admin123'), # Default password
|
176 |
+
'created_at': datetime.now().isoformat(),
|
177 |
+
'is_active': True,
|
178 |
+
'is_admin': True
|
179 |
+
}
|
180 |
+
|
181 |
+
self.save_users(users)
|
182 |
+
return {
|
183 |
+
'success': True,
|
184 |
+
'message': 'Default admin user created',
|
185 |
+
'username': admin_username,
|
186 |
+
'password': 'admin123',
|
187 |
+
'note': 'Please change the default password after first login'
|
188 |
+
}
|
189 |
+
|
190 |
+
def load_active_sessions(self) -> Dict[str, Any]:
|
191 |
+
"""Load active sessions from file"""
|
192 |
+
try:
|
193 |
+
if os.path.exists(self.session_file):
|
194 |
+
with open(self.session_file, 'r') as f:
|
195 |
+
return json.load(f)
|
196 |
+
except:
|
197 |
+
pass
|
198 |
+
return {}
|
199 |
+
|
200 |
+
def save_active_sessions(self, sessions: Dict[str, Any]):
|
201 |
+
"""Save active sessions to file"""
|
202 |
+
try:
|
203 |
+
with open(self.session_file, 'w') as f:
|
204 |
+
json.dump(sessions, f, indent=2)
|
205 |
+
except:
|
206 |
+
pass
|
207 |
+
|
208 |
+
def add_active_session(self, user_id: str, token: str):
|
209 |
+
"""Add an active session"""
|
210 |
+
sessions = self.load_active_sessions()
|
211 |
+
sessions[user_id] = {
|
212 |
+
'token': token,
|
213 |
+
'created_at': datetime.now().isoformat(),
|
214 |
+
'last_activity': datetime.now().isoformat()
|
215 |
+
}
|
216 |
+
self.save_active_sessions(sessions)
|
217 |
+
|
218 |
+
def remove_active_session(self, user_id: str):
|
219 |
+
"""Remove an active session"""
|
220 |
+
sessions = self.load_active_sessions()
|
221 |
+
if user_id in sessions:
|
222 |
+
del sessions[user_id]
|
223 |
+
self.save_active_sessions(sessions)
|
224 |
+
|
225 |
+
def is_session_active(self, user_id: str, token: str) -> bool:
|
226 |
+
"""Check if a session is active"""
|
227 |
+
sessions = self.load_active_sessions()
|
228 |
+
if user_id not in sessions:
|
229 |
+
return False
|
230 |
+
|
231 |
+
session = sessions[user_id]
|
232 |
+
if session.get('token') != token:
|
233 |
+
return False
|
234 |
+
|
235 |
+
# Check if session is expired (8 hours)
|
236 |
+
created_at = datetime.fromisoformat(session['created_at'])
|
237 |
+
if datetime.now() - created_at > timedelta(hours=8):
|
238 |
+
self.remove_active_session(user_id)
|
239 |
+
return False
|
240 |
+
|
241 |
+
return True
|
242 |
+
|
243 |
+
def logout_user(self, user_id: str):
|
244 |
+
"""Logout user and invalidate session"""
|
245 |
+
self.remove_active_session(user_id)
|
246 |
+
return {'success': True, 'message': 'Logged out successfully'}
|
247 |
+
|
248 |
+
def cleanup_expired_sessions(self):
|
249 |
+
"""Clean up expired sessions"""
|
250 |
+
sessions = self.load_active_sessions()
|
251 |
+
current_time = datetime.now()
|
252 |
+
|
253 |
+
expired_sessions = []
|
254 |
+
for user_id, session in sessions.items():
|
255 |
+
created_at = datetime.fromisoformat(session['created_at'])
|
256 |
+
if current_time - created_at > timedelta(hours=8):
|
257 |
+
expired_sessions.append(user_id)
|
258 |
+
|
259 |
+
for user_id in expired_sessions:
|
260 |
+
del sessions[user_id]
|
261 |
+
|
262 |
+
if expired_sessions:
|
263 |
+
self.save_active_sessions(sessions)
|
264 |
+
|
265 |
+
return len(expired_sessions)
|
266 |
+
|
267 |
+
def update_session_activity(self, user_id: str):
|
268 |
+
"""Update last activity time for a session"""
|
269 |
+
sessions = self.load_active_sessions()
|
270 |
+
if user_id in sessions:
|
271 |
+
sessions[user_id]['last_activity'] = datetime.now().isoformat()
|
272 |
+
self.save_active_sessions(sessions)
|
273 |
+
|
274 |
+
# Global auth manager
|
275 |
+
auth_manager = AuthManager()
|
276 |
+
|
277 |
+
def require_auth(f):
|
278 |
+
"""Decorator to require authentication"""
|
279 |
+
@wraps(f)
|
280 |
+
def decorated_function(*args, **kwargs):
|
281 |
+
if not FLASK_AVAILABLE:
|
282 |
+
return f(*args, **kwargs)
|
283 |
+
|
284 |
+
user = auth_manager.get_current_user(request)
|
285 |
+
if not user:
|
286 |
+
if request.is_json:
|
287 |
+
return jsonify({'success': False, 'error': 'Authentication required'}), 401
|
288 |
+
else:
|
289 |
+
return redirect(url_for('login'))
|
290 |
+
return f(*args, **kwargs)
|
291 |
+
return decorated_function
|
292 |
+
|
293 |
+
def get_current_user() -> Optional[Dict[str, Any]]:
|
294 |
+
"""Get current authenticated user"""
|
295 |
+
if not FLASK_AVAILABLE:
|
296 |
+
return None
|
297 |
+
return auth_manager.get_current_user(request)
|
src/components/citation_network.py
ADDED
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
import json
|
3 |
+
from datetime import datetime
|
4 |
+
from typing import List, Dict, Any
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from collections import defaultdict
|
7 |
+
|
8 |
+
class CitationNetworkAnalyzer:
|
9 |
+
"""Analyze citation networks and author collaborations - Web App Version"""
|
10 |
+
|
11 |
+
def __init__(self):
|
12 |
+
self.reset()
|
13 |
+
print("✅ Citation network analyzer initialized (web app version)!")
|
14 |
+
|
15 |
+
def reset(self):
|
16 |
+
"""Reset all data structures"""
|
17 |
+
self.citation_graph = nx.DiGraph()
|
18 |
+
self.author_graph = nx.Graph()
|
19 |
+
self.paper_data = {}
|
20 |
+
self.author_data = {}
|
21 |
+
print("🔄 Citation network analyzer reset")
|
22 |
+
|
23 |
+
def _safe_get_authors(self, paper: Dict) -> List[str]:
|
24 |
+
"""Safely extract and normalize author list from paper"""
|
25 |
+
authors = paper.get('authors', [])
|
26 |
+
|
27 |
+
# Handle None
|
28 |
+
if authors is None:
|
29 |
+
return []
|
30 |
+
|
31 |
+
# Handle string (comma-separated)
|
32 |
+
if isinstance(authors, str):
|
33 |
+
if not authors.strip():
|
34 |
+
return []
|
35 |
+
return [a.strip() for a in authors.split(',') if a.strip()]
|
36 |
+
|
37 |
+
# Handle list
|
38 |
+
if isinstance(authors, list):
|
39 |
+
result = []
|
40 |
+
for author in authors:
|
41 |
+
if isinstance(author, str) and author.strip():
|
42 |
+
result.append(author.strip())
|
43 |
+
elif isinstance(author, dict):
|
44 |
+
# Handle author objects with 'name' field
|
45 |
+
name = author.get('name', '') or author.get('authorId', '')
|
46 |
+
if name and isinstance(name, str):
|
47 |
+
result.append(name.strip())
|
48 |
+
return result
|
49 |
+
|
50 |
+
# Unknown format
|
51 |
+
return []
|
52 |
+
|
53 |
+
def _safe_add_author(self, author_name: str, paper_id: str, citation_count: int = 0):
|
54 |
+
"""Safely add author to the graph"""
|
55 |
+
try:
|
56 |
+
# Initialize author data if not exists
|
57 |
+
if author_name not in self.author_data:
|
58 |
+
self.author_data[author_name] = {
|
59 |
+
'papers': [],
|
60 |
+
'total_citations': 0
|
61 |
+
}
|
62 |
+
|
63 |
+
# Add to NetworkX graph if not exists
|
64 |
+
if not self.author_graph.has_node(author_name):
|
65 |
+
self.author_graph.add_node(author_name)
|
66 |
+
|
67 |
+
# Update author data
|
68 |
+
if paper_id not in self.author_data[author_name]['papers']:
|
69 |
+
self.author_data[author_name]['papers'].append(paper_id)
|
70 |
+
self.author_data[author_name]['total_citations'] += citation_count
|
71 |
+
|
72 |
+
return True
|
73 |
+
|
74 |
+
except Exception as e:
|
75 |
+
print(f"⚠️ Error adding author {author_name}: {e}")
|
76 |
+
return False
|
77 |
+
|
78 |
+
def _safe_add_collaboration(self, author1: str, author2: str, paper_id: str):
|
79 |
+
"""Safely add collaboration edge between authors"""
|
80 |
+
try:
|
81 |
+
# Ensure both authors exist
|
82 |
+
if not self.author_graph.has_node(author1):
|
83 |
+
self.author_graph.add_node(author1)
|
84 |
+
if not self.author_graph.has_node(author2):
|
85 |
+
self.author_graph.add_node(author2)
|
86 |
+
|
87 |
+
# Add or update edge
|
88 |
+
if self.author_graph.has_edge(author1, author2):
|
89 |
+
# Update existing edge
|
90 |
+
edge_data = self.author_graph.edges[author1, author2]
|
91 |
+
edge_data['weight'] = edge_data.get('weight', 0) + 1
|
92 |
+
if 'papers' not in edge_data:
|
93 |
+
edge_data['papers'] = []
|
94 |
+
if paper_id not in edge_data['papers']:
|
95 |
+
edge_data['papers'].append(paper_id)
|
96 |
+
else:
|
97 |
+
# Add new edge
|
98 |
+
self.author_graph.add_edge(author1, author2, weight=1, papers=[paper_id])
|
99 |
+
|
100 |
+
return True
|
101 |
+
|
102 |
+
except Exception as e:
|
103 |
+
print(f"⚠️ Error adding collaboration {author1}-{author2}: {e}")
|
104 |
+
return False
|
105 |
+
|
106 |
+
def add_papers(self, papers: List[Dict]):
|
107 |
+
"""Add papers to the citation network"""
|
108 |
+
if not papers:
|
109 |
+
print("⚠️ No papers provided to add_papers")
|
110 |
+
return
|
111 |
+
|
112 |
+
processed_count = 0
|
113 |
+
error_count = 0
|
114 |
+
|
115 |
+
print(f"📝 Processing {len(papers)} papers...")
|
116 |
+
|
117 |
+
for paper_idx, paper in enumerate(papers):
|
118 |
+
try:
|
119 |
+
# Validate paper input
|
120 |
+
if not isinstance(paper, dict):
|
121 |
+
print(f"⚠️ Paper {paper_idx} is not a dict: {type(paper)}")
|
122 |
+
error_count += 1
|
123 |
+
continue
|
124 |
+
|
125 |
+
# Generate paper ID
|
126 |
+
paper_id = paper.get('paper_id')
|
127 |
+
if not paper_id:
|
128 |
+
paper_id = paper.get('url', '')
|
129 |
+
if not paper_id:
|
130 |
+
title = paper.get('title', f'Unknown_{paper_idx}')
|
131 |
+
paper_id = f"paper_{abs(hash(title)) % 1000000}"
|
132 |
+
|
133 |
+
# Store paper data
|
134 |
+
self.paper_data[paper_id] = {
|
135 |
+
'title': paper.get('title', ''),
|
136 |
+
'authors': self._safe_get_authors(paper),
|
137 |
+
'year': paper.get('year'),
|
138 |
+
'venue': paper.get('venue', ''),
|
139 |
+
'citation_count': paper.get('citation_count', 0),
|
140 |
+
'source': paper.get('source', ''),
|
141 |
+
'url': paper.get('url', ''),
|
142 |
+
'abstract': paper.get('abstract', '')
|
143 |
+
}
|
144 |
+
|
145 |
+
# Add to citation graph
|
146 |
+
self.citation_graph.add_node(paper_id, **self.paper_data[paper_id])
|
147 |
+
|
148 |
+
# Process authors
|
149 |
+
authors = self._safe_get_authors(paper)
|
150 |
+
citation_count = paper.get('citation_count', 0)
|
151 |
+
|
152 |
+
# Validate citation count
|
153 |
+
if not isinstance(citation_count, (int, float)):
|
154 |
+
citation_count = 0
|
155 |
+
|
156 |
+
# Add authors
|
157 |
+
valid_authors = []
|
158 |
+
for author in authors:
|
159 |
+
if self._safe_add_author(author, paper_id, citation_count):
|
160 |
+
valid_authors.append(author)
|
161 |
+
|
162 |
+
# Add collaborations
|
163 |
+
for i, author1 in enumerate(valid_authors):
|
164 |
+
for j, author2 in enumerate(valid_authors):
|
165 |
+
if i < j: # Avoid duplicates and self-loops
|
166 |
+
self._safe_add_collaboration(author1, author2, paper_id)
|
167 |
+
|
168 |
+
processed_count += 1
|
169 |
+
|
170 |
+
except Exception as e:
|
171 |
+
print(f"⚠️ Error processing paper {paper_idx}: {e}")
|
172 |
+
error_count += 1
|
173 |
+
continue
|
174 |
+
|
175 |
+
print(f"✅ Successfully processed {processed_count} papers ({error_count} errors)")
|
176 |
+
|
177 |
+
def analyze_author_network(self) -> Dict:
|
178 |
+
"""Analyze author collaboration network"""
|
179 |
+
try:
|
180 |
+
if len(self.author_graph.nodes) == 0:
|
181 |
+
return {'error': 'No authors in network'}
|
182 |
+
|
183 |
+
# Basic network metrics
|
184 |
+
metrics = {
|
185 |
+
'total_authors': len(self.author_graph.nodes),
|
186 |
+
'total_collaborations': len(self.author_graph.edges),
|
187 |
+
'network_density': nx.density(self.author_graph),
|
188 |
+
'number_of_components': nx.number_connected_components(self.author_graph),
|
189 |
+
'largest_component_size': len(max(nx.connected_components(self.author_graph), key=len)) if nx.number_connected_components(self.author_graph) > 0 else 0
|
190 |
+
}
|
191 |
+
|
192 |
+
# Most collaborative authors
|
193 |
+
collaboration_counts = {node: self.author_graph.degree(node) for node in self.author_graph.nodes}
|
194 |
+
top_collaborators = sorted(collaboration_counts.items(), key=lambda x: x[1], reverse=True)[:10]
|
195 |
+
|
196 |
+
# Most productive authors
|
197 |
+
productivity = {}
|
198 |
+
for author, data in self.author_data.items():
|
199 |
+
productivity[author] = len(data.get('papers', []))
|
200 |
+
top_productive = sorted(productivity.items(), key=lambda x: x[1], reverse=True)[:10]
|
201 |
+
|
202 |
+
# Most cited authors
|
203 |
+
citation_counts = {}
|
204 |
+
for author, data in self.author_data.items():
|
205 |
+
citation_counts[author] = data.get('total_citations', 0)
|
206 |
+
top_cited = sorted(citation_counts.items(), key=lambda x: x[1], reverse=True)[:10]
|
207 |
+
|
208 |
+
return {
|
209 |
+
'network_metrics': metrics,
|
210 |
+
'top_collaborators': top_collaborators,
|
211 |
+
'top_productive_authors': top_productive,
|
212 |
+
'top_cited_authors': top_cited,
|
213 |
+
'analysis_timestamp': datetime.now().isoformat()
|
214 |
+
}
|
215 |
+
|
216 |
+
except Exception as e:
|
217 |
+
return {
|
218 |
+
'error': str(e),
|
219 |
+
'analysis_timestamp': datetime.now().isoformat()
|
220 |
+
}
|
221 |
+
|
222 |
+
def analyze_paper_network(self) -> Dict:
|
223 |
+
"""Analyze paper citation network"""
|
224 |
+
try:
|
225 |
+
if len(self.citation_graph.nodes) == 0:
|
226 |
+
return {'error': 'No papers in network'}
|
227 |
+
|
228 |
+
# Basic network metrics
|
229 |
+
metrics = {
|
230 |
+
'total_papers': len(self.citation_graph.nodes),
|
231 |
+
'total_citations': len(self.citation_graph.edges),
|
232 |
+
'network_density': nx.density(self.citation_graph),
|
233 |
+
'number_of_components': nx.number_weakly_connected_components(self.citation_graph),
|
234 |
+
'largest_component_size': len(max(nx.weakly_connected_components(self.citation_graph), key=len)) if nx.number_weakly_connected_components(self.citation_graph) > 0 else 0
|
235 |
+
}
|
236 |
+
|
237 |
+
# Most cited papers
|
238 |
+
in_degree = dict(self.citation_graph.in_degree())
|
239 |
+
most_cited = sorted(in_degree.items(), key=lambda x: x[1], reverse=True)[:10]
|
240 |
+
|
241 |
+
# Most citing papers
|
242 |
+
out_degree = dict(self.citation_graph.out_degree())
|
243 |
+
most_citing = sorted(out_degree.items(), key=lambda x: x[1], reverse=True)[:10]
|
244 |
+
|
245 |
+
# Convert paper IDs to titles for readability
|
246 |
+
most_cited_titles = []
|
247 |
+
for paper_id, count in most_cited:
|
248 |
+
if paper_id in self.paper_data:
|
249 |
+
most_cited_titles.append((self.paper_data[paper_id]['title'], count))
|
250 |
+
else:
|
251 |
+
most_cited_titles.append((paper_id, count))
|
252 |
+
|
253 |
+
most_citing_titles = []
|
254 |
+
for paper_id, count in most_citing:
|
255 |
+
if paper_id in self.paper_data:
|
256 |
+
most_citing_titles.append((self.paper_data[paper_id]['title'], count))
|
257 |
+
else:
|
258 |
+
most_citing_titles.append((paper_id, count))
|
259 |
+
|
260 |
+
return {
|
261 |
+
'network_metrics': metrics,
|
262 |
+
'most_cited_papers': most_cited_titles,
|
263 |
+
'most_citing_papers': most_citing_titles,
|
264 |
+
'analysis_timestamp': datetime.now().isoformat()
|
265 |
+
}
|
266 |
+
|
267 |
+
except Exception as e:
|
268 |
+
return {
|
269 |
+
'error': str(e),
|
270 |
+
'analysis_timestamp': datetime.now().isoformat()
|
271 |
+
}
|
272 |
+
|
273 |
+
def get_network_summary(self) -> Dict:
|
274 |
+
"""Get comprehensive network summary"""
|
275 |
+
try:
|
276 |
+
author_analysis = self.analyze_author_network()
|
277 |
+
paper_analysis = self.analyze_paper_network()
|
278 |
+
|
279 |
+
return {
|
280 |
+
'author_network': author_analysis,
|
281 |
+
'paper_network': paper_analysis,
|
282 |
+
'overall_stats': {
|
283 |
+
'total_papers': len(self.paper_data),
|
284 |
+
'total_authors': len(self.author_data),
|
285 |
+
'papers_per_author': len(self.paper_data) / max(len(self.author_data), 1),
|
286 |
+
'collaborations_per_author': len(self.author_graph.edges) / max(len(self.author_graph.nodes), 1)
|
287 |
+
},
|
288 |
+
'analysis_timestamp': datetime.now().isoformat()
|
289 |
+
}
|
290 |
+
|
291 |
+
except Exception as e:
|
292 |
+
return {
|
293 |
+
'error': str(e),
|
294 |
+
'analysis_timestamp': datetime.now().isoformat()
|
295 |
+
}
|
src/components/config.py
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Configuration module for ResearchMate
|
3 |
+
Provides backward compatibility with new settings system
|
4 |
+
"""
|
5 |
+
|
6 |
+
import os
|
7 |
+
from pathlib import Path
|
8 |
+
from typing import Optional
|
9 |
+
from ..settings import get_settings
|
10 |
+
|
11 |
+
# Get settings instance
|
12 |
+
settings = get_settings()
|
13 |
+
|
14 |
+
class Config:
|
15 |
+
"""Configuration settings for ResearchMate - Legacy compatibility wrapper"""
|
16 |
+
|
17 |
+
# Application settings
|
18 |
+
APP_NAME: str = "ResearchMate"
|
19 |
+
VERSION: str = "2.0.0"
|
20 |
+
DEBUG: bool = settings.server.debug
|
21 |
+
HOST: str = settings.server.host
|
22 |
+
PORT: int = settings.server.port
|
23 |
+
|
24 |
+
# API Keys
|
25 |
+
GROQ_API_KEY: Optional[str] = settings.get_groq_api_key()
|
26 |
+
|
27 |
+
# Groq Llama 3.3 70B settings
|
28 |
+
LLAMA_MODEL: str = settings.ai_model.model_name
|
29 |
+
MAX_INPUT_TOKENS: int = settings.ai_model.max_tokens
|
30 |
+
MAX_OUTPUT_TOKENS: int = settings.ai_model.max_tokens
|
31 |
+
TEMPERATURE: float = settings.ai_model.temperature
|
32 |
+
TOP_P: float = settings.ai_model.top_p
|
33 |
+
|
34 |
+
# Embeddings and chunking
|
35 |
+
EMBEDDING_MODEL: str = settings.database.embedding_model
|
36 |
+
CHUNK_SIZE: int = settings.search.chunk_size
|
37 |
+
CHUNK_OVERLAP: int = settings.search.chunk_overlap
|
38 |
+
|
39 |
+
# Database settings
|
40 |
+
BASE_DIR: Path = Path(__file__).parent.parent.parent
|
41 |
+
CHROMA_DB_PATH: str = str(BASE_DIR / "chroma_db")
|
42 |
+
COLLECTION_NAME: str = settings.database.collection_name
|
43 |
+
PERSIST_DIRECTORY: str = str(BASE_DIR / settings.database.chroma_persist_dir.lstrip('./')) # Make absolute
|
44 |
+
|
45 |
+
# Upload settings
|
46 |
+
UPLOAD_DIRECTORY: str = settings.get_upload_dir()
|
47 |
+
MAX_FILE_SIZE: int = settings.upload.max_file_size
|
48 |
+
ALLOWED_EXTENSIONS: set = set(ext.lstrip('.') for ext in settings.upload.allowed_extensions)
|
49 |
+
|
50 |
+
# Search settings
|
51 |
+
TOP_K_SIMILAR: int = settings.search.max_results
|
52 |
+
MAX_PAPER_LENGTH: int = 100000 # Keep existing default
|
53 |
+
MAX_SUMMARY_LENGTH: int = 2000 # Keep existing default
|
54 |
+
|
55 |
+
# Rate limiting
|
56 |
+
RATE_LIMIT_ENABLED: bool = os.getenv("RATE_LIMIT_ENABLED", "true").lower() == "true"
|
57 |
+
RATE_LIMIT_REQUESTS: int = int(os.getenv("RATE_LIMIT_REQUESTS", "100"))
|
58 |
+
RATE_LIMIT_WINDOW: int = int(os.getenv("RATE_LIMIT_WINDOW", "3600"))
|
59 |
+
|
60 |
+
# Security
|
61 |
+
SECRET_KEY: str = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
|
62 |
+
ALLOWED_HOSTS: list = os.getenv("ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")
|
63 |
+
|
64 |
+
# Logging
|
65 |
+
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
66 |
+
LOG_FILE: str = os.getenv("LOG_FILE", str(BASE_DIR / "logs" / "app.log"))
|
67 |
+
|
68 |
+
# External APIs
|
69 |
+
ARXIV_API_BASE_URL: str = os.getenv("ARXIV_API_BASE_URL", "http://export.arxiv.org/api/query")
|
70 |
+
SEMANTIC_SCHOLAR_API_URL: str = os.getenv("SEMANTIC_SCHOLAR_API_URL", "https://api.semanticscholar.org/graph/v1/paper/search")
|
71 |
+
SEMANTIC_SCHOLAR_API_KEY: Optional[str] = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
|
72 |
+
|
73 |
+
@classmethod
|
74 |
+
def create_directories(cls):
|
75 |
+
"""Create necessary directories"""
|
76 |
+
directories = [
|
77 |
+
cls.CHROMA_DB_PATH,
|
78 |
+
cls.PERSIST_DIRECTORY,
|
79 |
+
cls.UPLOAD_DIRECTORY,
|
80 |
+
str(Path(cls.LOG_FILE).parent)
|
81 |
+
]
|
82 |
+
|
83 |
+
for directory in directories:
|
84 |
+
Path(directory).mkdir(parents=True, exist_ok=True)
|
85 |
+
|
86 |
+
@classmethod
|
87 |
+
def validate_config(cls):
|
88 |
+
"""Validate configuration settings"""
|
89 |
+
if not cls.GROQ_API_KEY:
|
90 |
+
raise ValueError("GROQ_API_KEY environment variable is required")
|
91 |
+
|
92 |
+
if cls.MAX_FILE_SIZE > 50 * 1024 * 1024: # 50MB limit
|
93 |
+
raise ValueError("MAX_FILE_SIZE cannot exceed 50MB")
|
94 |
+
|
95 |
+
if cls.CHUNK_SIZE < 100:
|
96 |
+
raise ValueError("CHUNK_SIZE must be at least 100 characters")
|
97 |
+
|
98 |
+
@classmethod
|
99 |
+
def get_summary(cls) -> dict:
|
100 |
+
"""Get configuration summary"""
|
101 |
+
return {
|
102 |
+
"app_name": cls.APP_NAME,
|
103 |
+
"version": cls.VERSION,
|
104 |
+
"debug": cls.DEBUG,
|
105 |
+
"host": cls.HOST,
|
106 |
+
"port": cls.PORT,
|
107 |
+
"llama_model": cls.LLAMA_MODEL,
|
108 |
+
"embedding_model": cls.EMBEDDING_MODEL,
|
109 |
+
"chunk_size": cls.CHUNK_SIZE,
|
110 |
+
"max_file_size": cls.MAX_FILE_SIZE,
|
111 |
+
"rate_limit_enabled": cls.RATE_LIMIT_ENABLED
|
112 |
+
}
|
113 |
+
|
114 |
+
# Initialize configuration
|
115 |
+
config = Config()
|
116 |
+
config.create_directories()
|
117 |
+
|
118 |
+
# Validate configuration on import
|
119 |
+
try:
|
120 |
+
config.validate_config()
|
121 |
+
print("Configuration validated successfully")
|
122 |
+
except ValueError as e:
|
123 |
+
print(f"Configuration error: {e}")
|
124 |
+
if not config.DEBUG:
|
125 |
+
raise
|
src/components/groq_processor.py
ADDED
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Groq Llama 3.3 70B integration component
|
3 |
+
"""
|
4 |
+
|
5 |
+
import os
|
6 |
+
from typing import Dict, List, Optional, Any
|
7 |
+
from datetime import datetime
|
8 |
+
import re
|
9 |
+
|
10 |
+
from groq import Groq
|
11 |
+
from langchain.llms.base import LLM
|
12 |
+
from langchain.schema import Document
|
13 |
+
from pydantic import Field
|
14 |
+
|
15 |
+
from .config import config
|
16 |
+
|
17 |
+
|
18 |
+
class GroqLlamaLLM(LLM):
|
19 |
+
"""LangChain-compatible wrapper for Groq Llama 3.3 70B"""
|
20 |
+
|
21 |
+
api_key: str = Field(...)
|
22 |
+
groq_client: Any = Field(default=None)
|
23 |
+
model_name: str = Field(default="llama-3.3-70b-versatile")
|
24 |
+
temperature: float = Field(default=0.7)
|
25 |
+
max_tokens: int = Field(default=2000)
|
26 |
+
top_p: float = Field(default=0.9)
|
27 |
+
|
28 |
+
def __init__(self, **kwargs):
|
29 |
+
super().__init__(**kwargs)
|
30 |
+
self.groq_client = Groq(api_key=self.api_key)
|
31 |
+
|
32 |
+
class Config:
|
33 |
+
arbitrary_types_allowed = True
|
34 |
+
|
35 |
+
@property
|
36 |
+
def _llm_type(self) -> str:
|
37 |
+
return "groq_llama"
|
38 |
+
|
39 |
+
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
|
40 |
+
try:
|
41 |
+
response = self.groq_client.chat.completions.create(
|
42 |
+
model=self.model_name,
|
43 |
+
messages=[{"role": "user", "content": prompt}],
|
44 |
+
temperature=self.temperature,
|
45 |
+
max_tokens=self.max_tokens,
|
46 |
+
top_p=self.top_p,
|
47 |
+
stop=stop
|
48 |
+
)
|
49 |
+
return response.choices[0].message.content
|
50 |
+
except Exception as e:
|
51 |
+
return f"Error: {str(e)}"
|
52 |
+
|
53 |
+
@property
|
54 |
+
def _identifying_params(self) -> Dict[str, Any]:
|
55 |
+
return {
|
56 |
+
"model_name": self.model_name,
|
57 |
+
"temperature": self.temperature,
|
58 |
+
"max_tokens": self.max_tokens,
|
59 |
+
"top_p": self.top_p
|
60 |
+
}
|
61 |
+
|
62 |
+
|
63 |
+
class GroqProcessor:
|
64 |
+
"""Enhanced Groq Llama processor with research capabilities"""
|
65 |
+
|
66 |
+
def __init__(self, config_obj=None):
|
67 |
+
# Use passed config or default config
|
68 |
+
self.config = config_obj if config_obj else config
|
69 |
+
|
70 |
+
if not self.config.GROQ_API_KEY:
|
71 |
+
raise ValueError("Groq API key not found! Please set GROQ_API_KEY environment variable.")
|
72 |
+
|
73 |
+
self.groq_client = Groq(api_key=self.config.GROQ_API_KEY)
|
74 |
+
self.llm = GroqLlamaLLM(
|
75 |
+
api_key=self.config.GROQ_API_KEY,
|
76 |
+
model_name=self.config.LLAMA_MODEL,
|
77 |
+
temperature=self.config.TEMPERATURE,
|
78 |
+
max_tokens=self.config.MAX_OUTPUT_TOKENS,
|
79 |
+
top_p=self.config.TOP_P
|
80 |
+
)
|
81 |
+
print("Groq Llama 3.3 70B initialized successfully!")
|
82 |
+
|
83 |
+
def generate_response(self, prompt: str, max_tokens: int = 2000) -> str:
|
84 |
+
"""Generate response using Groq Llama"""
|
85 |
+
try:
|
86 |
+
response = self.groq_client.chat.completions.create(
|
87 |
+
model=self.config.LLAMA_MODEL,
|
88 |
+
messages=[{"role": "user", "content": prompt}],
|
89 |
+
temperature=self.config.TEMPERATURE,
|
90 |
+
max_tokens=max_tokens,
|
91 |
+
top_p=self.config.TOP_P
|
92 |
+
)
|
93 |
+
return response.choices[0].message.content.strip()
|
94 |
+
except Exception as e:
|
95 |
+
return f"Error: {str(e)}"
|
96 |
+
|
97 |
+
def summarize_paper(self, title: str, abstract: str, content: str) -> Dict[str, str]:
|
98 |
+
"""Generate comprehensive paper summary"""
|
99 |
+
try:
|
100 |
+
if len(content) > self.config.MAX_PAPER_LENGTH:
|
101 |
+
content = content[:self.config.MAX_PAPER_LENGTH] + "..."
|
102 |
+
|
103 |
+
prompt = f"""Analyze this research paper and provide a structured summary:
|
104 |
+
|
105 |
+
Title: {title}
|
106 |
+
Abstract: {abstract}
|
107 |
+
Content: {content[:8000]}
|
108 |
+
|
109 |
+
Provide a comprehensive summary with these sections:
|
110 |
+
1. **MAIN SUMMARY** (2-3 sentences)
|
111 |
+
2. **KEY CONTRIBUTIONS** (3-5 bullet points)
|
112 |
+
3. **METHODOLOGY** (brief description)
|
113 |
+
4. **KEY FINDINGS** (3-5 bullet points)
|
114 |
+
5. **LIMITATIONS** (if mentioned)
|
115 |
+
|
116 |
+
Format your response clearly with section headers."""
|
117 |
+
|
118 |
+
response = self.generate_response(prompt, max_tokens=self.config.MAX_SUMMARY_LENGTH)
|
119 |
+
return self._parse_summary_response(response, title, abstract)
|
120 |
+
except Exception as e:
|
121 |
+
return {
|
122 |
+
'summary': f'Error generating summary: {str(e)}',
|
123 |
+
'contributions': 'N/A',
|
124 |
+
'methodology': 'N/A',
|
125 |
+
'findings': 'N/A',
|
126 |
+
'limitations': 'N/A',
|
127 |
+
'title': title,
|
128 |
+
'abstract': abstract
|
129 |
+
}
|
130 |
+
|
131 |
+
def _parse_summary_response(self, response: str, title: str, abstract: str) -> Dict[str, str]:
|
132 |
+
"""Parse AI response into structured summary"""
|
133 |
+
sections = {
|
134 |
+
'summary': '',
|
135 |
+
'contributions': '',
|
136 |
+
'methodology': '',
|
137 |
+
'findings': '',
|
138 |
+
'limitations': '',
|
139 |
+
'title': title,
|
140 |
+
'abstract': abstract
|
141 |
+
}
|
142 |
+
|
143 |
+
if "Error:" in response:
|
144 |
+
return sections
|
145 |
+
|
146 |
+
lines = response.split('\n')
|
147 |
+
current_section = 'summary'
|
148 |
+
|
149 |
+
for line in lines:
|
150 |
+
line = line.strip()
|
151 |
+
if not line:
|
152 |
+
continue
|
153 |
+
|
154 |
+
line_lower = line.lower()
|
155 |
+
if any(keyword in line_lower for keyword in ['main summary', '1.', '**main']):
|
156 |
+
current_section = 'summary'
|
157 |
+
continue
|
158 |
+
elif any(keyword in line_lower for keyword in ['key contributions', '2.', '**key contrib']):
|
159 |
+
current_section = 'contributions'
|
160 |
+
continue
|
161 |
+
elif any(keyword in line_lower for keyword in ['methodology', '3.', '**method']):
|
162 |
+
current_section = 'methodology'
|
163 |
+
continue
|
164 |
+
elif any(keyword in line_lower for keyword in ['key findings', 'findings', '4.', '**key find']):
|
165 |
+
current_section = 'findings'
|
166 |
+
continue
|
167 |
+
elif any(keyword in line_lower for keyword in ['limitations', '5.', '**limit']):
|
168 |
+
current_section = 'limitations'
|
169 |
+
continue
|
170 |
+
|
171 |
+
if not line.startswith(('1.', '2.', '3.', '4.', '5.', '**', '#')):
|
172 |
+
sections[current_section] += line + ' '
|
173 |
+
|
174 |
+
return sections
|
175 |
+
|
176 |
+
def analyze_trends(self, texts: List[str]) -> Dict:
|
177 |
+
"""Analyze research trends from multiple texts"""
|
178 |
+
try:
|
179 |
+
combined_text = ' '.join(texts[:10]) # Limit to avoid token limits
|
180 |
+
|
181 |
+
prompt = f"""Analyze research trends in this collection of texts:
|
182 |
+
|
183 |
+
{combined_text[:5000]}
|
184 |
+
|
185 |
+
Identify:
|
186 |
+
1. Key research themes and topics
|
187 |
+
2. Emerging trends and directions
|
188 |
+
3. Frequently mentioned technologies/methods
|
189 |
+
4. Research gaps or opportunities
|
190 |
+
|
191 |
+
Provide analysis as structured points."""
|
192 |
+
|
193 |
+
response = self.generate_response(prompt, max_tokens=1500)
|
194 |
+
|
195 |
+
return {
|
196 |
+
'trend_analysis': response,
|
197 |
+
'texts_analyzed': len(texts),
|
198 |
+
'analysis_date': datetime.now().isoformat(),
|
199 |
+
'keywords': self._extract_keywords(combined_text)
|
200 |
+
}
|
201 |
+
except Exception as e:
|
202 |
+
return {
|
203 |
+
'trend_analysis': f'Error: {str(e)}',
|
204 |
+
'texts_analyzed': 0,
|
205 |
+
'analysis_date': datetime.now().isoformat(),
|
206 |
+
'keywords': []
|
207 |
+
}
|
208 |
+
|
209 |
+
def _extract_keywords(self, text: str) -> List[str]:
|
210 |
+
"""Extract keywords from text"""
|
211 |
+
words = re.findall(r'\b[a-zA-Z]+\b', text.lower())
|
212 |
+
stop_words = {'the', 'and', 'for', 'are', 'with', 'this', 'that', 'from', 'they', 'have'}
|
213 |
+
keywords = [w for w in words if len(w) > 3 and w not in stop_words]
|
214 |
+
|
215 |
+
# Count frequency and return top keywords
|
216 |
+
word_counts = {}
|
217 |
+
for word in keywords:
|
218 |
+
word_counts[word] = word_counts.get(word, 0) + 1
|
219 |
+
|
220 |
+
return [word for word, count in sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:20]]
|
221 |
+
|
222 |
+
def answer_question(self, question: str, context: str = "") -> str:
|
223 |
+
"""Answer a question with optional context"""
|
224 |
+
try:
|
225 |
+
prompt = f"""Answer this research question based on the provided context:
|
226 |
+
|
227 |
+
Question: {question}
|
228 |
+
|
229 |
+
Context: {context[:4000] if context else 'No specific context provided'}
|
230 |
+
|
231 |
+
Provide a clear, informative answer based on the context and your knowledge."""
|
232 |
+
|
233 |
+
return self.generate_response(prompt, max_tokens=1000)
|
234 |
+
except Exception as e:
|
235 |
+
return f"Error answering question: {str(e)}"
|
236 |
+
|
237 |
+
def generate_literature_review(self, papers: List[Dict], research_question: str) -> str:
|
238 |
+
"""Generate literature review from papers"""
|
239 |
+
try:
|
240 |
+
papers_text = "\n".join([
|
241 |
+
f"Title: {paper.get('title', '')}\nAbstract: {paper.get('abstract', '')}\n"
|
242 |
+
for paper in papers[:10]
|
243 |
+
])
|
244 |
+
|
245 |
+
prompt = f"""Generate a comprehensive literature review for the research question: "{research_question}"
|
246 |
+
|
247 |
+
Based on these papers:
|
248 |
+
{papers_text}
|
249 |
+
|
250 |
+
Provide a structured review with:
|
251 |
+
1. Introduction to the research area
|
252 |
+
2. Key themes and methodologies
|
253 |
+
3. Major findings and contributions
|
254 |
+
4. Research gaps and limitations
|
255 |
+
5. Future research directions
|
256 |
+
6. Conclusion
|
257 |
+
|
258 |
+
Keep it academic and well-structured."""
|
259 |
+
|
260 |
+
return self.generate_response(prompt, max_tokens=3000)
|
261 |
+
except Exception as e:
|
262 |
+
return f"Error generating literature review: {str(e)}"
|
263 |
+
|
264 |
+
def classify_paper(self, title: str, abstract: str) -> Dict[str, Any]:
|
265 |
+
"""Classify a paper into research categories"""
|
266 |
+
try:
|
267 |
+
prompt = f"""Classify this research paper:
|
268 |
+
|
269 |
+
Title: {title}
|
270 |
+
Abstract: {abstract}
|
271 |
+
|
272 |
+
Provide classification in JSON format:
|
273 |
+
{{
|
274 |
+
"primary_field": "field name",
|
275 |
+
"subfields": ["subfield1", "subfield2"],
|
276 |
+
"methodology": "methodology type",
|
277 |
+
"application_area": "application area",
|
278 |
+
"novelty_score": 1-10,
|
279 |
+
"impact_potential": "high/medium/low"
|
280 |
+
}}"""
|
281 |
+
|
282 |
+
response = self.generate_response(prompt, max_tokens=500)
|
283 |
+
|
284 |
+
# Try to parse as JSON, fallback to structured text
|
285 |
+
try:
|
286 |
+
import json
|
287 |
+
return json.loads(response)
|
288 |
+
except:
|
289 |
+
return {
|
290 |
+
"classification": response,
|
291 |
+
"title": title,
|
292 |
+
"processed_at": datetime.now().isoformat()
|
293 |
+
}
|
294 |
+
except Exception as e:
|
295 |
+
return {
|
296 |
+
"error": f"Classification error: {str(e)}",
|
297 |
+
"title": title,
|
298 |
+
"processed_at": datetime.now().isoformat()
|
299 |
+
}
|
300 |
+
|
301 |
+
def get_research_recommendations(self, interests: List[str], recent_papers: List[Dict]) -> str:
|
302 |
+
"""Get personalized research recommendations"""
|
303 |
+
try:
|
304 |
+
interests_text = ", ".join(interests)
|
305 |
+
papers_text = "\n".join([
|
306 |
+
f"- {paper.get('title', '')}"
|
307 |
+
for paper in recent_papers[:10]
|
308 |
+
])
|
309 |
+
|
310 |
+
prompt = f"""Based on these research interests: {interests_text}
|
311 |
+
|
312 |
+
And these recent papers:
|
313 |
+
{papers_text}
|
314 |
+
|
315 |
+
Provide personalized research recommendations including:
|
316 |
+
1. Trending topics to explore
|
317 |
+
2. Potential research gaps
|
318 |
+
3. Collaboration opportunities
|
319 |
+
4. Methodological approaches to consider
|
320 |
+
5. Future research directions
|
321 |
+
|
322 |
+
Keep recommendations specific and actionable."""
|
323 |
+
|
324 |
+
return self.generate_response(prompt, max_tokens=1500)
|
325 |
+
except Exception as e:
|
326 |
+
return f"Error generating recommendations: {str(e)}"
|
src/components/pdf_processor.py
ADDED
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
PDF Processor Component
|
3 |
+
Processes PDF files to extract text and metadata
|
4 |
+
"""
|
5 |
+
|
6 |
+
import os
|
7 |
+
import re
|
8 |
+
import warnings
|
9 |
+
from typing import List, Dict, Optional, Any
|
10 |
+
from datetime import datetime
|
11 |
+
from pathlib import Path
|
12 |
+
|
13 |
+
# PDF processing libraries
|
14 |
+
import pypdf
|
15 |
+
try:
|
16 |
+
import pdfplumber
|
17 |
+
import fitz # PyMuPDF
|
18 |
+
PDF_ENHANCED = True
|
19 |
+
except ImportError:
|
20 |
+
PDF_ENHANCED = False
|
21 |
+
|
22 |
+
warnings.filterwarnings('ignore')
|
23 |
+
|
24 |
+
|
25 |
+
class PDFProcessor:
|
26 |
+
"""
|
27 |
+
Processes PDF files to extract text, metadata, and structure
|
28 |
+
Supports multiple PDF processing libraries for better compatibility
|
29 |
+
"""
|
30 |
+
|
31 |
+
def __init__(self, config=None):
|
32 |
+
# Import Config only when needed to avoid dependency issues
|
33 |
+
if config is None:
|
34 |
+
try:
|
35 |
+
from .config import Config
|
36 |
+
self.config = Config()
|
37 |
+
except ImportError:
|
38 |
+
# Fallback to None if Config cannot be imported
|
39 |
+
self.config = None
|
40 |
+
else:
|
41 |
+
self.config = config
|
42 |
+
self.supported_formats = ['.pdf']
|
43 |
+
|
44 |
+
# Check available libraries
|
45 |
+
self.libraries = {
|
46 |
+
'pypdf': True,
|
47 |
+
'pdfplumber': PDF_ENHANCED,
|
48 |
+
'PyMuPDF': PDF_ENHANCED
|
49 |
+
}
|
50 |
+
|
51 |
+
print(f"PDF Processor initialized with libraries: {[k for k, v in self.libraries.items() if v]}")
|
52 |
+
|
53 |
+
def extract_text_from_file(self, file_path: str, method: str = 'auto') -> Dict[str, Any]:
|
54 |
+
"""
|
55 |
+
Extract text from PDF file
|
56 |
+
|
57 |
+
Args:
|
58 |
+
file_path: Path to PDF file
|
59 |
+
method: Extraction method ('auto', 'pypdf', 'pdfplumber', 'pymupdf')
|
60 |
+
|
61 |
+
Returns:
|
62 |
+
Dictionary with extracted text and metadata
|
63 |
+
"""
|
64 |
+
if not os.path.exists(file_path):
|
65 |
+
return {'error': f"File not found: {file_path}"}
|
66 |
+
|
67 |
+
if not file_path.lower().endswith('.pdf'):
|
68 |
+
return {'error': f"Not a PDF file: {file_path}"}
|
69 |
+
|
70 |
+
try:
|
71 |
+
print(f"Processing PDF: {os.path.basename(file_path)}")
|
72 |
+
|
73 |
+
# Try different methods based on preference
|
74 |
+
if method == 'auto':
|
75 |
+
# Try methods in order of preference
|
76 |
+
methods = ['pdfplumber', 'pymupdf', 'pypdf']
|
77 |
+
for m in methods:
|
78 |
+
if self.libraries.get(m.replace('pymupdf', 'PyMuPDF').replace('pdfplumber', 'pdfplumber').replace('pypdf', 'pypdf')):
|
79 |
+
result = self._extract_with_method(file_path, m)
|
80 |
+
if result and not result.get('error'):
|
81 |
+
return result
|
82 |
+
|
83 |
+
# If all methods fail, return error
|
84 |
+
return {'error': 'All extraction methods failed'}
|
85 |
+
|
86 |
+
else:
|
87 |
+
return self._extract_with_method(file_path, method)
|
88 |
+
|
89 |
+
except Exception as e:
|
90 |
+
return {'error': f"Error processing PDF: {str(e)}"}
|
91 |
+
|
92 |
+
def _extract_with_method(self, file_path: str, method: str) -> Dict[str, Any]:
|
93 |
+
"""
|
94 |
+
Extract text using a specific method
|
95 |
+
|
96 |
+
Args:
|
97 |
+
file_path: Path to PDF file
|
98 |
+
method: Extraction method
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
Dictionary with extracted text and metadata
|
102 |
+
"""
|
103 |
+
try:
|
104 |
+
if method == 'pdfplumber' and self.libraries['pdfplumber']:
|
105 |
+
return self._extract_with_pdfplumber(file_path)
|
106 |
+
elif method == 'pymupdf' and self.libraries['PyMuPDF']:
|
107 |
+
return self._extract_with_pymupdf(file_path)
|
108 |
+
elif method == 'pypdf' and self.libraries['pypdf']:
|
109 |
+
return self._extract_with_pypdf(file_path)
|
110 |
+
else:
|
111 |
+
return {'error': f"Method {method} not available"}
|
112 |
+
|
113 |
+
except Exception as e:
|
114 |
+
return {'error': f"Error with method {method}: {str(e)}"}
|
115 |
+
|
116 |
+
def _extract_with_pdfplumber(self, file_path: str) -> Dict[str, Any]:
|
117 |
+
"""Extract text using pdfplumber (best for tables and layout)"""
|
118 |
+
import pdfplumber
|
119 |
+
|
120 |
+
text_content = []
|
121 |
+
metadata = {
|
122 |
+
'method': 'pdfplumber',
|
123 |
+
'pages': 0,
|
124 |
+
'tables': 0,
|
125 |
+
'images': 0
|
126 |
+
}
|
127 |
+
|
128 |
+
with pdfplumber.open(file_path) as pdf:
|
129 |
+
metadata['pages'] = len(pdf.pages)
|
130 |
+
|
131 |
+
for page_num, page in enumerate(pdf.pages):
|
132 |
+
# Extract text
|
133 |
+
page_text = page.extract_text()
|
134 |
+
if page_text:
|
135 |
+
text_content.append(f"--- Page {page_num + 1} ---\n{page_text}")
|
136 |
+
|
137 |
+
# Count tables
|
138 |
+
tables = page.extract_tables()
|
139 |
+
if tables:
|
140 |
+
metadata['tables'] += len(tables)
|
141 |
+
# Add table content
|
142 |
+
for table in tables:
|
143 |
+
table_text = self._format_table(table)
|
144 |
+
text_content.append(f"--- Table on Page {page_num + 1} ---\n{table_text}")
|
145 |
+
|
146 |
+
# Count images
|
147 |
+
if hasattr(page, 'images'):
|
148 |
+
metadata['images'] += len(page.images)
|
149 |
+
|
150 |
+
full_text = '\n\n'.join(text_content)
|
151 |
+
|
152 |
+
return {
|
153 |
+
'text': full_text,
|
154 |
+
'metadata': metadata,
|
155 |
+
'word_count': len(full_text.split()),
|
156 |
+
'char_count': len(full_text),
|
157 |
+
'extracted_at': datetime.now().isoformat(),
|
158 |
+
'file_path': file_path
|
159 |
+
}
|
160 |
+
|
161 |
+
def _extract_with_pymupdf(self, file_path: str) -> Dict[str, Any]:
|
162 |
+
"""Extract text using PyMuPDF (fast and accurate)"""
|
163 |
+
import fitz
|
164 |
+
|
165 |
+
doc = fitz.open(file_path)
|
166 |
+
text_content = []
|
167 |
+
metadata = {
|
168 |
+
'method': 'pymupdf',
|
169 |
+
'pages': len(doc),
|
170 |
+
'images': 0,
|
171 |
+
'links': 0
|
172 |
+
}
|
173 |
+
|
174 |
+
for page_num in range(len(doc)):
|
175 |
+
page = doc[page_num]
|
176 |
+
|
177 |
+
# Extract text
|
178 |
+
page_text = page.get_text()
|
179 |
+
if page_text.strip():
|
180 |
+
text_content.append(f"--- Page {page_num + 1} ---\n{page_text}")
|
181 |
+
|
182 |
+
# Count images
|
183 |
+
images = page.get_images()
|
184 |
+
metadata['images'] += len(images)
|
185 |
+
|
186 |
+
# Count links
|
187 |
+
links = page.get_links()
|
188 |
+
metadata['links'] += len(links)
|
189 |
+
|
190 |
+
doc.close()
|
191 |
+
|
192 |
+
full_text = '\n\n'.join(text_content)
|
193 |
+
|
194 |
+
return {
|
195 |
+
'text': full_text,
|
196 |
+
'metadata': metadata,
|
197 |
+
'word_count': len(full_text.split()),
|
198 |
+
'char_count': len(full_text),
|
199 |
+
'extracted_at': datetime.now().isoformat(),
|
200 |
+
'file_path': file_path
|
201 |
+
}
|
202 |
+
|
203 |
+
def _extract_with_pypdf(self, file_path: str) -> Dict[str, Any]:
|
204 |
+
"""Extract text using pypdf (basic but reliable)"""
|
205 |
+
text_content = []
|
206 |
+
metadata = {
|
207 |
+
'method': 'pypdf',
|
208 |
+
'pages': 0
|
209 |
+
}
|
210 |
+
|
211 |
+
with open(file_path, 'rb') as file:
|
212 |
+
pdf_reader = pypdf.PdfReader(file)
|
213 |
+
metadata['pages'] = len(pdf_reader.pages)
|
214 |
+
|
215 |
+
for page_num, page in enumerate(pdf_reader.pages):
|
216 |
+
page_text = page.extract_text()
|
217 |
+
if page_text.strip():
|
218 |
+
text_content.append(f"--- Page {page_num + 1} ---\n{page_text}")
|
219 |
+
|
220 |
+
full_text = '\n\n'.join(text_content)
|
221 |
+
|
222 |
+
return {
|
223 |
+
'text': full_text,
|
224 |
+
'metadata': metadata,
|
225 |
+
'word_count': len(full_text.split()),
|
226 |
+
'char_count': len(full_text),
|
227 |
+
'extracted_at': datetime.now().isoformat(),
|
228 |
+
'file_path': file_path
|
229 |
+
}
|
230 |
+
|
231 |
+
def _format_table(self, table: List[List[str]]) -> str:
|
232 |
+
"""Format a table for text output"""
|
233 |
+
if not table:
|
234 |
+
return ""
|
235 |
+
|
236 |
+
formatted_rows = []
|
237 |
+
for row in table:
|
238 |
+
if row: # Skip empty rows
|
239 |
+
formatted_row = ' | '.join(str(cell) if cell else '' for cell in row)
|
240 |
+
formatted_rows.append(formatted_row)
|
241 |
+
|
242 |
+
return '\n'.join(formatted_rows)
|
243 |
+
|
244 |
+
def extract_text_from_bytes(self, pdf_bytes: bytes, filename: str = "uploaded.pdf") -> Dict[str, Any]:
|
245 |
+
"""
|
246 |
+
Extract text from PDF bytes (for uploaded files)
|
247 |
+
|
248 |
+
Args:
|
249 |
+
pdf_bytes: PDF file bytes
|
250 |
+
filename: Original filename
|
251 |
+
|
252 |
+
Returns:
|
253 |
+
Dictionary with extracted text and metadata
|
254 |
+
"""
|
255 |
+
try:
|
256 |
+
# Save bytes to temporary file
|
257 |
+
import tempfile
|
258 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
|
259 |
+
tmp_file.write(pdf_bytes)
|
260 |
+
tmp_path = tmp_file.name
|
261 |
+
|
262 |
+
# Extract text
|
263 |
+
result = self.extract_text_from_file(tmp_path)
|
264 |
+
|
265 |
+
# Clean up
|
266 |
+
os.unlink(tmp_path)
|
267 |
+
|
268 |
+
# Update metadata
|
269 |
+
if 'metadata' in result:
|
270 |
+
result['metadata']['original_filename'] = filename
|
271 |
+
result['metadata']['file_size'] = len(pdf_bytes)
|
272 |
+
|
273 |
+
return result
|
274 |
+
|
275 |
+
except Exception as e:
|
276 |
+
return {'error': f"Error processing PDF bytes: {str(e)}"}
|
277 |
+
|
278 |
+
def validate_pdf(self, file_path: str) -> Dict[str, Any]:
|
279 |
+
"""
|
280 |
+
Validate PDF file
|
281 |
+
|
282 |
+
Args:
|
283 |
+
file_path: Path to PDF file
|
284 |
+
|
285 |
+
Returns:
|
286 |
+
Validation result
|
287 |
+
"""
|
288 |
+
try:
|
289 |
+
if not os.path.exists(file_path):
|
290 |
+
return {'valid': False, 'error': 'File not found'}
|
291 |
+
|
292 |
+
if not file_path.lower().endswith('.pdf'):
|
293 |
+
return {'valid': False, 'error': 'Not a PDF file'}
|
294 |
+
|
295 |
+
# Try to open with pypdf
|
296 |
+
with open(file_path, 'rb') as file:
|
297 |
+
pdf_reader = pypdf.PdfReader(file)
|
298 |
+
page_count = len(pdf_reader.pages)
|
299 |
+
|
300 |
+
# Check if encrypted
|
301 |
+
is_encrypted = pdf_reader.is_encrypted
|
302 |
+
|
303 |
+
# Get file size
|
304 |
+
file_size = os.path.getsize(file_path)
|
305 |
+
|
306 |
+
return {
|
307 |
+
'valid': True,
|
308 |
+
'pages': page_count,
|
309 |
+
'encrypted': is_encrypted,
|
310 |
+
'file_size': file_size,
|
311 |
+
'file_path': file_path
|
312 |
+
}
|
313 |
+
|
314 |
+
except Exception as e:
|
315 |
+
return {'valid': False, 'error': str(e)}
|
316 |
+
|
317 |
+
def get_pdf_metadata(self, file_path: str) -> Dict[str, Any]:
|
318 |
+
"""
|
319 |
+
Extract metadata from PDF
|
320 |
+
|
321 |
+
Args:
|
322 |
+
file_path: Path to PDF file
|
323 |
+
|
324 |
+
Returns:
|
325 |
+
PDF metadata
|
326 |
+
"""
|
327 |
+
try:
|
328 |
+
metadata = {}
|
329 |
+
|
330 |
+
# Try pypdf first
|
331 |
+
try:
|
332 |
+
with open(file_path, 'rb') as file:
|
333 |
+
pdf_reader = pypdf.PdfReader(file)
|
334 |
+
if pdf_reader.metadata:
|
335 |
+
metadata.update({
|
336 |
+
'title': pdf_reader.metadata.get('/Title', ''),
|
337 |
+
'author': pdf_reader.metadata.get('/Author', ''),
|
338 |
+
'subject': pdf_reader.metadata.get('/Subject', ''),
|
339 |
+
'creator': pdf_reader.metadata.get('/Creator', ''),
|
340 |
+
'producer': pdf_reader.metadata.get('/Producer', ''),
|
341 |
+
'creation_date': pdf_reader.metadata.get('/CreationDate', ''),
|
342 |
+
'modification_date': pdf_reader.metadata.get('/ModDate', '')
|
343 |
+
})
|
344 |
+
except Exception:
|
345 |
+
pass
|
346 |
+
|
347 |
+
# Try PyMuPDF for additional metadata
|
348 |
+
if self.libraries['PyMuPDF']:
|
349 |
+
try:
|
350 |
+
import fitz
|
351 |
+
doc = fitz.open(file_path)
|
352 |
+
doc_metadata = doc.metadata
|
353 |
+
doc.close()
|
354 |
+
|
355 |
+
if doc_metadata:
|
356 |
+
metadata.update({
|
357 |
+
'format': doc_metadata.get('format', ''),
|
358 |
+
'encryption': doc_metadata.get('encryption', ''),
|
359 |
+
'keywords': doc_metadata.get('keywords', '')
|
360 |
+
})
|
361 |
+
except Exception:
|
362 |
+
pass
|
363 |
+
|
364 |
+
# Add file system metadata
|
365 |
+
stat = os.stat(file_path)
|
366 |
+
metadata.update({
|
367 |
+
'file_size': stat.st_size,
|
368 |
+
'created': datetime.fromtimestamp(stat.st_ctime).isoformat(),
|
369 |
+
'modified': datetime.fromtimestamp(stat.st_mtime).isoformat(),
|
370 |
+
'accessed': datetime.fromtimestamp(stat.st_atime).isoformat()
|
371 |
+
})
|
372 |
+
|
373 |
+
return metadata
|
374 |
+
|
375 |
+
except Exception as e:
|
376 |
+
return {'error': f"Error extracting metadata: {str(e)}"}
|
377 |
+
|
378 |
+
def split_pdf_text(self, text: str, chunk_size: int = None, chunk_overlap: int = None) -> List[str]:
|
379 |
+
"""
|
380 |
+
Split PDF text into chunks for processing
|
381 |
+
|
382 |
+
Args:
|
383 |
+
text: Extracted text
|
384 |
+
chunk_size: Size of each chunk
|
385 |
+
chunk_overlap: Overlap between chunks
|
386 |
+
|
387 |
+
Returns:
|
388 |
+
List of text chunks
|
389 |
+
"""
|
390 |
+
# Use provided values or defaults if config is None
|
391 |
+
if chunk_size is None:
|
392 |
+
chunk_size = self.config.CHUNK_SIZE if self.config else 1000
|
393 |
+
if chunk_overlap is None:
|
394 |
+
chunk_overlap = self.config.CHUNK_OVERLAP if self.config else 200
|
395 |
+
|
396 |
+
if len(text) <= chunk_size:
|
397 |
+
return [text]
|
398 |
+
|
399 |
+
chunks = []
|
400 |
+
start = 0
|
401 |
+
|
402 |
+
while start < len(text):
|
403 |
+
end = start + chunk_size
|
404 |
+
|
405 |
+
# Try to break at sentence boundary
|
406 |
+
if end < len(text):
|
407 |
+
# Look for sentence ending
|
408 |
+
sentence_end = text.rfind('.', start, end)
|
409 |
+
if sentence_end > start:
|
410 |
+
end = sentence_end + 1
|
411 |
+
else:
|
412 |
+
# Look for paragraph break
|
413 |
+
para_end = text.rfind('\n\n', start, end)
|
414 |
+
if para_end > start:
|
415 |
+
end = para_end + 2
|
416 |
+
else:
|
417 |
+
# Look for any line break
|
418 |
+
line_end = text.rfind('\n', start, end)
|
419 |
+
if line_end > start:
|
420 |
+
end = line_end + 1
|
421 |
+
|
422 |
+
chunk = text[start:end].strip()
|
423 |
+
if chunk:
|
424 |
+
chunks.append(chunk)
|
425 |
+
|
426 |
+
start = end - chunk_overlap
|
427 |
+
|
428 |
+
return chunks
|
429 |
+
|
430 |
+
def clean_text(self, text: str) -> str:
|
431 |
+
"""
|
432 |
+
Clean extracted text
|
433 |
+
|
434 |
+
Args:
|
435 |
+
text: Raw extracted text
|
436 |
+
|
437 |
+
Returns:
|
438 |
+
Cleaned text
|
439 |
+
"""
|
440 |
+
if not text:
|
441 |
+
return ""
|
442 |
+
|
443 |
+
# Remove extra whitespace
|
444 |
+
text = re.sub(r'\s+', ' ', text)
|
445 |
+
|
446 |
+
# Remove page headers/footers (basic)
|
447 |
+
text = re.sub(r'Page \d+', '', text)
|
448 |
+
|
449 |
+
# Remove email addresses (optional)
|
450 |
+
text = re.sub(r'\S+@\S+', '', text)
|
451 |
+
|
452 |
+
# Remove URLs (optional)
|
453 |
+
text = re.sub(r'https?://\S+', '', text)
|
454 |
+
|
455 |
+
# Fix common OCR errors
|
456 |
+
text = text.replace('fi', 'fi')
|
457 |
+
text = text.replace('fl', 'fl')
|
458 |
+
text = text.replace('ff', 'ff')
|
459 |
+
text = text.replace('ffi', 'ffi')
|
460 |
+
text = text.replace('ffl', 'ffl')
|
461 |
+
|
462 |
+
return text.strip()
|
463 |
+
|
464 |
+
def get_processing_stats(self) -> Dict[str, Any]:
|
465 |
+
"""
|
466 |
+
Get PDF processing statistics
|
467 |
+
|
468 |
+
Returns:
|
469 |
+
Processing statistics
|
470 |
+
"""
|
471 |
+
return {
|
472 |
+
'available_libraries': self.libraries,
|
473 |
+
'supported_formats': self.supported_formats,
|
474 |
+
'enhanced_features': PDF_ENHANCED,
|
475 |
+
'config': {
|
476 |
+
'chunk_size': self.config.CHUNK_SIZE if self.config else 1000,
|
477 |
+
'chunk_overlap': self.config.CHUNK_OVERLAP if self.config else 200
|
478 |
+
}
|
479 |
+
}
|
src/components/rag_system.py
ADDED
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
RAG System Component
|
3 |
+
Retrieval-Augmented Generation for research papers
|
4 |
+
"""
|
5 |
+
|
6 |
+
import os
|
7 |
+
import warnings
|
8 |
+
from typing import List, Dict, Optional, Any
|
9 |
+
from datetime import datetime
|
10 |
+
|
11 |
+
# LangChain
|
12 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
13 |
+
from langchain.chains import RetrievalQA
|
14 |
+
from langchain_community.vectorstores import Chroma
|
15 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
16 |
+
from langchain.schema import Document
|
17 |
+
|
18 |
+
from .config import Config
|
19 |
+
from .groq_processor import GroqLlamaLLM
|
20 |
+
|
21 |
+
warnings.filterwarnings('ignore')
|
22 |
+
|
23 |
+
|
24 |
+
class RAGSystem:
|
25 |
+
"""
|
26 |
+
Advanced RAG (Retrieval-Augmented Generation) System
|
27 |
+
Combines vector database search with LLM reasoning
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(self, config: Config = None):
|
31 |
+
self.config = config or Config()
|
32 |
+
# Ensure directories exist
|
33 |
+
self.config.create_directories()
|
34 |
+
|
35 |
+
self.embeddings = None
|
36 |
+
self.vectorstore = None
|
37 |
+
self.llm = None
|
38 |
+
self.qa_chain = None
|
39 |
+
self.text_splitter = None
|
40 |
+
self.papers_metadata = {}
|
41 |
+
|
42 |
+
self._initialize_components()
|
43 |
+
|
44 |
+
def _initialize_components(self):
|
45 |
+
"""Initialize all RAG components"""
|
46 |
+
try:
|
47 |
+
# Initialize embeddings
|
48 |
+
print("Initializing embeddings...")
|
49 |
+
self.embeddings = HuggingFaceEmbeddings(
|
50 |
+
model_name=self.config.EMBEDDING_MODEL,
|
51 |
+
model_kwargs={'device': 'cpu'}
|
52 |
+
)
|
53 |
+
print("✅ Embeddings initialized!")
|
54 |
+
|
55 |
+
# Initialize text splitter
|
56 |
+
self.text_splitter = RecursiveCharacterTextSplitter(
|
57 |
+
chunk_size=self.config.CHUNK_SIZE,
|
58 |
+
chunk_overlap=self.config.CHUNK_OVERLAP
|
59 |
+
)
|
60 |
+
print("✅ Text splitter initialized!")
|
61 |
+
|
62 |
+
# Initialize LLM
|
63 |
+
print("Initializing LLM...")
|
64 |
+
self.llm = GroqLlamaLLM(
|
65 |
+
api_key=self.config.GROQ_API_KEY,
|
66 |
+
model_name=self.config.LLAMA_MODEL,
|
67 |
+
temperature=self.config.TEMPERATURE,
|
68 |
+
max_tokens=self.config.MAX_OUTPUT_TOKENS,
|
69 |
+
top_p=self.config.TOP_P
|
70 |
+
)
|
71 |
+
print("✅ LLM initialized!")
|
72 |
+
|
73 |
+
# Initialize or load vectorstore
|
74 |
+
print("Initializing vectorstore...")
|
75 |
+
self._initialize_vectorstore()
|
76 |
+
|
77 |
+
# Initialize QA chain
|
78 |
+
if self.vectorstore:
|
79 |
+
print("Initializing QA chain...")
|
80 |
+
self.qa_chain = RetrievalQA.from_chain_type(
|
81 |
+
llm=self.llm,
|
82 |
+
chain_type="stuff",
|
83 |
+
retriever=self.vectorstore.as_retriever(
|
84 |
+
search_kwargs={"k": self.config.TOP_K_SIMILAR}
|
85 |
+
),
|
86 |
+
return_source_documents=True
|
87 |
+
)
|
88 |
+
print("✅ QA chain initialized!")
|
89 |
+
|
90 |
+
print("✅ RAG System initialized successfully!")
|
91 |
+
|
92 |
+
except Exception as e:
|
93 |
+
print(f"❌ Error initializing RAG System: {e}")
|
94 |
+
import traceback
|
95 |
+
traceback.print_exc()
|
96 |
+
raise
|
97 |
+
|
98 |
+
def _initialize_vectorstore(self):
|
99 |
+
"""Initialize or load existing vectorstore"""
|
100 |
+
try:
|
101 |
+
# Ensure persist directory exists with absolute path
|
102 |
+
persist_dir = os.path.abspath(self.config.PERSIST_DIRECTORY)
|
103 |
+
print(f"Initializing vectorstore at: {persist_dir}")
|
104 |
+
os.makedirs(persist_dir, exist_ok=True)
|
105 |
+
|
106 |
+
# Check if directory has existing data
|
107 |
+
has_existing_data = os.path.exists(persist_dir) and any(
|
108 |
+
f for f in os.listdir(persist_dir)
|
109 |
+
if not f.startswith('.') and os.path.isfile(os.path.join(persist_dir, f))
|
110 |
+
)
|
111 |
+
|
112 |
+
if has_existing_data:
|
113 |
+
print("Loading existing vectorstore...")
|
114 |
+
self.vectorstore = Chroma(
|
115 |
+
persist_directory=persist_dir,
|
116 |
+
embedding_function=self.embeddings,
|
117 |
+
collection_name=self.config.COLLECTION_NAME
|
118 |
+
)
|
119 |
+
try:
|
120 |
+
count = self.vectorstore._collection.count()
|
121 |
+
print(f"✅ Loaded vectorstore with {count} documents")
|
122 |
+
except Exception as count_error:
|
123 |
+
print(f"✅ Loaded vectorstore (document count unavailable: {count_error})")
|
124 |
+
else:
|
125 |
+
print("Creating new vectorstore...")
|
126 |
+
self.vectorstore = Chroma(
|
127 |
+
persist_directory=persist_dir,
|
128 |
+
embedding_function=self.embeddings,
|
129 |
+
collection_name=self.config.COLLECTION_NAME
|
130 |
+
)
|
131 |
+
print("✅ New vectorstore created successfully!")
|
132 |
+
|
133 |
+
except Exception as e:
|
134 |
+
print(f"❌ Error initializing vectorstore: {e}")
|
135 |
+
print(f" Persist directory: {getattr(self.config, 'PERSIST_DIRECTORY', 'NOT SET')}")
|
136 |
+
print(f" Collection name: {getattr(self.config, 'COLLECTION_NAME', 'NOT SET')}")
|
137 |
+
print(" Continuing without vectorstore - search functionality will be limited")
|
138 |
+
self.vectorstore = None
|
139 |
+
|
140 |
+
def add_papers(self, papers: List[Dict[str, Any]]):
|
141 |
+
"""
|
142 |
+
Add research papers to the RAG system
|
143 |
+
|
144 |
+
Args:
|
145 |
+
papers: List of paper dictionaries with 'title', 'content', 'summary', etc.
|
146 |
+
"""
|
147 |
+
if not self.vectorstore:
|
148 |
+
print("Vectorstore not initialized! Attempting to reinitialize...")
|
149 |
+
try:
|
150 |
+
self._initialize_vectorstore()
|
151 |
+
if not self.vectorstore:
|
152 |
+
print("Failed to initialize vectorstore - papers will not be added to search index")
|
153 |
+
return
|
154 |
+
except Exception as e:
|
155 |
+
print(f"Failed to reinitialize vectorstore: {e}")
|
156 |
+
return
|
157 |
+
|
158 |
+
documents = []
|
159 |
+
|
160 |
+
for paper in papers:
|
161 |
+
# Create metadata - Chroma only supports str, int, float, bool, None
|
162 |
+
authors = paper.get('authors', [])
|
163 |
+
categories = paper.get('categories', [])
|
164 |
+
|
165 |
+
metadata = {
|
166 |
+
'title': str(paper.get('title', 'Unknown')),
|
167 |
+
'authors': ', '.join(authors) if isinstance(authors, list) else str(authors),
|
168 |
+
'published': str(paper.get('published', '')),
|
169 |
+
'pdf_url': str(paper.get('pdf_url', '')),
|
170 |
+
'arxiv_id': str(paper.get('arxiv_id', '')),
|
171 |
+
'summary': str(paper.get('summary', '')),
|
172 |
+
'categories': ', '.join(categories) if isinstance(categories, list) else str(categories),
|
173 |
+
'source': str(paper.get('source', 'unknown')),
|
174 |
+
'added_at': datetime.now().isoformat()
|
175 |
+
}
|
176 |
+
|
177 |
+
# Store metadata
|
178 |
+
paper_id = paper.get('arxiv_id', paper.get('title', ''))
|
179 |
+
self.papers_metadata[paper_id] = metadata
|
180 |
+
|
181 |
+
# Process content
|
182 |
+
content = paper.get('content', '')
|
183 |
+
if not content:
|
184 |
+
content = paper.get('summary', '')
|
185 |
+
|
186 |
+
if content:
|
187 |
+
# Split content into chunks
|
188 |
+
chunks = self.text_splitter.split_text(content)
|
189 |
+
|
190 |
+
# Create documents
|
191 |
+
for i, chunk in enumerate(chunks):
|
192 |
+
doc_metadata = metadata.copy()
|
193 |
+
doc_metadata['chunk_id'] = i
|
194 |
+
doc_metadata['chunk_count'] = len(chunks)
|
195 |
+
|
196 |
+
documents.append(Document(
|
197 |
+
page_content=chunk,
|
198 |
+
metadata=doc_metadata
|
199 |
+
))
|
200 |
+
|
201 |
+
if documents:
|
202 |
+
try:
|
203 |
+
print(f"Adding {len(documents)} chunks to vectorstore...")
|
204 |
+
self.vectorstore.add_documents(documents)
|
205 |
+
self.vectorstore.persist()
|
206 |
+
print(f"✅ Successfully added {len(documents)} chunks from {len(papers)} papers!")
|
207 |
+
except Exception as e:
|
208 |
+
print(f"❌ Error adding documents to vectorstore: {e}")
|
209 |
+
print(" This may be due to metadata formatting issues")
|
210 |
+
# Try to add documents one by one to identify problematic ones
|
211 |
+
success_count = 0
|
212 |
+
for i, doc in enumerate(documents):
|
213 |
+
try:
|
214 |
+
self.vectorstore.add_documents([doc])
|
215 |
+
success_count += 1
|
216 |
+
except Exception as doc_error:
|
217 |
+
print(f" Failed to add document {i}: {doc_error}")
|
218 |
+
print(f" Metadata: {doc.metadata}")
|
219 |
+
|
220 |
+
if success_count > 0:
|
221 |
+
self.vectorstore.persist()
|
222 |
+
print(f"✅ Successfully added {success_count}/{len(documents)} documents")
|
223 |
+
else:
|
224 |
+
print("No valid documents to add!")
|
225 |
+
|
226 |
+
def search_papers(self, query: str, k: int = None) -> List[Dict[str, Any]]:
|
227 |
+
"""
|
228 |
+
Search for relevant papers using vector similarity
|
229 |
+
|
230 |
+
Args:
|
231 |
+
query: Search query
|
232 |
+
k: Number of results to return
|
233 |
+
|
234 |
+
Returns:
|
235 |
+
List of relevant paper chunks with metadata
|
236 |
+
"""
|
237 |
+
if not self.vectorstore:
|
238 |
+
print("Vectorstore not initialized!")
|
239 |
+
return []
|
240 |
+
|
241 |
+
try:
|
242 |
+
k = k or self.config.TOP_K_SIMILAR
|
243 |
+
results = self.vectorstore.similarity_search_with_score(query, k=k)
|
244 |
+
|
245 |
+
formatted_results = []
|
246 |
+
for doc, score in results:
|
247 |
+
result = {
|
248 |
+
'content': doc.page_content,
|
249 |
+
'score': score,
|
250 |
+
'metadata': doc.metadata,
|
251 |
+
'title': doc.metadata.get('title', 'Unknown'),
|
252 |
+
'authors': doc.metadata.get('authors', []),
|
253 |
+
'published': doc.metadata.get('published', ''),
|
254 |
+
'summary': doc.metadata.get('summary', ''),
|
255 |
+
'arxiv_id': doc.metadata.get('arxiv_id', ''),
|
256 |
+
'pdf_url': doc.metadata.get('pdf_url', ''),
|
257 |
+
'categories': doc.metadata.get('categories', [])
|
258 |
+
}
|
259 |
+
formatted_results.append(result)
|
260 |
+
|
261 |
+
return formatted_results
|
262 |
+
|
263 |
+
except Exception as e:
|
264 |
+
print(f"Search error: {e}")
|
265 |
+
return []
|
266 |
+
|
267 |
+
def answer_question(self, question: str) -> Dict[str, Any]:
|
268 |
+
"""
|
269 |
+
Answer a research question using RAG
|
270 |
+
|
271 |
+
Args:
|
272 |
+
question: Research question
|
273 |
+
|
274 |
+
Returns:
|
275 |
+
Dictionary with answer and source information
|
276 |
+
"""
|
277 |
+
if not self.qa_chain:
|
278 |
+
return {
|
279 |
+
'answer': "RAG system not properly initialized!",
|
280 |
+
'sources': [],
|
281 |
+
'error': "System not initialized"
|
282 |
+
}
|
283 |
+
|
284 |
+
try:
|
285 |
+
print(f"Processing question: {question}")
|
286 |
+
result = self.qa_chain({"query": question})
|
287 |
+
|
288 |
+
# Extract source information
|
289 |
+
sources = []
|
290 |
+
for doc in result.get('source_documents', []):
|
291 |
+
sources.append({
|
292 |
+
'title': doc.metadata.get('title', 'Unknown'),
|
293 |
+
'authors': doc.metadata.get('authors', []),
|
294 |
+
'content_snippet': doc.page_content[:200] + "..." if len(doc.page_content) > 200 else doc.page_content,
|
295 |
+
'arxiv_id': doc.metadata.get('arxiv_id', ''),
|
296 |
+
'pdf_url': doc.metadata.get('pdf_url', ''),
|
297 |
+
'chunk_id': doc.metadata.get('chunk_id', 0)
|
298 |
+
})
|
299 |
+
|
300 |
+
return {
|
301 |
+
'answer': result['result'],
|
302 |
+
'sources': sources,
|
303 |
+
'question': question,
|
304 |
+
'timestamp': datetime.now().isoformat()
|
305 |
+
}
|
306 |
+
|
307 |
+
except Exception as e:
|
308 |
+
print(f"Error answering question: {e}")
|
309 |
+
return {
|
310 |
+
'answer': f"Error processing question: {str(e)}",
|
311 |
+
'sources': [],
|
312 |
+
'error': str(e)
|
313 |
+
}
|
314 |
+
|
315 |
+
def get_database_stats(self) -> Dict[str, Any]:
|
316 |
+
"""Get statistics about the knowledge base"""
|
317 |
+
if not self.vectorstore:
|
318 |
+
return {'status': 'not_initialized', 'count': 0}
|
319 |
+
|
320 |
+
try:
|
321 |
+
count = self.vectorstore._collection.count()
|
322 |
+
return {
|
323 |
+
'status': 'active',
|
324 |
+
'total_chunks': count,
|
325 |
+
'total_papers': len(self.papers_metadata),
|
326 |
+
'embedding_model': self.config.EMBEDDING_MODEL,
|
327 |
+
'chunk_size': self.config.CHUNK_SIZE,
|
328 |
+
'chunk_overlap': self.config.CHUNK_OVERLAP
|
329 |
+
}
|
330 |
+
except Exception as e:
|
331 |
+
return {'status': 'error', 'error': str(e)}
|
332 |
+
|
333 |
+
def clear_database(self):
|
334 |
+
"""Clear all data from the vectorstore"""
|
335 |
+
try:
|
336 |
+
if self.vectorstore:
|
337 |
+
self.vectorstore.delete_collection()
|
338 |
+
print("Database cleared!")
|
339 |
+
|
340 |
+
self.papers_metadata.clear()
|
341 |
+
self._initialize_vectorstore()
|
342 |
+
|
343 |
+
except Exception as e:
|
344 |
+
print(f"Error clearing database: {e}")
|
345 |
+
|
346 |
+
def export_papers_metadata(self) -> Dict[str, Any]:
|
347 |
+
"""Export papers metadata for backup or analysis"""
|
348 |
+
return {
|
349 |
+
'metadata': self.papers_metadata,
|
350 |
+
'export_time': datetime.now().isoformat(),
|
351 |
+
'total_papers': len(self.papers_metadata),
|
352 |
+
'database_stats': self.get_database_stats()
|
353 |
+
}
|
354 |
+
|
355 |
+
def test_vectorstore(self) -> Dict[str, Any]:
|
356 |
+
"""Test vectorstore functionality and return status"""
|
357 |
+
status = {
|
358 |
+
'vectorstore_initialized': False,
|
359 |
+
'can_add_documents': False,
|
360 |
+
'can_search': False,
|
361 |
+
'document_count': 0,
|
362 |
+
'persist_directory': getattr(self.config, 'PERSIST_DIRECTORY', 'NOT SET'),
|
363 |
+
'collection_name': getattr(self.config, 'COLLECTION_NAME', 'NOT SET'),
|
364 |
+
'errors': []
|
365 |
+
}
|
366 |
+
|
367 |
+
try:
|
368 |
+
if self.vectorstore is None:
|
369 |
+
status['errors'].append("Vectorstore is None")
|
370 |
+
return status
|
371 |
+
|
372 |
+
status['vectorstore_initialized'] = True
|
373 |
+
|
374 |
+
# Test document count
|
375 |
+
try:
|
376 |
+
count = self.vectorstore._collection.count()
|
377 |
+
status['document_count'] = count
|
378 |
+
except Exception as e:
|
379 |
+
status['errors'].append(f"Cannot get document count: {e}")
|
380 |
+
|
381 |
+
# Test adding a simple document
|
382 |
+
try:
|
383 |
+
test_doc = Document(
|
384 |
+
page_content="This is a test document",
|
385 |
+
metadata={"test": True, "source": "vectorstore_test"}
|
386 |
+
)
|
387 |
+
self.vectorstore.add_documents([test_doc])
|
388 |
+
status['can_add_documents'] = True
|
389 |
+
|
390 |
+
# Test searching
|
391 |
+
results = self.vectorstore.similarity_search("test document", k=1)
|
392 |
+
if results:
|
393 |
+
status['can_search'] = True
|
394 |
+
|
395 |
+
# Clean up test document
|
396 |
+
try:
|
397 |
+
# Remove test document if possible
|
398 |
+
pass # Chroma doesn't have easy delete by metadata
|
399 |
+
except:
|
400 |
+
pass
|
401 |
+
|
402 |
+
except Exception as e:
|
403 |
+
status['errors'].append(f"Cannot add/search documents: {e}")
|
404 |
+
|
405 |
+
except Exception as e:
|
406 |
+
status['errors'].append(f"Vectorstore test failed: {e}")
|
407 |
+
|
408 |
+
return status
|
src/components/research_assistant.py
ADDED
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Research Assistant Component
|
3 |
+
Main research assistant logic and workflow management
|
4 |
+
"""
|
5 |
+
|
6 |
+
import os
|
7 |
+
import json
|
8 |
+
from typing import List, Dict, Optional, Any
|
9 |
+
from datetime import datetime
|
10 |
+
import logging
|
11 |
+
|
12 |
+
from .config import Config
|
13 |
+
from .groq_processor import GroqProcessor
|
14 |
+
from .rag_system import RAGSystem
|
15 |
+
from .unified_fetcher import PaperFetcher
|
16 |
+
from .pdf_processor import PDFProcessor
|
17 |
+
from .trend_monitor import AdvancedTrendMonitor
|
18 |
+
|
19 |
+
|
20 |
+
class ProjectManager:
|
21 |
+
"""Manages research projects"""
|
22 |
+
|
23 |
+
def __init__(self, config: Config = None):
|
24 |
+
self.config = config or Config()
|
25 |
+
self.projects = {}
|
26 |
+
self.project_counter = 0
|
27 |
+
self.projects_file = os.path.join(self.config.BASE_DIR, 'projects.json')
|
28 |
+
self.load_projects()
|
29 |
+
|
30 |
+
def load_projects(self):
|
31 |
+
"""Load projects from storage"""
|
32 |
+
try:
|
33 |
+
if os.path.exists(self.projects_file):
|
34 |
+
with open(self.projects_file, 'r') as f:
|
35 |
+
data = json.load(f)
|
36 |
+
self.projects = data.get('projects', {})
|
37 |
+
self.project_counter = data.get('counter', 0)
|
38 |
+
print(f"Loaded {len(self.projects)} projects")
|
39 |
+
except Exception as e:
|
40 |
+
print(f"Error loading projects: {e}")
|
41 |
+
|
42 |
+
def save_projects(self):
|
43 |
+
"""Save projects to storage"""
|
44 |
+
try:
|
45 |
+
os.makedirs(os.path.dirname(self.projects_file), exist_ok=True)
|
46 |
+
with open(self.projects_file, 'w') as f:
|
47 |
+
json.dump({
|
48 |
+
'projects': self.projects,
|
49 |
+
'counter': self.project_counter
|
50 |
+
}, f, indent=2)
|
51 |
+
except Exception as e:
|
52 |
+
print(f"Error saving projects: {e}")
|
53 |
+
|
54 |
+
def create_project(self, name: str, research_question: str, keywords: List[str], user_id: str) -> str:
|
55 |
+
"""Create a new research project"""
|
56 |
+
self.project_counter += 1
|
57 |
+
project_id = f"project_{self.project_counter}"
|
58 |
+
|
59 |
+
self.projects[project_id] = {
|
60 |
+
'id': project_id,
|
61 |
+
'name': name,
|
62 |
+
'research_question': research_question,
|
63 |
+
'keywords': keywords,
|
64 |
+
'papers': [],
|
65 |
+
'notes': [],
|
66 |
+
'status': 'active',
|
67 |
+
'user_id': user_id, # Track which user created this project
|
68 |
+
'created_at': datetime.now().isoformat(),
|
69 |
+
'updated_at': datetime.now().isoformat()
|
70 |
+
}
|
71 |
+
|
72 |
+
self.save_projects()
|
73 |
+
return project_id
|
74 |
+
|
75 |
+
def get_project(self, project_id: str, user_id: str = None) -> Optional[Dict[str, Any]]:
|
76 |
+
"""Get a project by ID, optionally checking user ownership"""
|
77 |
+
project = self.projects.get(project_id)
|
78 |
+
if project and user_id:
|
79 |
+
# Check if user owns this project
|
80 |
+
if project.get('user_id') != user_id:
|
81 |
+
return None
|
82 |
+
return project
|
83 |
+
|
84 |
+
def update_project(self, project_id: str, user_id: str = None, **kwargs):
|
85 |
+
"""Update a project"""
|
86 |
+
if project_id in self.projects:
|
87 |
+
# Check user ownership if user_id provided
|
88 |
+
if user_id and self.projects[project_id].get('user_id') != user_id:
|
89 |
+
return False
|
90 |
+
self.projects[project_id].update(kwargs)
|
91 |
+
self.projects[project_id]['updated_at'] = datetime.now().isoformat()
|
92 |
+
self.save_projects()
|
93 |
+
return True
|
94 |
+
return False
|
95 |
+
|
96 |
+
def add_paper_to_project(self, project_id: str, paper: Dict[str, Any], user_id: str = None):
|
97 |
+
"""Add a paper to a project"""
|
98 |
+
if project_id in self.projects:
|
99 |
+
# Check user ownership if user_id provided
|
100 |
+
if user_id and self.projects[project_id].get('user_id') != user_id:
|
101 |
+
return False
|
102 |
+
self.projects[project_id]['papers'].append(paper)
|
103 |
+
self.update_project(project_id, user_id=user_id)
|
104 |
+
return True
|
105 |
+
return False
|
106 |
+
|
107 |
+
def list_projects(self, user_id: str = None) -> List[Dict[str, Any]]:
|
108 |
+
"""List projects, optionally filtered by user ID"""
|
109 |
+
if user_id:
|
110 |
+
# Return only projects owned by this user
|
111 |
+
return [project for project in self.projects.values()
|
112 |
+
if project.get('user_id') == user_id]
|
113 |
+
else:
|
114 |
+
# Return all projects (for admin use)
|
115 |
+
return list(self.projects.values())
|
116 |
+
|
117 |
+
|
118 |
+
class SimpleResearchAssistant:
|
119 |
+
"""
|
120 |
+
Simplified research assistant that combines all components
|
121 |
+
"""
|
122 |
+
|
123 |
+
def __init__(self, config: Config = None):
|
124 |
+
self.config = config or Config()
|
125 |
+
|
126 |
+
# Initialize components
|
127 |
+
print("Initializing Research Assistant...")
|
128 |
+
self.groq_processor = GroqProcessor(self.config)
|
129 |
+
self.rag_system = RAGSystem(self.config)
|
130 |
+
self.paper_fetcher = PaperFetcher(self.config)
|
131 |
+
self.pdf_processor = PDFProcessor(self.config)
|
132 |
+
self.project_manager = ProjectManager(self.config)
|
133 |
+
self.trend_monitor = AdvancedTrendMonitor(self.groq_processor)
|
134 |
+
|
135 |
+
print("Research Assistant initialized!")
|
136 |
+
|
137 |
+
# Set up logging
|
138 |
+
logging.basicConfig(level=getattr(logging, self.config.LOG_LEVEL))
|
139 |
+
self.logger = logging.getLogger(__name__)
|
140 |
+
|
141 |
+
def search_papers(self, query: str, max_results: int = 10, sources: List[str] = None) -> List[Dict[str, Any]]:
|
142 |
+
"""
|
143 |
+
Search for papers across multiple sources
|
144 |
+
|
145 |
+
Args:
|
146 |
+
query: Search query
|
147 |
+
max_results: Maximum number of results
|
148 |
+
sources: List of sources to search ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
149 |
+
|
150 |
+
Returns:
|
151 |
+
List of papers
|
152 |
+
"""
|
153 |
+
# Use all sources by default for comprehensive search
|
154 |
+
if sources is None:
|
155 |
+
sources = ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
156 |
+
|
157 |
+
self.logger.info(f"Searching for: {query}")
|
158 |
+
print(f"DEBUG: Starting multi-source search for '{query}' with max_results={max_results}")
|
159 |
+
print(f"DEBUG: Using sources: {sources}")
|
160 |
+
|
161 |
+
try:
|
162 |
+
# Use the unified fetcher for all sources
|
163 |
+
papers = self.paper_fetcher.search_papers(query, max_results, sources=sources)
|
164 |
+
print(f"DEBUG: Unified fetcher returned {len(papers)} papers")
|
165 |
+
|
166 |
+
# Add to RAG system for future querying
|
167 |
+
if papers:
|
168 |
+
try:
|
169 |
+
self.rag_system.add_papers(papers)
|
170 |
+
print("DEBUG: Papers added to RAG system")
|
171 |
+
except Exception as e:
|
172 |
+
print(f"DEBUG: Failed to add papers to RAG system: {e}")
|
173 |
+
|
174 |
+
self.logger.info(f"Found {len(papers)} papers from {len(sources)} sources")
|
175 |
+
print(f"DEBUG: Returning {len(papers)} papers from multi-source search")
|
176 |
+
return papers
|
177 |
+
|
178 |
+
except Exception as e:
|
179 |
+
print(f"DEBUG: Multi-source search failed: {e}")
|
180 |
+
self.logger.error(f"Multi-source search failed: {e}")
|
181 |
+
return []
|
182 |
+
|
183 |
+
def ask_question(self, question: str, context: str = None) -> Dict[str, Any]:
|
184 |
+
"""
|
185 |
+
Answer a research question using RAG
|
186 |
+
|
187 |
+
Args:
|
188 |
+
question: Research question
|
189 |
+
context: Optional context
|
190 |
+
|
191 |
+
Returns:
|
192 |
+
Answer with sources
|
193 |
+
"""
|
194 |
+
self.logger.info(f"Answering question: {question}")
|
195 |
+
|
196 |
+
# Use RAG system if available
|
197 |
+
if self.rag_system.vectorstore:
|
198 |
+
return self.rag_system.answer_question(question)
|
199 |
+
else:
|
200 |
+
# Fallback to direct LLM
|
201 |
+
answer = self.groq_processor.answer_question(question, context or "")
|
202 |
+
return {
|
203 |
+
'answer': answer,
|
204 |
+
'sources': [],
|
205 |
+
'method': 'direct_llm'
|
206 |
+
}
|
207 |
+
|
208 |
+
def process_pdf(self, file_path: str) -> Dict[str, Any]:
|
209 |
+
"""
|
210 |
+
Process a PDF file
|
211 |
+
|
212 |
+
Args:
|
213 |
+
file_path: Path to PDF file
|
214 |
+
|
215 |
+
Returns:
|
216 |
+
Processing result
|
217 |
+
"""
|
218 |
+
self.logger.info(f"Processing PDF: {file_path}")
|
219 |
+
|
220 |
+
# Extract text
|
221 |
+
extraction_result = self.pdf_processor.extract_text_from_file(file_path)
|
222 |
+
|
223 |
+
if extraction_result.get('error'):
|
224 |
+
return {'success': False, 'error': extraction_result['error']}
|
225 |
+
|
226 |
+
text = extraction_result.get('text', '')
|
227 |
+
|
228 |
+
# Extract basic information
|
229 |
+
title = self._extract_title_from_text(text)
|
230 |
+
abstract = self._extract_abstract_from_text(text)
|
231 |
+
|
232 |
+
# Generate summary using Groq
|
233 |
+
summary = self.groq_processor.summarize_paper(title, abstract, text)
|
234 |
+
|
235 |
+
# Create paper object
|
236 |
+
paper = {
|
237 |
+
'title': title,
|
238 |
+
'abstract': abstract,
|
239 |
+
'content': text,
|
240 |
+
'summary': summary,
|
241 |
+
'source': 'uploaded_pdf',
|
242 |
+
'file_path': file_path,
|
243 |
+
'processed_at': datetime.now().isoformat(),
|
244 |
+
'metadata': extraction_result.get('metadata', {})
|
245 |
+
}
|
246 |
+
|
247 |
+
# Try to add to RAG system (don't fail if RAG is not initialized)
|
248 |
+
try:
|
249 |
+
self.rag_system.add_papers([paper])
|
250 |
+
except Exception as e:
|
251 |
+
self.logger.warning(f"Could not add paper to RAG system: {e}")
|
252 |
+
|
253 |
+
# Return formatted response with all expected fields
|
254 |
+
return {
|
255 |
+
'success': True,
|
256 |
+
'title': title,
|
257 |
+
'abstract': abstract,
|
258 |
+
'text_length': len(text),
|
259 |
+
'processed_at': datetime.now().isoformat(),
|
260 |
+
'summary': summary,
|
261 |
+
'paper': paper,
|
262 |
+
'word_count': extraction_result.get('word_count', 0),
|
263 |
+
'pages': extraction_result.get('metadata', {}).get('pages', 0)
|
264 |
+
}
|
265 |
+
|
266 |
+
def analyze_trends(self, topic: str, max_papers: int = 50) -> Dict[str, Any]:
|
267 |
+
"""
|
268 |
+
Analyze research trends for a topic using advanced trend monitoring
|
269 |
+
|
270 |
+
Args:
|
271 |
+
topic: Research topic
|
272 |
+
max_papers: Maximum papers to analyze
|
273 |
+
|
274 |
+
Returns:
|
275 |
+
Advanced trend analysis
|
276 |
+
"""
|
277 |
+
self.logger.info(f"Analyzing trends for: {topic}")
|
278 |
+
print(f"📊 Starting advanced trend analysis for '{topic}'")
|
279 |
+
|
280 |
+
# Get papers from multiple sources for comprehensive analysis
|
281 |
+
papers = self.search_papers(topic, max_papers)
|
282 |
+
|
283 |
+
if not papers:
|
284 |
+
return {'error': 'No papers found for trend analysis'}
|
285 |
+
|
286 |
+
print(f"📊 Found {len(papers)} papers for trend analysis")
|
287 |
+
|
288 |
+
# Use advanced trend monitor for comprehensive analysis
|
289 |
+
trend_report = self.trend_monitor.generate_trend_report(papers)
|
290 |
+
|
291 |
+
# Add metadata
|
292 |
+
trend_report['query_metadata'] = {
|
293 |
+
'topic': topic,
|
294 |
+
'papers_analyzed': len(papers),
|
295 |
+
'analysis_date': datetime.now().isoformat(),
|
296 |
+
'analysis_type': 'advanced_trend_monitoring'
|
297 |
+
}
|
298 |
+
|
299 |
+
return trend_report
|
300 |
+
|
301 |
+
def create_project(self, name: str, research_question: str, keywords: List[str], user_id: str) -> str:
|
302 |
+
"""Create a new research project"""
|
303 |
+
return self.project_manager.create_project(name, research_question, keywords, user_id)
|
304 |
+
|
305 |
+
def get_project(self, project_id: str, user_id: str = None) -> Optional[Dict[str, Any]]:
|
306 |
+
"""Get a project by ID"""
|
307 |
+
return self.project_manager.get_project(project_id, user_id)
|
308 |
+
|
309 |
+
def list_projects(self, user_id: str = None) -> List[Dict[str, Any]]:
|
310 |
+
"""List projects"""
|
311 |
+
return self.project_manager.list_projects(user_id)
|
312 |
+
|
313 |
+
def conduct_literature_search(self, project_id: str, max_papers: int = 20, user_id: str = None) -> Dict[str, Any]:
|
314 |
+
"""
|
315 |
+
Conduct literature search for a project
|
316 |
+
|
317 |
+
Args:
|
318 |
+
project_id: Project ID
|
319 |
+
max_papers: Maximum papers to find
|
320 |
+
user_id: User ID to check ownership
|
321 |
+
|
322 |
+
Returns:
|
323 |
+
Search results
|
324 |
+
"""
|
325 |
+
project = self.project_manager.get_project(project_id, user_id)
|
326 |
+
if not project:
|
327 |
+
return {'error': 'Project not found or access denied'}
|
328 |
+
|
329 |
+
# Build search query
|
330 |
+
query = f"{project['research_question']} {' '.join(project['keywords'])}"
|
331 |
+
|
332 |
+
# Search for papers
|
333 |
+
papers = self.search_papers(query, max_papers)
|
334 |
+
|
335 |
+
# Add papers to project
|
336 |
+
for paper in papers:
|
337 |
+
self.project_manager.add_paper_to_project(project_id, paper, user_id)
|
338 |
+
|
339 |
+
return {
|
340 |
+
'project_id': project_id,
|
341 |
+
'papers_found': len(papers),
|
342 |
+
'papers': papers
|
343 |
+
}
|
344 |
+
|
345 |
+
def generate_literature_review(self, project_id: str, user_id: str = None) -> Dict[str, Any]:
|
346 |
+
"""
|
347 |
+
Generate a literature review for a project
|
348 |
+
|
349 |
+
Args:
|
350 |
+
project_id: Project ID
|
351 |
+
user_id: User ID to check ownership
|
352 |
+
|
353 |
+
Returns:
|
354 |
+
Literature review
|
355 |
+
"""
|
356 |
+
try:
|
357 |
+
project = self.project_manager.get_project(project_id, user_id)
|
358 |
+
if not project:
|
359 |
+
return {'error': 'Project not found or access denied'}
|
360 |
+
|
361 |
+
papers = project.get('papers', [])
|
362 |
+
if not papers:
|
363 |
+
return {'error': 'No papers found in project'}
|
364 |
+
|
365 |
+
print(f"Generating review for project {project_id} with {len(papers)} papers...")
|
366 |
+
|
367 |
+
# Generate review
|
368 |
+
review_content = self.groq_processor.generate_literature_review(
|
369 |
+
papers,
|
370 |
+
project['research_question']
|
371 |
+
)
|
372 |
+
|
373 |
+
print(f"Review generated, length: {len(review_content) if review_content else 0}")
|
374 |
+
|
375 |
+
if not review_content or review_content.startswith("Error"):
|
376 |
+
return {'error': f'Failed to generate review: {review_content}'}
|
377 |
+
|
378 |
+
return {
|
379 |
+
'project_id': project_id,
|
380 |
+
'review': {
|
381 |
+
'content': review_content,
|
382 |
+
'papers_count': len(papers),
|
383 |
+
'research_question': project['research_question']
|
384 |
+
},
|
385 |
+
'papers_reviewed': len(papers),
|
386 |
+
'generated_at': datetime.now().isoformat()
|
387 |
+
}
|
388 |
+
except Exception as e:
|
389 |
+
print(f"Error in generate_literature_review: {str(e)}")
|
390 |
+
return {'error': f'Unexpected error: {str(e)}'}
|
391 |
+
|
392 |
+
|
393 |
+
def get_system_status(self) -> Dict[str, Any]:
|
394 |
+
"""Get system status"""
|
395 |
+
return {
|
396 |
+
'status': 'operational',
|
397 |
+
'components': {
|
398 |
+
'groq_processor': 'ready',
|
399 |
+
'rag_system': 'ready',
|
400 |
+
'arxiv_fetcher': 'ready',
|
401 |
+
'pdf_processor': 'ready',
|
402 |
+
'project_manager': 'ready'
|
403 |
+
},
|
404 |
+
'statistics': {
|
405 |
+
'rag_documents': self.rag_system.get_database_stats().get('total_chunks', 0),
|
406 |
+
'system_version': '2.0.0',
|
407 |
+
'status_check_time': datetime.now().isoformat()
|
408 |
+
},
|
409 |
+
'config': self.config.get_summary()
|
410 |
+
}
|
411 |
+
|
412 |
+
def _extract_title_from_text(self, text: str) -> str:
|
413 |
+
"""Extract title from PDF text"""
|
414 |
+
lines = text.split('\n')[:20] # Check first 20 lines
|
415 |
+
|
416 |
+
for line in lines:
|
417 |
+
line = line.strip()
|
418 |
+
if len(line) > 10 and len(line) < 200:
|
419 |
+
# Skip lines that look like headers or metadata
|
420 |
+
if not any(keyword in line.lower() for keyword in ['page', 'arxiv', 'doi', 'submitted', 'accepted']):
|
421 |
+
return line
|
422 |
+
|
423 |
+
return "Unknown Title"
|
424 |
+
|
425 |
+
def _extract_abstract_from_text(self, text: str) -> str:
|
426 |
+
"""Extract abstract from PDF text"""
|
427 |
+
text_lower = text.lower()
|
428 |
+
|
429 |
+
# Look for abstract section
|
430 |
+
abstract_start = text_lower.find('abstract')
|
431 |
+
if abstract_start != -1:
|
432 |
+
# Find the end of abstract (usually next section)
|
433 |
+
abstract_text = text[abstract_start:]
|
434 |
+
|
435 |
+
# Look for common section headers that might follow abstract
|
436 |
+
section_headers = ['introduction', '1. introduction', '1 introduction', 'keywords', 'key words']
|
437 |
+
|
438 |
+
end_pos = len(abstract_text)
|
439 |
+
for header in section_headers:
|
440 |
+
pos = abstract_text.lower().find(header)
|
441 |
+
if pos != -1 and pos < end_pos:
|
442 |
+
end_pos = pos
|
443 |
+
|
444 |
+
abstract = abstract_text[:end_pos]
|
445 |
+
|
446 |
+
# Clean up
|
447 |
+
abstract = abstract.replace('abstract', '', 1).strip()
|
448 |
+
if len(abstract) > 1000:
|
449 |
+
abstract = abstract[:1000] + "..."
|
450 |
+
|
451 |
+
return abstract
|
452 |
+
|
453 |
+
return "Abstract not found"
|
454 |
+
|
455 |
+
|
456 |
+
class ResearchMate:
|
457 |
+
"""
|
458 |
+
Main ResearchMate interface
|
459 |
+
Simplified wrapper around the research assistant
|
460 |
+
"""
|
461 |
+
|
462 |
+
def __init__(self, config: Config = None):
|
463 |
+
self.config = config or Config()
|
464 |
+
self.assistant = SimpleResearchAssistant(self.config)
|
465 |
+
self.version = "2.0.0"
|
466 |
+
self.initialized_at = datetime.now().isoformat()
|
467 |
+
|
468 |
+
print(f"ResearchMate {self.version} initialized!")
|
469 |
+
|
470 |
+
def search(self, query: str, max_results: int = 10) -> Dict[str, Any]:
|
471 |
+
"""Search for papers"""
|
472 |
+
try:
|
473 |
+
papers = self.assistant.search_papers(query, max_results)
|
474 |
+
return {
|
475 |
+
'success': True,
|
476 |
+
'query': query,
|
477 |
+
'papers': papers,
|
478 |
+
'count': len(papers)
|
479 |
+
}
|
480 |
+
except Exception as e:
|
481 |
+
return {'success': False, 'error': str(e)}
|
482 |
+
|
483 |
+
def ask(self, question: str) -> Dict[str, Any]:
|
484 |
+
"""Ask a research question"""
|
485 |
+
try:
|
486 |
+
result = self.assistant.ask_question(question)
|
487 |
+
return {
|
488 |
+
'success': True,
|
489 |
+
'question': question,
|
490 |
+
'answer': result['answer'],
|
491 |
+
'sources': result.get('sources', [])
|
492 |
+
}
|
493 |
+
except Exception as e:
|
494 |
+
return {'success': False, 'error': str(e)}
|
495 |
+
|
496 |
+
def upload_pdf(self, file_path: str) -> Dict[str, Any]:
|
497 |
+
"""Process uploaded PDF"""
|
498 |
+
try:
|
499 |
+
result = self.assistant.process_pdf(file_path)
|
500 |
+
return result
|
501 |
+
except Exception as e:
|
502 |
+
return {'success': False, 'error': str(e)}
|
503 |
+
|
504 |
+
def analyze_trends(self, topic: str) -> Dict[str, Any]:
|
505 |
+
"""Analyze research trends"""
|
506 |
+
try:
|
507 |
+
result = self.assistant.analyze_trends(topic)
|
508 |
+
return {'success': True, **result}
|
509 |
+
except Exception as e:
|
510 |
+
return {'success': False, 'error': str(e)}
|
511 |
+
|
512 |
+
def create_project(self, name: str, research_question: str, keywords: List[str], user_id: str) -> Dict[str, Any]:
|
513 |
+
"""Create research project"""
|
514 |
+
try:
|
515 |
+
project_id = self.assistant.create_project(name, research_question, keywords, user_id)
|
516 |
+
return {
|
517 |
+
'success': True,
|
518 |
+
'project_id': project_id,
|
519 |
+
'message': f'Project "{name}" created successfully'
|
520 |
+
}
|
521 |
+
except Exception as e:
|
522 |
+
return {'success': False, 'error': str(e)}
|
523 |
+
|
524 |
+
def get_project(self, project_id: str, user_id: str = None) -> Dict[str, Any]:
|
525 |
+
"""Get project details"""
|
526 |
+
try:
|
527 |
+
project = self.assistant.get_project(project_id, user_id)
|
528 |
+
if project:
|
529 |
+
return {'success': True, 'project': project}
|
530 |
+
else:
|
531 |
+
return {'success': False, 'error': 'Project not found or access denied'}
|
532 |
+
except Exception as e:
|
533 |
+
return {'success': False, 'error': str(e)}
|
534 |
+
|
535 |
+
def list_projects(self, user_id: str = None) -> Dict[str, Any]:
|
536 |
+
"""List projects"""
|
537 |
+
try:
|
538 |
+
projects = self.assistant.list_projects(user_id)
|
539 |
+
return {'success': True, 'projects': projects}
|
540 |
+
except Exception as e:
|
541 |
+
return {'success': False, 'error': str(e)}
|
542 |
+
|
543 |
+
def search_project_literature(self, project_id: str, max_papers: int = 20, user_id: str = None) -> Dict[str, Any]:
|
544 |
+
"""Search literature for a project"""
|
545 |
+
try:
|
546 |
+
result = self.assistant.conduct_literature_search(project_id, max_papers, user_id)
|
547 |
+
return {'success': True, **result}
|
548 |
+
except Exception as e:
|
549 |
+
return {'success': False, 'error': str(e)}
|
550 |
+
|
551 |
+
def generate_review(self, project_id: str, user_id: str = None) -> Dict[str, Any]:
|
552 |
+
"""Generate literature review for a project"""
|
553 |
+
try:
|
554 |
+
result = self.assistant.generate_literature_review(project_id, user_id)
|
555 |
+
return {'success': True, **result}
|
556 |
+
except Exception as e:
|
557 |
+
return {'success': False, 'error': str(e)}
|
558 |
+
|
559 |
+
def get_status(self) -> Dict[str, Any]:
|
560 |
+
"""Get system status"""
|
561 |
+
try:
|
562 |
+
status = self.assistant.get_system_status()
|
563 |
+
return {'success': True, **status}
|
564 |
+
except Exception as e:
|
565 |
+
return {'success': False, 'error': str(e)}
|
566 |
+
|
567 |
+
def analyze_project(self, project_id: str, user_id: str = None) -> Dict[str, Any]:
|
568 |
+
"""Analyze project literature"""
|
569 |
+
try:
|
570 |
+
project = self.assistant.get_project(project_id, user_id)
|
571 |
+
if not project:
|
572 |
+
return {'success': False, 'error': 'Project not found or access denied'}
|
573 |
+
|
574 |
+
# Basic project analysis
|
575 |
+
papers = project.get('papers', [])
|
576 |
+
if not papers:
|
577 |
+
return {'success': False, 'error': 'No papers found in project'}
|
578 |
+
|
579 |
+
# Helper function to safely extract year
|
580 |
+
def safe_year(paper):
|
581 |
+
year = paper.get('year')
|
582 |
+
if year is None:
|
583 |
+
return None
|
584 |
+
try:
|
585 |
+
if isinstance(year, str):
|
586 |
+
year = int(year)
|
587 |
+
if isinstance(year, int) and 1900 <= year <= 2030:
|
588 |
+
return year
|
589 |
+
except (ValueError, TypeError):
|
590 |
+
pass
|
591 |
+
return None
|
592 |
+
|
593 |
+
# Analyze papers
|
594 |
+
total_papers = len(papers)
|
595 |
+
|
596 |
+
# Process years more safely
|
597 |
+
years = [safe_year(p) for p in papers]
|
598 |
+
years = [y for y in years if y is not None]
|
599 |
+
|
600 |
+
authors = []
|
601 |
+
for p in papers:
|
602 |
+
if p.get('authors'):
|
603 |
+
if isinstance(p.get('authors'), list):
|
604 |
+
authors.extend(p.get('authors'))
|
605 |
+
elif isinstance(p.get('authors'), str):
|
606 |
+
authors.append(p.get('authors'))
|
607 |
+
|
608 |
+
# Extract key topics from keywords and titles
|
609 |
+
all_keywords = []
|
610 |
+
for p in papers:
|
611 |
+
if p.get('keywords'):
|
612 |
+
if isinstance(p.get('keywords'), list):
|
613 |
+
all_keywords.extend(p.get('keywords'))
|
614 |
+
elif isinstance(p.get('keywords'), str):
|
615 |
+
all_keywords.extend(p.get('keywords').split(','))
|
616 |
+
|
617 |
+
# Calculate year range safely
|
618 |
+
year_range = "Unknown"
|
619 |
+
if years:
|
620 |
+
min_year = min(years)
|
621 |
+
max_year = max(years)
|
622 |
+
year_range = f"{min_year} - {max_year}" if min_year != max_year else str(min_year)
|
623 |
+
|
624 |
+
# Count recent papers safely
|
625 |
+
recent_papers_count = len([p for p in papers if safe_year(p) is not None and safe_year(p) >= 2020])
|
626 |
+
|
627 |
+
# Basic analysis
|
628 |
+
analysis = {
|
629 |
+
'total_papers': total_papers,
|
630 |
+
'year_range': year_range,
|
631 |
+
'unique_authors': len(set(authors)) if authors else 0,
|
632 |
+
'top_authors': list(set(authors))[:10] if authors else [],
|
633 |
+
'key_topics': list(set([k.strip().lower() for k in all_keywords if k.strip()]))[:10] if all_keywords else [],
|
634 |
+
'recent_papers': [p for p in papers if safe_year(p) is not None and safe_year(p) >= 2020][:5],
|
635 |
+
'trends': f"Based on {total_papers} papers" + (f" spanning {year_range}" if years else ""),
|
636 |
+
'insights': f"""## Key Research Insights
|
637 |
+
|
638 |
+
**Total Literature:** {total_papers} papers analyzed
|
639 |
+
|
640 |
+
**Research Scope:** {"Multi-year analysis spanning " + str(len(set(years))) + " different years" if len(years) > 1 else "Limited temporal scope"}
|
641 |
+
|
642 |
+
**Author Collaboration:** {len(set(authors))} unique researchers identified
|
643 |
+
|
644 |
+
**Key Themes:** {', '.join(list(set([k.strip().title() for k in all_keywords if k.strip()]))[:5]) if all_keywords else 'No specific themes identified'}
|
645 |
+
|
646 |
+
**Research Activity:** {"Active research area" if total_papers > 10 else "Emerging research area"}
|
647 |
+
""",
|
648 |
+
'summary': f"""## Literature Analysis Summary
|
649 |
+
|
650 |
+
This project contains **{total_papers} research papers**{f" published between {year_range}" if years else ""}.
|
651 |
+
|
652 |
+
**Research Community:** The work involves {len(set(authors))} unique authors{f", with top contributors including {', '.join(list(set(authors))[:3])}" if len(authors) >= 3 else ""}.
|
653 |
+
|
654 |
+
**Research Focus:** {"The literature covers diverse topics including " + ', '.join(list(set([k.strip().title() for k in all_keywords if k.strip()]))[:5]) if all_keywords else "The research focus requires further analysis based on paper content"}.
|
655 |
+
|
656 |
+
**Temporal Distribution:** {"Recent research activity is strong" if recent_papers_count > total_papers * 0.5 else "Includes both historical and recent contributions"}.
|
657 |
+
|
658 |
+
**Research Maturity:** {"Well-established research area" if total_papers > 20 else "Growing research area"} with {"strong" if len(set(authors)) > 15 else "moderate"} community engagement.
|
659 |
+
"""
|
660 |
+
}
|
661 |
+
|
662 |
+
return {
|
663 |
+
'success': True,
|
664 |
+
'project_id': project_id,
|
665 |
+
'analysis': analysis,
|
666 |
+
'timestamp': datetime.now().isoformat()
|
667 |
+
}
|
668 |
+
except Exception as e:
|
669 |
+
return {'success': False, 'error': str(e)}
|
670 |
+
|
671 |
+
def ask_project_question(self, project_id: str, question: str) -> Dict[str, Any]:
|
672 |
+
"""Ask a question about a specific project"""
|
673 |
+
try:
|
674 |
+
project = self.assistant.get_project(project_id)
|
675 |
+
if not project:
|
676 |
+
return {'success': False, 'error': 'Project not found'}
|
677 |
+
|
678 |
+
# Context-aware question answering
|
679 |
+
context = f"Project: {project.get('name', '')}\n"
|
680 |
+
context += f"Research Question: {project.get('research_question', '')}\n"
|
681 |
+
context += f"Keywords: {', '.join(project.get('keywords', []))}\n"
|
682 |
+
|
683 |
+
# Use RAG system with project context
|
684 |
+
full_question = f"Context: {context}\n\nQuestion: {question}"
|
685 |
+
result = self.assistant.ask_question(full_question)
|
686 |
+
|
687 |
+
return {
|
688 |
+
'success': True,
|
689 |
+
'project_id': project_id,
|
690 |
+
'question': question,
|
691 |
+
'answer': result['answer'],
|
692 |
+
'sources': result.get('sources', [])
|
693 |
+
}
|
694 |
+
except Exception as e:
|
695 |
+
return {'success': False, 'error': str(e)}
|
696 |
+
|
697 |
+
@property
|
698 |
+
def trend_monitor(self):
|
699 |
+
"""Access to the advanced trend monitor"""
|
700 |
+
return self.assistant.trend_monitor
|
701 |
+
|
702 |
+
def search_papers(self, query: str, max_results: int = 10):
|
703 |
+
"""Direct access to paper search"""
|
704 |
+
return self.assistant.search_papers(query, max_results)
|
src/components/trend_monitor.py
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Advanced Research Trend Monitor - Web App Version
|
3 |
+
Based on the notebook implementation with enhanced features
|
4 |
+
"""
|
5 |
+
|
6 |
+
import json
|
7 |
+
import time
|
8 |
+
from datetime import datetime, timedelta
|
9 |
+
from typing import List, Dict, Any, Optional
|
10 |
+
from collections import defaultdict, Counter
|
11 |
+
import re
|
12 |
+
|
13 |
+
# Optional imports for advanced features
|
14 |
+
try:
|
15 |
+
import networkx as nx
|
16 |
+
HAS_NETWORKX = True
|
17 |
+
except ImportError:
|
18 |
+
HAS_NETWORKX = False
|
19 |
+
print("⚠️ NetworkX not available - some advanced features disabled")
|
20 |
+
|
21 |
+
try:
|
22 |
+
import matplotlib.pyplot as plt
|
23 |
+
import seaborn as sns
|
24 |
+
HAS_PLOTTING = True
|
25 |
+
except ImportError:
|
26 |
+
HAS_PLOTTING = False
|
27 |
+
print("⚠️ Matplotlib/Seaborn not available - plotting features disabled")
|
28 |
+
|
29 |
+
try:
|
30 |
+
from wordcloud import WordCloud
|
31 |
+
HAS_WORDCLOUD = True
|
32 |
+
except ImportError:
|
33 |
+
HAS_WORDCLOUD = False
|
34 |
+
print("⚠️ WordCloud not available - word cloud features disabled")
|
35 |
+
|
36 |
+
try:
|
37 |
+
import numpy as np
|
38 |
+
HAS_NUMPY = True
|
39 |
+
except ImportError:
|
40 |
+
HAS_NUMPY = False
|
41 |
+
print("⚠️ NumPy not available - some numerical features disabled")
|
42 |
+
|
43 |
+
class AdvancedTrendMonitor:
|
44 |
+
"""Advanced research trend monitoring with temporal analysis and gap detection"""
|
45 |
+
|
46 |
+
def __init__(self, groq_processor=None):
|
47 |
+
self.groq_processor = groq_processor
|
48 |
+
self.trend_data = {}
|
49 |
+
self.keyword_trends = defaultdict(list)
|
50 |
+
self.temporal_data = defaultdict(list)
|
51 |
+
self.gap_analysis_cache = {}
|
52 |
+
print("✅ Advanced Research Trend Monitor initialized!")
|
53 |
+
|
54 |
+
def analyze_temporal_trends(self, papers: List[Dict], timeframe: str = "yearly") -> Dict:
|
55 |
+
"""Analyze trends over time with sophisticated temporal analysis"""
|
56 |
+
try:
|
57 |
+
if not papers:
|
58 |
+
return {'error': 'No papers provided for temporal analysis'}
|
59 |
+
|
60 |
+
# Group papers by time period
|
61 |
+
temporal_groups = defaultdict(list)
|
62 |
+
year_counts = defaultdict(int)
|
63 |
+
keyword_evolution = defaultdict(lambda: defaultdict(int))
|
64 |
+
|
65 |
+
for paper in papers:
|
66 |
+
year = paper.get('year')
|
67 |
+
if not year:
|
68 |
+
continue
|
69 |
+
|
70 |
+
# Handle different year formats
|
71 |
+
if isinstance(year, str):
|
72 |
+
try:
|
73 |
+
year = int(year)
|
74 |
+
except ValueError:
|
75 |
+
continue
|
76 |
+
|
77 |
+
if year < 1990 or year > 2030: # Filter unrealistic years
|
78 |
+
continue
|
79 |
+
|
80 |
+
temporal_groups[year].append(paper)
|
81 |
+
year_counts[year] += 1
|
82 |
+
|
83 |
+
# Track keyword evolution
|
84 |
+
title = paper.get('title', '').lower()
|
85 |
+
abstract = paper.get('abstract', '').lower()
|
86 |
+
content = f"{title} {abstract}"
|
87 |
+
|
88 |
+
# Extract keywords (simple approach)
|
89 |
+
keywords = self._extract_keywords(content)
|
90 |
+
for keyword in keywords:
|
91 |
+
keyword_evolution[year][keyword] += 1
|
92 |
+
|
93 |
+
# Calculate trends
|
94 |
+
trends = {
|
95 |
+
'publication_trend': dict(sorted(year_counts.items())),
|
96 |
+
'keyword_evolution': dict(keyword_evolution),
|
97 |
+
'temporal_analysis': {},
|
98 |
+
'growth_analysis': {},
|
99 |
+
'emerging_topics': {},
|
100 |
+
'declining_topics': {}
|
101 |
+
}
|
102 |
+
|
103 |
+
# Analyze publication growth
|
104 |
+
years = sorted(year_counts.keys())
|
105 |
+
if len(years) >= 2:
|
106 |
+
recent_years = years[-3:] # Last 3 years
|
107 |
+
earlier_years = years[:-3] if len(years) > 3 else years[:-1]
|
108 |
+
|
109 |
+
recent_avg = sum(year_counts[y] for y in recent_years) / len(recent_years)
|
110 |
+
earlier_avg = sum(year_counts[y] for y in earlier_years) / len(earlier_years) if earlier_years else 0
|
111 |
+
|
112 |
+
growth_rate = ((recent_avg - earlier_avg) / earlier_avg * 100) if earlier_avg > 0 else 0
|
113 |
+
|
114 |
+
trends['growth_analysis'] = {
|
115 |
+
'recent_average': recent_avg,
|
116 |
+
'earlier_average': earlier_avg,
|
117 |
+
'growth_rate_percent': growth_rate,
|
118 |
+
'trend_direction': 'growing' if growth_rate > 5 else 'declining' if growth_rate < -5 else 'stable'
|
119 |
+
}
|
120 |
+
|
121 |
+
# Analyze emerging vs declining topics
|
122 |
+
if len(years) >= 2:
|
123 |
+
recent_year = years[-1]
|
124 |
+
previous_year = years[-2] if len(years) > 1 else years[-1]
|
125 |
+
|
126 |
+
recent_keywords = set(keyword_evolution[recent_year].keys())
|
127 |
+
previous_keywords = set(keyword_evolution[previous_year].keys())
|
128 |
+
|
129 |
+
emerging = recent_keywords - previous_keywords
|
130 |
+
declining = previous_keywords - recent_keywords
|
131 |
+
|
132 |
+
trends['emerging_topics'] = {
|
133 |
+
'topics': list(emerging)[:10], # Top 10 emerging
|
134 |
+
'count': len(emerging)
|
135 |
+
}
|
136 |
+
|
137 |
+
trends['declining_topics'] = {
|
138 |
+
'topics': list(declining)[:10], # Top 10 declining
|
139 |
+
'count': len(declining)
|
140 |
+
}
|
141 |
+
|
142 |
+
# Temporal analysis summary
|
143 |
+
trends['temporal_analysis'] = {
|
144 |
+
'total_years': len(years),
|
145 |
+
'year_range': f"{min(years)}-{max(years)}" if years else "N/A",
|
146 |
+
'peak_year': max(year_counts.items(), key=lambda x: x[1])[0] if year_counts else None,
|
147 |
+
'total_papers': sum(year_counts.values()),
|
148 |
+
'average_per_year': sum(year_counts.values()) / len(years) if years else 0
|
149 |
+
}
|
150 |
+
|
151 |
+
return trends
|
152 |
+
|
153 |
+
except Exception as e:
|
154 |
+
return {
|
155 |
+
'error': f'Temporal trend analysis failed: {str(e)}',
|
156 |
+
'analysis_timestamp': datetime.now().isoformat()
|
157 |
+
}
|
158 |
+
|
159 |
+
def detect_research_gaps(self, papers: List[Dict]) -> Dict:
|
160 |
+
"""Detect research gaps using advanced analysis"""
|
161 |
+
try:
|
162 |
+
if not papers:
|
163 |
+
return {'error': 'No papers provided for gap analysis'}
|
164 |
+
|
165 |
+
# Analyze methodologies
|
166 |
+
methodologies = defaultdict(int)
|
167 |
+
research_areas = defaultdict(int)
|
168 |
+
data_types = defaultdict(int)
|
169 |
+
evaluation_methods = defaultdict(int)
|
170 |
+
|
171 |
+
# Common research area keywords
|
172 |
+
area_keywords = {
|
173 |
+
'natural_language_processing': ['nlp', 'language', 'text', 'linguistic'],
|
174 |
+
'computer_vision': ['vision', 'image', 'visual', 'cv'],
|
175 |
+
'machine_learning': ['ml', 'learning', 'algorithm', 'model'],
|
176 |
+
'deep_learning': ['deep', 'neural', 'network', 'cnn', 'rnn'],
|
177 |
+
'reinforcement_learning': ['reinforcement', 'rl', 'agent', 'policy'],
|
178 |
+
'robotics': ['robot', 'robotic', 'manipulation', 'control'],
|
179 |
+
'healthcare': ['medical', 'health', 'clinical', 'patient'],
|
180 |
+
'finance': ['financial', 'trading', 'market', 'economic'],
|
181 |
+
'security': ['security', 'privacy', 'attack', 'defense']
|
182 |
+
}
|
183 |
+
|
184 |
+
# Methodology keywords
|
185 |
+
method_keywords = {
|
186 |
+
'supervised_learning': ['supervised', 'classification', 'regression'],
|
187 |
+
'unsupervised_learning': ['unsupervised', 'clustering', 'dimensionality'],
|
188 |
+
'semi_supervised': ['semi-supervised', 'few-shot', 'zero-shot'],
|
189 |
+
'transfer_learning': ['transfer', 'domain adaptation', 'fine-tuning'],
|
190 |
+
'federated_learning': ['federated', 'distributed', 'decentralized'],
|
191 |
+
'meta_learning': ['meta', 'learning to learn', 'few-shot'],
|
192 |
+
'explainable_ai': ['explainable', 'interpretable', 'explanation'],
|
193 |
+
'adversarial': ['adversarial', 'robust', 'attack']
|
194 |
+
}
|
195 |
+
|
196 |
+
# Analyze papers
|
197 |
+
for paper in papers:
|
198 |
+
content = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
|
199 |
+
|
200 |
+
# Count research areas
|
201 |
+
for area, keywords in area_keywords.items():
|
202 |
+
if any(keyword in content for keyword in keywords):
|
203 |
+
research_areas[area] += 1
|
204 |
+
|
205 |
+
# Count methodologies
|
206 |
+
for method, keywords in method_keywords.items():
|
207 |
+
if any(keyword in content for keyword in keywords):
|
208 |
+
methodologies[method] += 1
|
209 |
+
|
210 |
+
# Identify data types
|
211 |
+
if 'dataset' in content or 'data' in content:
|
212 |
+
if any(word in content for word in ['text', 'corpus', 'language']):
|
213 |
+
data_types['text'] += 1
|
214 |
+
elif any(word in content for word in ['image', 'visual', 'video']):
|
215 |
+
data_types['image'] += 1
|
216 |
+
elif any(word in content for word in ['audio', 'speech', 'sound']):
|
217 |
+
data_types['audio'] += 1
|
218 |
+
elif any(word in content for word in ['sensor', 'iot', 'time series']):
|
219 |
+
data_types['sensor'] += 1
|
220 |
+
else:
|
221 |
+
data_types['tabular'] += 1
|
222 |
+
|
223 |
+
# Identify gaps
|
224 |
+
gaps = {
|
225 |
+
'methodology_gaps': [],
|
226 |
+
'research_area_gaps': [],
|
227 |
+
'data_type_gaps': [],
|
228 |
+
'interdisciplinary_gaps': [],
|
229 |
+
'emerging_gaps': []
|
230 |
+
}
|
231 |
+
|
232 |
+
# Find underexplored methodologies
|
233 |
+
total_papers = len(papers)
|
234 |
+
for method, count in methodologies.items():
|
235 |
+
coverage = (count / total_papers) * 100
|
236 |
+
if coverage < 5: # Less than 5% coverage
|
237 |
+
gaps['methodology_gaps'].append({
|
238 |
+
'method': method.replace('_', ' ').title(),
|
239 |
+
'coverage_percent': coverage,
|
240 |
+
'papers_count': count
|
241 |
+
})
|
242 |
+
|
243 |
+
# Find underexplored research areas
|
244 |
+
for area, count in research_areas.items():
|
245 |
+
coverage = (count / total_papers) * 100
|
246 |
+
if coverage < 10: # Less than 10% coverage
|
247 |
+
gaps['research_area_gaps'].append({
|
248 |
+
'area': area.replace('_', ' ').title(),
|
249 |
+
'coverage_percent': coverage,
|
250 |
+
'papers_count': count
|
251 |
+
})
|
252 |
+
|
253 |
+
# Find underexplored data types
|
254 |
+
for dtype, count in data_types.items():
|
255 |
+
coverage = (count / total_papers) * 100
|
256 |
+
if coverage < 15: # Less than 15% coverage
|
257 |
+
gaps['data_type_gaps'].append({
|
258 |
+
'data_type': dtype.replace('_', ' ').title(),
|
259 |
+
'coverage_percent': coverage,
|
260 |
+
'papers_count': count
|
261 |
+
})
|
262 |
+
|
263 |
+
# Generate AI-powered gap analysis
|
264 |
+
if self.groq_processor:
|
265 |
+
ai_analysis = self._generate_ai_gap_analysis(papers, gaps)
|
266 |
+
gaps['ai_analysis'] = ai_analysis
|
267 |
+
|
268 |
+
gaps['analysis_summary'] = {
|
269 |
+
'total_papers_analyzed': total_papers,
|
270 |
+
'methodology_gaps_found': len(gaps['methodology_gaps']),
|
271 |
+
'research_area_gaps_found': len(gaps['research_area_gaps']),
|
272 |
+
'data_type_gaps_found': len(gaps['data_type_gaps']),
|
273 |
+
'analysis_timestamp': datetime.now().isoformat()
|
274 |
+
}
|
275 |
+
|
276 |
+
return gaps
|
277 |
+
|
278 |
+
except Exception as e:
|
279 |
+
return {
|
280 |
+
'error': f'Gap detection failed: {str(e)}',
|
281 |
+
'analysis_timestamp': datetime.now().isoformat()
|
282 |
+
}
|
283 |
+
|
284 |
+
def generate_trend_report(self, papers: List[Dict]) -> Dict:
|
285 |
+
"""Generate comprehensive trend report"""
|
286 |
+
try:
|
287 |
+
if not papers:
|
288 |
+
return {'error': 'No papers provided for trend report'}
|
289 |
+
|
290 |
+
print(f"📊 Generating trend report for {len(papers)} papers...")
|
291 |
+
|
292 |
+
# Run all analyses
|
293 |
+
temporal_trends = self.analyze_temporal_trends(papers)
|
294 |
+
research_gaps = self.detect_research_gaps(papers)
|
295 |
+
|
296 |
+
# Generate keyword trends
|
297 |
+
keyword_analysis = self._analyze_keyword_trends(papers)
|
298 |
+
|
299 |
+
# Generate emerging topics
|
300 |
+
emerging_topics = self._detect_emerging_topics(papers)
|
301 |
+
|
302 |
+
# Generate AI-powered executive summary
|
303 |
+
executive_summary = self._generate_executive_summary(papers, temporal_trends, research_gaps)
|
304 |
+
|
305 |
+
# Compile comprehensive report
|
306 |
+
report = {
|
307 |
+
'executive_summary': executive_summary,
|
308 |
+
'temporal_trends': temporal_trends,
|
309 |
+
'research_gaps': research_gaps,
|
310 |
+
'keyword_analysis': keyword_analysis,
|
311 |
+
'emerging_topics': emerging_topics,
|
312 |
+
'report_metadata': {
|
313 |
+
'papers_analyzed': len(papers),
|
314 |
+
'analysis_date': datetime.now().isoformat(),
|
315 |
+
'report_version': '2.0'
|
316 |
+
}
|
317 |
+
}
|
318 |
+
|
319 |
+
return report
|
320 |
+
|
321 |
+
except Exception as e:
|
322 |
+
return {
|
323 |
+
'error': f'Trend report generation failed: {str(e)}',
|
324 |
+
'analysis_timestamp': datetime.now().isoformat()
|
325 |
+
}
|
326 |
+
|
327 |
+
def _extract_keywords(self, content: str) -> List[str]:
|
328 |
+
"""Extract keywords from content using simple NLP"""
|
329 |
+
# Remove common words and extract meaningful terms
|
330 |
+
stop_words = {'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must', 'shall', 'can', 'this', 'that', 'these', 'those', 'we', 'they', 'our', 'their', 'using', 'based', 'approach', 'method', 'model', 'paper', 'study', 'research', 'work', 'results', 'show', 'propose', 'present'}
|
331 |
+
|
332 |
+
# Extract words (simple tokenization)
|
333 |
+
words = re.findall(r'\b[a-zA-Z]+\b', content.lower())
|
334 |
+
|
335 |
+
# Filter keywords
|
336 |
+
keywords = [word for word in words if len(word) > 3 and word not in stop_words]
|
337 |
+
|
338 |
+
# Return top keywords
|
339 |
+
return list(Counter(keywords).keys())[:20]
|
340 |
+
|
341 |
+
def _analyze_keyword_trends(self, papers: List[Dict]) -> Dict:
|
342 |
+
"""Analyze keyword trends over time"""
|
343 |
+
try:
|
344 |
+
keyword_by_year = defaultdict(lambda: defaultdict(int))
|
345 |
+
|
346 |
+
for paper in papers:
|
347 |
+
year = paper.get('year')
|
348 |
+
if not year:
|
349 |
+
continue
|
350 |
+
|
351 |
+
content = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
|
352 |
+
keywords = self._extract_keywords(content)
|
353 |
+
|
354 |
+
for keyword in keywords[:10]: # Top 10 keywords per paper
|
355 |
+
keyword_by_year[year][keyword] += 1
|
356 |
+
|
357 |
+
# Find trending keywords
|
358 |
+
trending_keywords = {}
|
359 |
+
for keyword in set().union(*[keywords.keys() for keywords in keyword_by_year.values()]):
|
360 |
+
years = sorted(keyword_by_year.keys())
|
361 |
+
if len(years) >= 2:
|
362 |
+
recent_count = keyword_by_year[years[-1]][keyword]
|
363 |
+
previous_count = keyword_by_year[years[-2]][keyword]
|
364 |
+
|
365 |
+
if previous_count > 0:
|
366 |
+
trend = ((recent_count - previous_count) / previous_count) * 100
|
367 |
+
trending_keywords[keyword] = trend
|
368 |
+
|
369 |
+
# Get top trending keywords
|
370 |
+
top_trending = sorted(trending_keywords.items(), key=lambda x: x[1], reverse=True)[:10]
|
371 |
+
|
372 |
+
return {
|
373 |
+
'keyword_evolution': dict(keyword_by_year),
|
374 |
+
'trending_keywords': top_trending,
|
375 |
+
'analysis_timestamp': datetime.now().isoformat()
|
376 |
+
}
|
377 |
+
|
378 |
+
except Exception as e:
|
379 |
+
return {
|
380 |
+
'error': f'Keyword trend analysis failed: {str(e)}',
|
381 |
+
'analysis_timestamp': datetime.now().isoformat()
|
382 |
+
}
|
383 |
+
|
384 |
+
def _detect_emerging_topics(self, papers: List[Dict]) -> Dict:
|
385 |
+
"""Detect emerging research topics"""
|
386 |
+
try:
|
387 |
+
# Group papers by recent years
|
388 |
+
recent_papers = []
|
389 |
+
older_papers = []
|
390 |
+
|
391 |
+
current_year = datetime.now().year
|
392 |
+
|
393 |
+
for paper in papers:
|
394 |
+
year = paper.get('year')
|
395 |
+
if not year:
|
396 |
+
continue
|
397 |
+
|
398 |
+
if isinstance(year, str):
|
399 |
+
try:
|
400 |
+
year = int(year)
|
401 |
+
except ValueError:
|
402 |
+
continue
|
403 |
+
|
404 |
+
if year >= current_year - 2: # Last 2 years
|
405 |
+
recent_papers.append(paper)
|
406 |
+
else:
|
407 |
+
older_papers.append(paper)
|
408 |
+
|
409 |
+
# Extract topics from recent vs older papers
|
410 |
+
recent_topics = set()
|
411 |
+
older_topics = set()
|
412 |
+
|
413 |
+
for paper in recent_papers:
|
414 |
+
content = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
|
415 |
+
topics = self._extract_keywords(content)
|
416 |
+
recent_topics.update(topics[:5]) # Top 5 topics per paper
|
417 |
+
|
418 |
+
for paper in older_papers:
|
419 |
+
content = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
|
420 |
+
topics = self._extract_keywords(content)
|
421 |
+
older_topics.update(topics[:5])
|
422 |
+
|
423 |
+
# Find emerging topics (in recent but not in older)
|
424 |
+
emerging = recent_topics - older_topics
|
425 |
+
|
426 |
+
return {
|
427 |
+
'emerging_topics': list(emerging)[:15], # Top 15 emerging topics
|
428 |
+
'recent_papers_count': len(recent_papers),
|
429 |
+
'older_papers_count': len(older_papers),
|
430 |
+
'analysis_timestamp': datetime.now().isoformat()
|
431 |
+
}
|
432 |
+
|
433 |
+
except Exception as e:
|
434 |
+
return {
|
435 |
+
'error': f'Emerging topic detection failed: {str(e)}',
|
436 |
+
'analysis_timestamp': datetime.now().isoformat()
|
437 |
+
}
|
438 |
+
|
439 |
+
def _generate_ai_gap_analysis(self, papers: List[Dict], gaps: Dict) -> str:
|
440 |
+
"""Generate AI-powered gap analysis"""
|
441 |
+
try:
|
442 |
+
if not self.groq_processor:
|
443 |
+
return "AI analysis not available - Groq processor not initialized"
|
444 |
+
|
445 |
+
# Prepare summary for AI analysis
|
446 |
+
summary = f"""
|
447 |
+
Research Gap Analysis Summary:
|
448 |
+
- Total Papers Analyzed: {len(papers)}
|
449 |
+
- Methodology Gaps Found: {len(gaps['methodology_gaps'])}
|
450 |
+
- Research Area Gaps Found: {len(gaps['research_area_gaps'])}
|
451 |
+
- Data Type Gaps Found: {len(gaps['data_type_gaps'])}
|
452 |
+
|
453 |
+
Top Methodology Gaps:
|
454 |
+
{', '.join([gap['method'] for gap in gaps['methodology_gaps'][:5]])}
|
455 |
+
|
456 |
+
Top Research Area Gaps:
|
457 |
+
{', '.join([gap['area'] for gap in gaps['research_area_gaps'][:5]])}
|
458 |
+
"""
|
459 |
+
|
460 |
+
prompt = f"""Based on this research gap analysis, provide insights on:
|
461 |
+
|
462 |
+
{summary}
|
463 |
+
|
464 |
+
Please provide:
|
465 |
+
1. **Key Research Gaps**: Most significant gaps and why they matter
|
466 |
+
2. **Opportunities**: Potential research opportunities in underexplored areas
|
467 |
+
3. **Recommendations**: Specific recommendations for future research
|
468 |
+
4. **Priority Areas**: Which gaps should be prioritized and why
|
469 |
+
|
470 |
+
Format as a structured analysis."""
|
471 |
+
|
472 |
+
response = self.groq_processor.generate_response(prompt, max_tokens=1500)
|
473 |
+
return response
|
474 |
+
|
475 |
+
except Exception as e:
|
476 |
+
return f"AI gap analysis failed: {str(e)}"
|
477 |
+
|
478 |
+
def _generate_executive_summary(self, papers: List[Dict], temporal_trends: Dict, research_gaps: Dict) -> str:
|
479 |
+
"""Generate executive summary of trend analysis"""
|
480 |
+
try:
|
481 |
+
if not self.groq_processor:
|
482 |
+
return "Executive summary not available - Groq processor not initialized"
|
483 |
+
|
484 |
+
# Prepare data for summary
|
485 |
+
growth_info = temporal_trends.get('growth_analysis', {})
|
486 |
+
gap_summary = research_gaps.get('analysis_summary', {})
|
487 |
+
|
488 |
+
prompt = f"""Generate an executive summary for this research trend analysis:
|
489 |
+
|
490 |
+
Papers Analyzed: {len(papers)}
|
491 |
+
Publication Growth: {growth_info.get('trend_direction', 'unknown')} ({growth_info.get('growth_rate_percent', 0):.1f}%)
|
492 |
+
Research Gaps Found: {gap_summary.get('methodology_gaps_found', 0)} methodology gaps, {gap_summary.get('research_area_gaps_found', 0)} area gaps
|
493 |
+
|
494 |
+
Temporal Analysis:
|
495 |
+
- Year Range: {temporal_trends.get('temporal_analysis', {}).get('year_range', 'N/A')}
|
496 |
+
- Peak Year: {temporal_trends.get('temporal_analysis', {}).get('peak_year', 'N/A')}
|
497 |
+
- Average Papers/Year: {temporal_trends.get('temporal_analysis', {}).get('average_per_year', 0):.1f}
|
498 |
+
|
499 |
+
Provide a 3-paragraph executive summary covering:
|
500 |
+
1. Overall research landscape and trends
|
501 |
+
2. Key findings and patterns
|
502 |
+
3. Implications and future directions"""
|
503 |
+
|
504 |
+
response = self.groq_processor.generate_response(prompt, max_tokens=1000)
|
505 |
+
return response
|
506 |
+
|
507 |
+
except Exception as e:
|
508 |
+
return f"Executive summary generation failed: {str(e)}"
|
509 |
+
|
510 |
+
def get_trend_summary(self) -> Dict:
|
511 |
+
"""Get summary of all trend data"""
|
512 |
+
return {
|
513 |
+
'total_trends_tracked': len(self.trend_data),
|
514 |
+
'keyword_trends_count': len(self.keyword_trends),
|
515 |
+
'temporal_data_points': sum(len(data) for data in self.temporal_data.values()),
|
516 |
+
'last_analysis': datetime.now().isoformat()
|
517 |
+
}
|
src/components/unified_fetcher.py
ADDED
@@ -0,0 +1,938 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Unified Research Paper Fetcher
|
3 |
+
Fetches papers from multiple sources: ArXiv, Semantic Scholar, Crossref, and PubMed
|
4 |
+
Replaces all previous fetcher components for maximum minimalism
|
5 |
+
"""
|
6 |
+
|
7 |
+
import re
|
8 |
+
import time
|
9 |
+
import requests
|
10 |
+
import xml.etree.ElementTree as ET
|
11 |
+
from typing import List, Dict, Optional, Any, Union
|
12 |
+
from datetime import datetime, timedelta
|
13 |
+
import arxiv
|
14 |
+
import json
|
15 |
+
from collections import Counter
|
16 |
+
|
17 |
+
|
18 |
+
class UnifiedPaperFetcher:
|
19 |
+
"""
|
20 |
+
Unified fetcher for research papers from multiple academic databases
|
21 |
+
Supports: ArXiv, Semantic Scholar, Crossref, PubMed
|
22 |
+
"""
|
23 |
+
|
24 |
+
def __init__(self, config=None):
|
25 |
+
# Import Config only when needed to avoid dependency issues
|
26 |
+
if config is None:
|
27 |
+
try:
|
28 |
+
from .config import Config
|
29 |
+
self.config = Config()
|
30 |
+
except ImportError:
|
31 |
+
self.config = None
|
32 |
+
else:
|
33 |
+
self.config = config
|
34 |
+
|
35 |
+
# Initialize clients
|
36 |
+
self.arxiv_client = arxiv.Client()
|
37 |
+
|
38 |
+
# API endpoints
|
39 |
+
self.semantic_scholar_base = "https://api.semanticscholar.org/graph/v1"
|
40 |
+
self.crossref_base = "https://api.crossref.org/works"
|
41 |
+
self.pubmed_base = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
|
42 |
+
|
43 |
+
# Rate limiting
|
44 |
+
self.last_request_time = {}
|
45 |
+
self.min_request_interval = {
|
46 |
+
'semantic_scholar': 5.0, # 5 seconds between requests
|
47 |
+
'crossref': 0.1, # 100ms between requests (polite)
|
48 |
+
'pubmed': 0.34, # ~3 requests per second
|
49 |
+
'arxiv': 3.0 # 3 seconds between requests
|
50 |
+
}
|
51 |
+
|
52 |
+
def search_papers(self,
|
53 |
+
query: str,
|
54 |
+
max_results: int = 10,
|
55 |
+
sources: List[str] = None,
|
56 |
+
sort_by: str = "relevance") -> List[Dict[str, Any]]:
|
57 |
+
"""
|
58 |
+
Search for papers across multiple sources
|
59 |
+
|
60 |
+
Args:
|
61 |
+
query: Search query
|
62 |
+
max_results: Maximum number of results per source
|
63 |
+
sources: List of sources ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
64 |
+
sort_by: Sort criteria
|
65 |
+
|
66 |
+
Returns:
|
67 |
+
List of paper dictionaries with unified format
|
68 |
+
"""
|
69 |
+
if sources is None:
|
70 |
+
sources = ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
71 |
+
|
72 |
+
all_papers = []
|
73 |
+
results_per_source = max(1, max_results // len(sources))
|
74 |
+
|
75 |
+
print(f"Searching for: '{query}' across sources: {sources}")
|
76 |
+
|
77 |
+
for source in sources:
|
78 |
+
try:
|
79 |
+
print(f"Searching {source}...")
|
80 |
+
|
81 |
+
if source == 'arxiv':
|
82 |
+
papers = self._search_arxiv(query, results_per_source)
|
83 |
+
elif source == 'semantic_scholar':
|
84 |
+
papers = self._search_semantic_scholar(query, results_per_source)
|
85 |
+
elif source == 'crossref':
|
86 |
+
papers = self._search_crossref(query, results_per_source)
|
87 |
+
elif source == 'pubmed':
|
88 |
+
papers = self._search_pubmed(query, results_per_source)
|
89 |
+
else:
|
90 |
+
print(f"Unknown source: {source}")
|
91 |
+
continue
|
92 |
+
|
93 |
+
print(f"Found {len(papers)} papers from {source}")
|
94 |
+
all_papers.extend(papers)
|
95 |
+
|
96 |
+
except Exception as e:
|
97 |
+
print(f"Error searching {source}: {e}")
|
98 |
+
continue
|
99 |
+
|
100 |
+
# Remove duplicates and sort
|
101 |
+
unique_papers = self._deduplicate_papers(all_papers)
|
102 |
+
|
103 |
+
# Sort by relevance/date
|
104 |
+
if sort_by == "date":
|
105 |
+
unique_papers.sort(key=lambda x: x.get('published_date', ''), reverse=True)
|
106 |
+
|
107 |
+
print(f"Total unique papers found: {len(unique_papers)}")
|
108 |
+
return unique_papers[:max_results]
|
109 |
+
|
110 |
+
def _search_arxiv(self, query: str, max_results: int) -> List[Dict[str, Any]]:
|
111 |
+
"""Search ArXiv"""
|
112 |
+
self._rate_limit('arxiv')
|
113 |
+
|
114 |
+
try:
|
115 |
+
search = arxiv.Search(
|
116 |
+
query=query,
|
117 |
+
max_results=max_results,
|
118 |
+
sort_by=arxiv.SortCriterion.Relevance,
|
119 |
+
sort_order=arxiv.SortOrder.Descending
|
120 |
+
)
|
121 |
+
|
122 |
+
papers = []
|
123 |
+
for result in self.arxiv_client.results(search):
|
124 |
+
paper = {
|
125 |
+
'title': result.title,
|
126 |
+
'authors': [author.name for author in result.authors],
|
127 |
+
'abstract': result.summary,
|
128 |
+
'published_date': result.published.strftime('%Y-%m-%d'),
|
129 |
+
'year': result.published.year,
|
130 |
+
'url': result.entry_id,
|
131 |
+
'pdf_url': result.pdf_url,
|
132 |
+
'source': 'ArXiv',
|
133 |
+
'arxiv_id': result.entry_id.split('/')[-1],
|
134 |
+
'categories': [cat for cat in result.categories],
|
135 |
+
'doi': result.doi
|
136 |
+
}
|
137 |
+
papers.append(paper)
|
138 |
+
|
139 |
+
return papers
|
140 |
+
|
141 |
+
except Exception as e:
|
142 |
+
print(f"ArXiv search error: {e}")
|
143 |
+
return []
|
144 |
+
|
145 |
+
def _search_semantic_scholar(self, query: str, max_results: int) -> List[Dict[str, Any]]:
|
146 |
+
"""Search Semantic Scholar"""
|
147 |
+
self._rate_limit('semantic_scholar')
|
148 |
+
|
149 |
+
try:
|
150 |
+
url = f"{self.semantic_scholar_base}/paper/search"
|
151 |
+
params = {
|
152 |
+
'query': query,
|
153 |
+
'limit': min(max_results, 100),
|
154 |
+
'fields': 'title,authors,abstract,year,url,venue,citationCount,referenceCount,publicationDate,externalIds'
|
155 |
+
}
|
156 |
+
|
157 |
+
# Retry logic for rate limiting
|
158 |
+
max_retries = 3
|
159 |
+
data = None
|
160 |
+
for attempt in range(max_retries):
|
161 |
+
data = self.safe_get(url, params)
|
162 |
+
if data and 'data' in data:
|
163 |
+
break
|
164 |
+
elif attempt < max_retries - 1:
|
165 |
+
wait_time = (attempt + 1) * 5
|
166 |
+
print(f"Semantic Scholar rate limited, waiting {wait_time} seconds...")
|
167 |
+
time.sleep(wait_time) # Exponential backoff
|
168 |
+
else:
|
169 |
+
print("Semantic Scholar API unavailable after retries")
|
170 |
+
return []
|
171 |
+
|
172 |
+
if not data or 'data' not in data:
|
173 |
+
return []
|
174 |
+
|
175 |
+
papers = []
|
176 |
+
for paper_data in data.get('data', []):
|
177 |
+
# Handle authors
|
178 |
+
authors = []
|
179 |
+
if paper_data.get('authors'):
|
180 |
+
authors = [author.get('name', 'Unknown') for author in paper_data['authors']]
|
181 |
+
|
182 |
+
# Handle external IDs
|
183 |
+
external_ids = paper_data.get('externalIds', {})
|
184 |
+
doi = external_ids.get('DOI')
|
185 |
+
arxiv_id = external_ids.get('ArXiv')
|
186 |
+
|
187 |
+
paper = {
|
188 |
+
'title': paper_data.get('title', 'No title'),
|
189 |
+
'authors': authors,
|
190 |
+
'abstract': paper_data.get('abstract', ''),
|
191 |
+
'published_date': paper_data.get('publicationDate', ''),
|
192 |
+
'year': paper_data.get('year'),
|
193 |
+
'url': paper_data.get('url', ''),
|
194 |
+
'source': 'Semantic Scholar',
|
195 |
+
'venue': paper_data.get('venue', ''),
|
196 |
+
'citation_count': paper_data.get('citationCount', 0),
|
197 |
+
'reference_count': paper_data.get('referenceCount', 0),
|
198 |
+
'doi': doi,
|
199 |
+
'arxiv_id': arxiv_id
|
200 |
+
}
|
201 |
+
papers.append(paper)
|
202 |
+
|
203 |
+
return papers
|
204 |
+
|
205 |
+
except Exception as e:
|
206 |
+
print(f"Semantic Scholar search error: {e}")
|
207 |
+
return []
|
208 |
+
|
209 |
+
def _search_crossref(self, query: str, max_results: int) -> List[Dict[str, Any]]:
|
210 |
+
"""Search Crossref"""
|
211 |
+
self._rate_limit('crossref')
|
212 |
+
|
213 |
+
try:
|
214 |
+
url = self.crossref_base
|
215 |
+
params = {
|
216 |
+
'query': query,
|
217 |
+
'rows': min(max_results, 20),
|
218 |
+
'sort': 'relevance',
|
219 |
+
'select': 'title,author,abstract,published-print,published-online,URL,DOI,container-title,type'
|
220 |
+
}
|
221 |
+
|
222 |
+
headers = {
|
223 |
+
'User-Agent': 'ResearchMate/2.0 (mailto:[email protected])'
|
224 |
+
}
|
225 |
+
|
226 |
+
response = requests.get(url, params=params, headers=headers, timeout=30)
|
227 |
+
response.raise_for_status()
|
228 |
+
data = response.json()
|
229 |
+
|
230 |
+
papers = []
|
231 |
+
for item in data.get('message', {}).get('items', []):
|
232 |
+
# Handle authors
|
233 |
+
authors = []
|
234 |
+
if item.get('author'):
|
235 |
+
for author in item['author']:
|
236 |
+
given = author.get('given', '')
|
237 |
+
family = author.get('family', '')
|
238 |
+
name = f"{given} {family}".strip()
|
239 |
+
if name:
|
240 |
+
authors.append(name)
|
241 |
+
|
242 |
+
# Handle publication date
|
243 |
+
published_date = ''
|
244 |
+
year = None
|
245 |
+
if item.get('published-print'):
|
246 |
+
date_parts = item['published-print'].get('date-parts', [[]])[0]
|
247 |
+
if date_parts:
|
248 |
+
year = date_parts[0]
|
249 |
+
if len(date_parts) >= 3:
|
250 |
+
published_date = f"{date_parts[0]:04d}-{date_parts[1]:02d}-{date_parts[2]:02d}"
|
251 |
+
elif len(date_parts) >= 2:
|
252 |
+
published_date = f"{date_parts[0]:04d}-{date_parts[1]:02d}-01"
|
253 |
+
else:
|
254 |
+
published_date = f"{date_parts[0]:04d}-01-01"
|
255 |
+
|
256 |
+
paper = {
|
257 |
+
'title': item.get('title', ['No title'])[0] if item.get('title') else 'No title',
|
258 |
+
'authors': authors,
|
259 |
+
'abstract': item.get('abstract', ''),
|
260 |
+
'published_date': published_date,
|
261 |
+
'year': year,
|
262 |
+
'url': item.get('URL', ''),
|
263 |
+
'source': 'Crossref',
|
264 |
+
'doi': item.get('DOI', ''),
|
265 |
+
'journal': item.get('container-title', [''])[0] if item.get('container-title') else '',
|
266 |
+
'type': item.get('type', '')
|
267 |
+
}
|
268 |
+
papers.append(paper)
|
269 |
+
|
270 |
+
return papers
|
271 |
+
|
272 |
+
except Exception as e:
|
273 |
+
print(f"Crossref search error: {e}")
|
274 |
+
return []
|
275 |
+
|
276 |
+
def _search_pubmed(self, query: str, max_results: int) -> List[Dict[str, Any]]:
|
277 |
+
"""Search PubMed"""
|
278 |
+
self._rate_limit('pubmed')
|
279 |
+
|
280 |
+
try:
|
281 |
+
# Step 1: Search for PMIDs
|
282 |
+
search_url = f"{self.pubmed_base}/esearch.fcgi"
|
283 |
+
search_params = {
|
284 |
+
'db': 'pubmed',
|
285 |
+
'term': query,
|
286 |
+
'retmax': min(max_results, 20),
|
287 |
+
'retmode': 'json',
|
288 |
+
'sort': 'relevance'
|
289 |
+
}
|
290 |
+
|
291 |
+
response = requests.get(search_url, params=search_params, timeout=30)
|
292 |
+
response.raise_for_status()
|
293 |
+
search_data = response.json()
|
294 |
+
|
295 |
+
pmids = search_data.get('esearchresult', {}).get('idlist', [])
|
296 |
+
if not pmids:
|
297 |
+
return []
|
298 |
+
|
299 |
+
# Step 2: Fetch details for PMIDs
|
300 |
+
self._rate_limit('pubmed')
|
301 |
+
fetch_url = f"{self.pubmed_base}/efetch.fcgi"
|
302 |
+
fetch_params = {
|
303 |
+
'db': 'pubmed',
|
304 |
+
'id': ','.join(pmids),
|
305 |
+
'retmode': 'xml'
|
306 |
+
}
|
307 |
+
|
308 |
+
response = requests.get(fetch_url, params=fetch_params, timeout=30)
|
309 |
+
response.raise_for_status()
|
310 |
+
|
311 |
+
# Parse XML
|
312 |
+
root = ET.fromstring(response.content)
|
313 |
+
papers = []
|
314 |
+
|
315 |
+
for article in root.findall('.//PubmedArticle'):
|
316 |
+
try:
|
317 |
+
# Extract basic info
|
318 |
+
medline = article.find('.//MedlineCitation')
|
319 |
+
if medline is None:
|
320 |
+
continue
|
321 |
+
|
322 |
+
article_elem = medline.find('.//Article')
|
323 |
+
if article_elem is None:
|
324 |
+
continue
|
325 |
+
|
326 |
+
# Title
|
327 |
+
title_elem = article_elem.find('.//ArticleTitle')
|
328 |
+
title = title_elem.text if title_elem is not None else 'No title'
|
329 |
+
|
330 |
+
# Authors
|
331 |
+
authors = []
|
332 |
+
author_list = article_elem.find('.//AuthorList')
|
333 |
+
if author_list is not None:
|
334 |
+
for author in author_list.findall('.//Author'):
|
335 |
+
last_name = author.find('.//LastName')
|
336 |
+
first_name = author.find('.//ForeName')
|
337 |
+
if last_name is not None and first_name is not None:
|
338 |
+
authors.append(f"{first_name.text} {last_name.text}")
|
339 |
+
elif last_name is not None:
|
340 |
+
authors.append(last_name.text)
|
341 |
+
|
342 |
+
# Abstract
|
343 |
+
abstract = ''
|
344 |
+
abstract_elem = article_elem.find('.//AbstractText')
|
345 |
+
if abstract_elem is not None:
|
346 |
+
abstract = abstract_elem.text or ''
|
347 |
+
|
348 |
+
# Publication date
|
349 |
+
pub_date = article_elem.find('.//PubDate')
|
350 |
+
published_date = ''
|
351 |
+
year = None
|
352 |
+
if pub_date is not None:
|
353 |
+
year_elem = pub_date.find('.//Year')
|
354 |
+
month_elem = pub_date.find('.//Month')
|
355 |
+
day_elem = pub_date.find('.//Day')
|
356 |
+
|
357 |
+
if year_elem is not None:
|
358 |
+
year = int(year_elem.text)
|
359 |
+
month = month_elem.text if month_elem is not None else '01'
|
360 |
+
day = day_elem.text if day_elem is not None else '01'
|
361 |
+
|
362 |
+
# Convert month name to number if needed
|
363 |
+
month_map = {
|
364 |
+
'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04',
|
365 |
+
'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08',
|
366 |
+
'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'
|
367 |
+
}
|
368 |
+
if month in month_map:
|
369 |
+
month = month_map[month]
|
370 |
+
elif not month.isdigit():
|
371 |
+
month = '01'
|
372 |
+
|
373 |
+
published_date = f"{year}-{month.zfill(2)}-{day.zfill(2)}"
|
374 |
+
|
375 |
+
# PMID
|
376 |
+
pmid_elem = medline.find('.//PMID')
|
377 |
+
pmid = pmid_elem.text if pmid_elem is not None else ''
|
378 |
+
|
379 |
+
# Journal
|
380 |
+
journal_elem = article_elem.find('.//Journal/Title')
|
381 |
+
journal = journal_elem.text if journal_elem is not None else ''
|
382 |
+
|
383 |
+
# DOI
|
384 |
+
doi = ''
|
385 |
+
article_ids = article.findall('.//ArticleId')
|
386 |
+
for article_id in article_ids:
|
387 |
+
if article_id.get('IdType') == 'doi':
|
388 |
+
doi = article_id.text
|
389 |
+
break
|
390 |
+
|
391 |
+
paper = {
|
392 |
+
'title': title,
|
393 |
+
'authors': authors,
|
394 |
+
'abstract': abstract,
|
395 |
+
'published_date': published_date,
|
396 |
+
'year': year,
|
397 |
+
'url': f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
|
398 |
+
'source': 'PubMed',
|
399 |
+
'pmid': pmid,
|
400 |
+
'journal': journal,
|
401 |
+
'doi': doi
|
402 |
+
}
|
403 |
+
papers.append(paper)
|
404 |
+
|
405 |
+
except Exception as e:
|
406 |
+
print(f"Error parsing PubMed article: {e}")
|
407 |
+
continue
|
408 |
+
|
409 |
+
return papers
|
410 |
+
|
411 |
+
except Exception as e:
|
412 |
+
print(f"PubMed search error: {e}")
|
413 |
+
return []
|
414 |
+
|
415 |
+
def _rate_limit(self, source: str):
|
416 |
+
"""Implement rate limiting for API calls"""
|
417 |
+
now = time.time()
|
418 |
+
last_request = self.last_request_time.get(source, 0)
|
419 |
+
interval = self.min_request_interval.get(source, 1.0)
|
420 |
+
|
421 |
+
time_since_last = now - last_request
|
422 |
+
if time_since_last < interval:
|
423 |
+
sleep_time = interval - time_since_last
|
424 |
+
time.sleep(sleep_time)
|
425 |
+
|
426 |
+
self.last_request_time[source] = time.time()
|
427 |
+
|
428 |
+
def safe_get(self, url: str, params: dict = None, headers: dict = None, timeout: int = 30) -> Optional[Dict[str, Any]]:
|
429 |
+
"""Safe HTTP GET with error handling"""
|
430 |
+
try:
|
431 |
+
response = requests.get(url, params=params, headers=headers, timeout=timeout)
|
432 |
+
response.raise_for_status()
|
433 |
+
return response.json()
|
434 |
+
except requests.exceptions.RequestException as e:
|
435 |
+
print(f"HTTP request failed: {e}")
|
436 |
+
return None
|
437 |
+
except json.JSONDecodeError as e:
|
438 |
+
print(f"JSON decode error: {e}")
|
439 |
+
return None
|
440 |
+
|
441 |
+
def _deduplicate_papers(self, papers: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
442 |
+
"""Remove duplicate papers based on title, DOI, or ArXiv ID"""
|
443 |
+
seen = set()
|
444 |
+
unique_papers = []
|
445 |
+
|
446 |
+
for paper in papers:
|
447 |
+
# Create identifier based on available fields
|
448 |
+
identifiers = []
|
449 |
+
# Use DOI if available
|
450 |
+
doi = paper.get('doi')
|
451 |
+
if doi is None:
|
452 |
+
doi = ''
|
453 |
+
doi = str(doi).strip()
|
454 |
+
if doi:
|
455 |
+
identifiers.append(f"doi:{doi.lower()}")
|
456 |
+
# Use ArXiv ID if available
|
457 |
+
arxiv_id = paper.get('arxiv_id')
|
458 |
+
if arxiv_id is None:
|
459 |
+
arxiv_id = ''
|
460 |
+
arxiv_id = str(arxiv_id).strip()
|
461 |
+
if arxiv_id:
|
462 |
+
identifiers.append(f"arxiv:{arxiv_id.lower()}")
|
463 |
+
# Use PMID if available
|
464 |
+
pmid = paper.get('pmid')
|
465 |
+
if pmid is None:
|
466 |
+
pmid = ''
|
467 |
+
pmid = str(pmid).strip()
|
468 |
+
if pmid:
|
469 |
+
identifiers.append(f"pmid:{pmid}")
|
470 |
+
# Use title as fallback
|
471 |
+
title = paper.get('title')
|
472 |
+
if title is None:
|
473 |
+
title = ''
|
474 |
+
title = str(title).strip().lower()
|
475 |
+
if title and title != 'no title':
|
476 |
+
# Clean title for comparison
|
477 |
+
clean_title = re.sub(r'[^\w\s]', '', title)
|
478 |
+
clean_title = ' '.join(clean_title.split())
|
479 |
+
identifiers.append(f"title:{clean_title}")
|
480 |
+
# Check if any identifier has been seen
|
481 |
+
found_duplicate = False
|
482 |
+
for identifier in identifiers:
|
483 |
+
if identifier in seen:
|
484 |
+
found_duplicate = True
|
485 |
+
break
|
486 |
+
if not found_duplicate:
|
487 |
+
# Add all identifiers to seen set
|
488 |
+
for identifier in identifiers:
|
489 |
+
seen.add(identifier)
|
490 |
+
unique_papers.append(paper)
|
491 |
+
return unique_papers
|
492 |
+
|
493 |
+
def get_paper_by_doi(self, doi: str) -> Optional[Dict[str, Any]]:
|
494 |
+
"""Get paper details by DOI from Crossref"""
|
495 |
+
try:
|
496 |
+
url = f"{self.crossref_base}/{doi}"
|
497 |
+
headers = {
|
498 |
+
'User-Agent': 'ResearchMate/2.0 (mailto:[email protected])'
|
499 |
+
}
|
500 |
+
|
501 |
+
response = requests.get(url, headers=headers, timeout=30)
|
502 |
+
response.raise_for_status()
|
503 |
+
data = response.json()
|
504 |
+
|
505 |
+
item = data.get('message', {})
|
506 |
+
if not item:
|
507 |
+
return None
|
508 |
+
|
509 |
+
# Parse the item (similar to _search_crossref)
|
510 |
+
authors = []
|
511 |
+
if item.get('author'):
|
512 |
+
for author in item['author']:
|
513 |
+
given = author.get('given', '')
|
514 |
+
family = author.get('family', '')
|
515 |
+
name = f"{given} {family}".strip()
|
516 |
+
if name:
|
517 |
+
authors.append(name)
|
518 |
+
|
519 |
+
# Handle publication date
|
520 |
+
published_date = ''
|
521 |
+
year = None
|
522 |
+
if item.get('published-print'):
|
523 |
+
date_parts = item['published-print'].get('date-parts', [[]])[0]
|
524 |
+
if date_parts:
|
525 |
+
year = date_parts[0]
|
526 |
+
if len(date_parts) >= 3:
|
527 |
+
published_date = f"{date_parts[0]:04d}-{date_parts[1]:02d}-{date_parts[2]:02d}"
|
528 |
+
|
529 |
+
paper = {
|
530 |
+
'title': item.get('title', ['No title'])[0] if item.get('title') else 'No title',
|
531 |
+
'authors': authors,
|
532 |
+
'abstract': item.get('abstract', ''),
|
533 |
+
'published_date': published_date,
|
534 |
+
'year': year,
|
535 |
+
'url': item.get('URL', ''),
|
536 |
+
'source': 'Crossref',
|
537 |
+
'doi': item.get('DOI', ''),
|
538 |
+
'journal': item.get('container-title', [''])[0] if item.get('container-title') else ''
|
539 |
+
}
|
540 |
+
|
541 |
+
return paper
|
542 |
+
|
543 |
+
except Exception as e:
|
544 |
+
print(f"Error fetching DOI {doi}: {e}")
|
545 |
+
return None
|
546 |
+
|
547 |
+
|
548 |
+
class PaperFetcher(UnifiedPaperFetcher):
|
549 |
+
"""
|
550 |
+
Consolidated paper fetcher combining all sources
|
551 |
+
This is the single fetcher class that replaces all previous fetcher components
|
552 |
+
"""
|
553 |
+
|
554 |
+
def __init__(self, config=None):
|
555 |
+
super().__init__(config)
|
556 |
+
|
557 |
+
def search_papers(self,
|
558 |
+
query: str,
|
559 |
+
max_results: int = 10,
|
560 |
+
sources: List[str] = None,
|
561 |
+
sort_by: str = "relevance",
|
562 |
+
category: str = None,
|
563 |
+
date_range: int = None) -> List[Dict[str, Any]]:
|
564 |
+
"""
|
565 |
+
Enhanced search with additional parameters from original ArxivFetcher
|
566 |
+
|
567 |
+
Args:
|
568 |
+
query: Search query
|
569 |
+
max_results: Maximum number of results
|
570 |
+
sources: List of sources ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
571 |
+
sort_by: Sort criteria ('relevance', 'date', 'lastUpdatedDate', 'submittedDate')
|
572 |
+
category: ArXiv category filter (e.g., 'cs.AI', 'cs.LG')
|
573 |
+
date_range: Days back to search (e.g., 7, 30, 365)
|
574 |
+
|
575 |
+
Returns:
|
576 |
+
List of paper dictionaries with unified format
|
577 |
+
"""
|
578 |
+
# Use all sources by default
|
579 |
+
if sources is None:
|
580 |
+
sources = ['arxiv', 'semantic_scholar', 'crossref', 'pubmed']
|
581 |
+
|
582 |
+
# Apply category filter to ArXiv query if specified
|
583 |
+
if category and 'arxiv' in sources:
|
584 |
+
enhanced_query = f"cat:{category} AND {query}"
|
585 |
+
return self._search_with_enhanced_query(enhanced_query, max_results, sources, sort_by, date_range)
|
586 |
+
|
587 |
+
return super().search_papers(query, max_results, sources, sort_by)
|
588 |
+
|
589 |
+
def _search_with_enhanced_query(self, query: str, max_results: int, sources: List[str], sort_by: str, date_range: int) -> List[Dict[str, Any]]:
|
590 |
+
"""Internal method for enhanced search with date filtering"""
|
591 |
+
papers = super().search_papers(query, max_results, sources, sort_by)
|
592 |
+
|
593 |
+
# Apply date filtering if specified
|
594 |
+
if date_range:
|
595 |
+
cutoff_date = datetime.now() - timedelta(days=date_range)
|
596 |
+
filtered_papers = []
|
597 |
+
for paper in papers:
|
598 |
+
pub_date_str = paper.get('published_date', '')
|
599 |
+
if pub_date_str:
|
600 |
+
try:
|
601 |
+
pub_date = datetime.strptime(pub_date_str, '%Y-%m-%d')
|
602 |
+
if pub_date >= cutoff_date:
|
603 |
+
filtered_papers.append(paper)
|
604 |
+
except ValueError:
|
605 |
+
# If date parsing fails, include the paper
|
606 |
+
filtered_papers.append(paper)
|
607 |
+
else:
|
608 |
+
# If no date, include the paper
|
609 |
+
filtered_papers.append(paper)
|
610 |
+
return filtered_papers
|
611 |
+
|
612 |
+
return papers
|
613 |
+
|
614 |
+
def get_paper_by_id(self, paper_id: str) -> Optional[Dict[str, Any]]:
|
615 |
+
"""
|
616 |
+
Get a specific paper by ID (supports ArXiv ID, DOI, PMID)
|
617 |
+
|
618 |
+
Args:
|
619 |
+
paper_id: Paper ID (ArXiv ID, DOI, or PMID)
|
620 |
+
|
621 |
+
Returns:
|
622 |
+
Paper dictionary or None
|
623 |
+
"""
|
624 |
+
# Check if it's an ArXiv ID
|
625 |
+
if re.match(r'^\d{4}\.\d{4,5}(v\d+)?$', paper_id):
|
626 |
+
return self._get_arxiv_paper_by_id(paper_id)
|
627 |
+
|
628 |
+
# Check if it's a DOI
|
629 |
+
if '/' in paper_id and ('10.' in paper_id or paper_id.startswith('doi:')):
|
630 |
+
doi = paper_id.replace('doi:', '')
|
631 |
+
return self.get_paper_by_doi(doi)
|
632 |
+
|
633 |
+
# Check if it's a PMID
|
634 |
+
if paper_id.isdigit():
|
635 |
+
return self._get_pubmed_paper_by_id(paper_id)
|
636 |
+
|
637 |
+
# Fallback: search for it
|
638 |
+
results = self.search_papers(paper_id, max_results=1)
|
639 |
+
return results[0] if results else None
|
640 |
+
|
641 |
+
def _get_arxiv_paper_by_id(self, arxiv_id: str) -> Optional[Dict[str, Any]]:
|
642 |
+
"""Get paper by ArXiv ID"""
|
643 |
+
try:
|
644 |
+
search = arxiv.Search(id_list=[arxiv_id])
|
645 |
+
results = list(self.arxiv_client.results(search))
|
646 |
+
|
647 |
+
if results:
|
648 |
+
result = results[0]
|
649 |
+
return {
|
650 |
+
'title': result.title,
|
651 |
+
'authors': [author.name for author in result.authors],
|
652 |
+
'abstract': result.summary,
|
653 |
+
'published_date': result.published.strftime('%Y-%m-%d'),
|
654 |
+
'year': result.published.year,
|
655 |
+
'url': result.entry_id,
|
656 |
+
'pdf_url': result.pdf_url,
|
657 |
+
'source': 'ArXiv',
|
658 |
+
'arxiv_id': result.entry_id.split('/')[-1],
|
659 |
+
'categories': [cat for cat in result.categories],
|
660 |
+
'doi': result.doi
|
661 |
+
}
|
662 |
+
return None
|
663 |
+
except Exception as e:
|
664 |
+
print(f"Error fetching ArXiv paper {arxiv_id}: {e}")
|
665 |
+
return None
|
666 |
+
|
667 |
+
def _get_pubmed_paper_by_id(self, pmid: str) -> Optional[Dict[str, Any]]:
|
668 |
+
"""Get paper by PubMed ID"""
|
669 |
+
try:
|
670 |
+
fetch_url = f"{self.pubmed_base}/efetch.fcgi"
|
671 |
+
fetch_params = {
|
672 |
+
'db': 'pubmed',
|
673 |
+
'id': pmid,
|
674 |
+
'retmode': 'xml'
|
675 |
+
}
|
676 |
+
|
677 |
+
response = requests.get(fetch_url, params=fetch_params, timeout=30)
|
678 |
+
response.raise_for_status()
|
679 |
+
|
680 |
+
root = ET.fromstring(response.content)
|
681 |
+
article = root.find('.//PubmedArticle')
|
682 |
+
|
683 |
+
if article is not None:
|
684 |
+
# Parse similar to _search_pubmed
|
685 |
+
medline = article.find('.//MedlineCitation')
|
686 |
+
article_elem = medline.find('.//Article')
|
687 |
+
|
688 |
+
title_elem = article_elem.find('.//ArticleTitle')
|
689 |
+
title = title_elem.text if title_elem is not None else 'No title'
|
690 |
+
|
691 |
+
authors = []
|
692 |
+
author_list = article_elem.find('.//AuthorList')
|
693 |
+
if author_list is not None:
|
694 |
+
for author in author_list.findall('.//Author'):
|
695 |
+
last_name = author.find('.//LastName')
|
696 |
+
first_name = author.find('.//ForeName')
|
697 |
+
if last_name is not None and first_name is not None:
|
698 |
+
authors.append(f"{first_name.text} {last_name.text}")
|
699 |
+
|
700 |
+
abstract = ''
|
701 |
+
abstract_elem = article_elem.find('.//AbstractText')
|
702 |
+
if abstract_elem is not None:
|
703 |
+
abstract = abstract_elem.text or ''
|
704 |
+
|
705 |
+
return {
|
706 |
+
'title': title,
|
707 |
+
'authors': authors,
|
708 |
+
'abstract': abstract,
|
709 |
+
'url': f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
|
710 |
+
'source': 'PubMed',
|
711 |
+
'pmid': pmid
|
712 |
+
}
|
713 |
+
return None
|
714 |
+
except Exception as e:
|
715 |
+
print(f"Error fetching PubMed paper {pmid}: {e}")
|
716 |
+
return None
|
717 |
+
|
718 |
+
def search_by_author(self, author: str, max_results: int = 20) -> List[Dict[str, Any]]:
|
719 |
+
"""
|
720 |
+
Search for papers by author across all sources
|
721 |
+
|
722 |
+
Args:
|
723 |
+
author: Author name
|
724 |
+
max_results: Maximum number of results
|
725 |
+
|
726 |
+
Returns:
|
727 |
+
List of paper dictionaries
|
728 |
+
"""
|
729 |
+
return self.search_papers(f"author:{author}", max_results=max_results, sort_by="date")
|
730 |
+
|
731 |
+
def search_by_category(self, category: str, max_results: int = 20) -> List[Dict[str, Any]]:
|
732 |
+
"""
|
733 |
+
Search for papers by category (primarily ArXiv)
|
734 |
+
|
735 |
+
Args:
|
736 |
+
category: Category (e.g., 'cs.AI', 'cs.LG', 'stat.ML')
|
737 |
+
max_results: Maximum number of results
|
738 |
+
|
739 |
+
Returns:
|
740 |
+
List of paper dictionaries
|
741 |
+
"""
|
742 |
+
return self.search_papers("", max_results=max_results, category=category, sort_by="date")
|
743 |
+
|
744 |
+
def get_trending_papers(self, category: str = "cs.AI", days: int = 7, max_results: int = 10) -> List[Dict[str, Any]]:
|
745 |
+
"""
|
746 |
+
Get trending papers in a category
|
747 |
+
|
748 |
+
Args:
|
749 |
+
category: Category to search
|
750 |
+
days: Days back to look for papers
|
751 |
+
max_results: Maximum number of results
|
752 |
+
|
753 |
+
Returns:
|
754 |
+
List of paper dictionaries
|
755 |
+
"""
|
756 |
+
return self.search_papers(
|
757 |
+
query="recent",
|
758 |
+
max_results=max_results,
|
759 |
+
category=category,
|
760 |
+
date_range=days,
|
761 |
+
sort_by="date"
|
762 |
+
)
|
763 |
+
|
764 |
+
def download_pdf(self, paper: Dict[str, Any], download_dir: str = "downloads") -> Optional[str]:
|
765 |
+
"""
|
766 |
+
Download PDF for a paper
|
767 |
+
|
768 |
+
Args:
|
769 |
+
paper: Paper dictionary
|
770 |
+
download_dir: Directory to save PDF
|
771 |
+
|
772 |
+
Returns:
|
773 |
+
Path to downloaded PDF or None
|
774 |
+
"""
|
775 |
+
try:
|
776 |
+
import os
|
777 |
+
os.makedirs(download_dir, exist_ok=True)
|
778 |
+
|
779 |
+
pdf_url = paper.get('pdf_url')
|
780 |
+
if not pdf_url:
|
781 |
+
print(f"No PDF URL for paper: {paper.get('title', 'Unknown')}")
|
782 |
+
return None
|
783 |
+
|
784 |
+
# Generate filename
|
785 |
+
paper_id = paper.get('arxiv_id', paper.get('pmid', paper.get('doi', 'unknown')))
|
786 |
+
filename = f"{paper_id}.pdf"
|
787 |
+
filepath = os.path.join(download_dir, filename)
|
788 |
+
|
789 |
+
if os.path.exists(filepath):
|
790 |
+
print(f"PDF already exists: {filepath}")
|
791 |
+
return filepath
|
792 |
+
|
793 |
+
print(f"Downloading PDF: {paper.get('title', 'Unknown')}")
|
794 |
+
|
795 |
+
response = requests.get(pdf_url, timeout=30)
|
796 |
+
response.raise_for_status()
|
797 |
+
|
798 |
+
with open(filepath, 'wb') as f:
|
799 |
+
f.write(response.content)
|
800 |
+
|
801 |
+
print(f"PDF downloaded: {filepath}")
|
802 |
+
return filepath
|
803 |
+
|
804 |
+
except Exception as e:
|
805 |
+
print(f"Error downloading PDF: {e}")
|
806 |
+
return None
|
807 |
+
|
808 |
+
def get_paper_recommendations(self, paper_id: str, max_results: int = 5) -> List[Dict[str, Any]]:
|
809 |
+
"""
|
810 |
+
Get paper recommendations based on a paper's content
|
811 |
+
|
812 |
+
Args:
|
813 |
+
paper_id: Paper ID
|
814 |
+
max_results: Number of recommendations
|
815 |
+
|
816 |
+
Returns:
|
817 |
+
List of recommended papers
|
818 |
+
"""
|
819 |
+
try:
|
820 |
+
# Get the base paper
|
821 |
+
base_paper = self.get_paper_by_id(paper_id)
|
822 |
+
if not base_paper:
|
823 |
+
return []
|
824 |
+
|
825 |
+
# Extract key terms from title and abstract
|
826 |
+
title = base_paper.get('title', '')
|
827 |
+
abstract = base_paper.get('abstract', '')
|
828 |
+
|
829 |
+
# Simple keyword extraction
|
830 |
+
keywords = self._extract_keywords(title + ' ' + abstract)
|
831 |
+
|
832 |
+
# Search for related papers
|
833 |
+
query = ' '.join(keywords[:5]) # Use top 5 keywords
|
834 |
+
|
835 |
+
related_papers = self.search_papers(
|
836 |
+
query=query,
|
837 |
+
max_results=max_results + 5, # Get more to filter out the original
|
838 |
+
sort_by="relevance"
|
839 |
+
)
|
840 |
+
|
841 |
+
# Filter out the original paper
|
842 |
+
recommendations = [p for p in related_papers if p.get('arxiv_id') != paper_id and p.get('pmid') != paper_id]
|
843 |
+
|
844 |
+
return recommendations[:max_results]
|
845 |
+
|
846 |
+
except Exception as e:
|
847 |
+
print(f"Error getting recommendations: {e}")
|
848 |
+
return []
|
849 |
+
|
850 |
+
def _extract_keywords(self, text: str) -> List[str]:
|
851 |
+
"""
|
852 |
+
Simple keyword extraction from text
|
853 |
+
|
854 |
+
Args:
|
855 |
+
text: Input text
|
856 |
+
|
857 |
+
Returns:
|
858 |
+
List of keywords
|
859 |
+
"""
|
860 |
+
# Simple implementation - can be improved with NLP libraries
|
861 |
+
stop_words = {
|
862 |
+
'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by',
|
863 |
+
'a', 'an', 'as', 'is', 'was', 'are', 'were', 'be', 'been', 'have', 'has', 'had',
|
864 |
+
'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must',
|
865 |
+
'can', 'this', 'that', 'these', 'those', 'we', 'us', 'our', 'you', 'your',
|
866 |
+
'he', 'him', 'his', 'she', 'her', 'it', 'its', 'they', 'them', 'their'
|
867 |
+
}
|
868 |
+
|
869 |
+
# Extract words
|
870 |
+
words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower())
|
871 |
+
|
872 |
+
# Filter and count
|
873 |
+
filtered_words = [word for word in words if word not in stop_words]
|
874 |
+
word_counts = Counter(filtered_words)
|
875 |
+
|
876 |
+
# Return most common words
|
877 |
+
return [word for word, count in word_counts.most_common(20)]
|
878 |
+
|
879 |
+
def get_categories(self) -> Dict[str, str]:
|
880 |
+
"""
|
881 |
+
Get available categories (primarily ArXiv)
|
882 |
+
|
883 |
+
Returns:
|
884 |
+
Dictionary of category codes and descriptions
|
885 |
+
"""
|
886 |
+
return {
|
887 |
+
'cs.AI': 'Artificial Intelligence',
|
888 |
+
'cs.LG': 'Machine Learning',
|
889 |
+
'cs.CV': 'Computer Vision',
|
890 |
+
'cs.CL': 'Computation and Language',
|
891 |
+
'cs.NE': 'Neural and Evolutionary Computing',
|
892 |
+
'cs.RO': 'Robotics',
|
893 |
+
'cs.CR': 'Cryptography and Security',
|
894 |
+
'cs.DC': 'Distributed, Parallel, and Cluster Computing',
|
895 |
+
'cs.DB': 'Databases',
|
896 |
+
'cs.DS': 'Data Structures and Algorithms',
|
897 |
+
'cs.HC': 'Human-Computer Interaction',
|
898 |
+
'cs.IR': 'Information Retrieval',
|
899 |
+
'cs.IT': 'Information Theory',
|
900 |
+
'cs.MM': 'Multimedia',
|
901 |
+
'cs.NI': 'Networking and Internet Architecture',
|
902 |
+
'cs.OS': 'Operating Systems',
|
903 |
+
'cs.PL': 'Programming Languages',
|
904 |
+
'cs.SE': 'Software Engineering',
|
905 |
+
'cs.SY': 'Systems and Control',
|
906 |
+
'stat.ML': 'Machine Learning (Statistics)',
|
907 |
+
'stat.AP': 'Applications (Statistics)',
|
908 |
+
'stat.CO': 'Computation (Statistics)',
|
909 |
+
'stat.ME': 'Methodology (Statistics)',
|
910 |
+
'stat.TH': 'Statistics Theory',
|
911 |
+
'math.ST': 'Statistics Theory (Mathematics)',
|
912 |
+
'math.PR': 'Probability (Mathematics)',
|
913 |
+
'math.OC': 'Optimization and Control',
|
914 |
+
'math.NA': 'Numerical Analysis',
|
915 |
+
'eess.AS': 'Audio and Speech Processing',
|
916 |
+
'eess.IV': 'Image and Video Processing',
|
917 |
+
'eess.SP': 'Signal Processing',
|
918 |
+
'eess.SY': 'Systems and Control',
|
919 |
+
'q-bio.QM': 'Quantitative Methods',
|
920 |
+
'q-bio.NC': 'Neurons and Cognition',
|
921 |
+
'physics.data-an': 'Data Analysis, Statistics and Probability'
|
922 |
+
}
|
923 |
+
|
924 |
+
|
925 |
+
# Backward compatibility aliases
|
926 |
+
class ArxivFetcher(PaperFetcher):
|
927 |
+
"""Backward compatibility class for ArxivFetcher"""
|
928 |
+
|
929 |
+
def __init__(self, config=None):
|
930 |
+
super().__init__(config)
|
931 |
+
|
932 |
+
def search_papers(self, query: str, max_results: int = 10, **kwargs) -> List[Dict[str, Any]]:
|
933 |
+
"""Search only ArXiv for backward compatibility"""
|
934 |
+
return super().search_papers(query, max_results, sources=['arxiv'], **kwargs)
|
935 |
+
|
936 |
+
|
937 |
+
# Main class alias for the unified fetcher
|
938 |
+
UnifiedFetcher = PaperFetcher
|
src/scripts/__init__.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
ResearchMate Scripts Package
|
3 |
+
Contains all management and deployment scripts for ResearchMate
|
4 |
+
"""
|
5 |
+
|
6 |
+
__version__ = "2.0.0"
|
7 |
+
__author__ = "ResearchMate Team"
|
8 |
+
__description__ = "AI Research Assistant Scripts"
|
9 |
+
|
10 |
+
from .deploy import ResearchMateDeployer
|
11 |
+
from .setup import ResearchMateSetup
|
12 |
+
from .manager import ResearchMateManager
|
13 |
+
from .dev_server import ResearchMateDevServer
|
14 |
+
|
15 |
+
__all__ = [
|
16 |
+
'ResearchMateDeployer',
|
17 |
+
'ResearchMateSetup',
|
18 |
+
'ResearchMateManager',
|
19 |
+
'ResearchMateDevServer'
|
20 |
+
]
|
src/scripts/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (716 Bytes). View file
|
|
src/scripts/__pycache__/__init__.cpython-313.pyc
ADDED
Binary file (635 Bytes). View file
|
|
src/scripts/__pycache__/deploy.cpython-311.pyc
ADDED
Binary file (22.4 kB). View file
|
|
src/scripts/__pycache__/deploy.cpython-313.pyc
ADDED
Binary file (13.7 kB). View file
|
|
src/scripts/__pycache__/dev_server.cpython-311.pyc
ADDED
Binary file (17.8 kB). View file
|
|
src/scripts/__pycache__/manager.cpython-311.pyc
ADDED
Binary file (22 kB). View file
|
|
src/scripts/__pycache__/setup.cpython-311.pyc
ADDED
Binary file (21.7 kB). View file
|
|
src/scripts/deploy.py
ADDED
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
ResearchMate Deployment Script
|
4 |
+
A complete Python-based deployment system for ResearchMate
|
5 |
+
"""
|
6 |
+
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import subprocess
|
10 |
+
import platform
|
11 |
+
import logging
|
12 |
+
from pathlib import Path
|
13 |
+
from typing import Dict, List, Optional
|
14 |
+
import venv
|
15 |
+
import shutil
|
16 |
+
from dotenv import load_dotenv
|
17 |
+
|
18 |
+
# Setup logging
|
19 |
+
logging.basicConfig(
|
20 |
+
level=logging.INFO,
|
21 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
22 |
+
handlers=[
|
23 |
+
logging.FileHandler(Path(__file__).parent.parent.parent / 'logs' / 'deployment.log'),
|
24 |
+
logging.StreamHandler()
|
25 |
+
]
|
26 |
+
)
|
27 |
+
|
28 |
+
logger = logging.getLogger(__name__)
|
29 |
+
|
30 |
+
class ResearchMateDeployer:
|
31 |
+
"""Complete deployment system for ResearchMate"""
|
32 |
+
|
33 |
+
def __init__(self, project_root: Optional[Path] = None):
|
34 |
+
self.project_root = project_root or Path(__file__).parent.parent.parent
|
35 |
+
self.venv_path = self.project_root / "venv"
|
36 |
+
self.requirements_file = self.project_root / "requirements.txt"
|
37 |
+
self.is_windows = platform.system() == "Windows"
|
38 |
+
|
39 |
+
# Load environment variables from .env file
|
40 |
+
env_file = self.project_root / ".env"
|
41 |
+
if env_file.exists():
|
42 |
+
load_dotenv(env_file)
|
43 |
+
logger.info(f"Loaded environment variables from {env_file}")
|
44 |
+
else:
|
45 |
+
logger.warning(f"No .env file found at {env_file}")
|
46 |
+
|
47 |
+
def print_banner(self):
|
48 |
+
"""Print deployment banner"""
|
49 |
+
banner = """
|
50 |
+
ResearchMate Deployment System
|
51 |
+
==============================
|
52 |
+
AI Research Assistant powered by Groq Llama 3.3 70B
|
53 |
+
Version: 2.0.0
|
54 |
+
"""
|
55 |
+
print(banner)
|
56 |
+
logger.info("Starting ResearchMate deployment")
|
57 |
+
|
58 |
+
def check_python_version(self) -> bool:
|
59 |
+
"""Check if Python version is compatible"""
|
60 |
+
min_version = (3, 11)
|
61 |
+
current_version = sys.version_info[:2]
|
62 |
+
|
63 |
+
if current_version < min_version:
|
64 |
+
logger.error(f"Python {min_version[0]}.{min_version[1]}+ required, got {current_version[0]}.{current_version[1]}")
|
65 |
+
return False
|
66 |
+
|
67 |
+
logger.info(f"Python version {current_version[0]}.{current_version[1]} is compatible")
|
68 |
+
return True
|
69 |
+
|
70 |
+
def create_virtual_environment(self) -> bool:
|
71 |
+
"""Create virtual environment if it doesn't exist"""
|
72 |
+
# Check if we're in a Conda environment
|
73 |
+
if 'CONDA_DEFAULT_ENV' in os.environ:
|
74 |
+
logger.info(f"Using existing Conda environment: {os.environ['CONDA_DEFAULT_ENV']}")
|
75 |
+
return True
|
76 |
+
|
77 |
+
if self.venv_path.exists():
|
78 |
+
logger.info("Virtual environment already exists")
|
79 |
+
# Verify it's properly set up
|
80 |
+
python_exe = self.get_venv_python()
|
81 |
+
if python_exe.exists():
|
82 |
+
logger.info("Virtual environment is properly configured")
|
83 |
+
return True
|
84 |
+
else:
|
85 |
+
# Check if we're running from within the venv - if so, don't try to recreate
|
86 |
+
if sys.prefix == str(self.venv_path) or sys.base_prefix != sys.prefix:
|
87 |
+
logger.warning("Running from within virtual environment, cannot recreate. Assuming it's properly set up.")
|
88 |
+
return True
|
89 |
+
|
90 |
+
logger.warning("Virtual environment exists but Python executable not found, recreating...")
|
91 |
+
try:
|
92 |
+
shutil.rmtree(self.venv_path)
|
93 |
+
except PermissionError:
|
94 |
+
logger.error("Cannot recreate virtual environment - permission denied. Please deactivate the virtual environment first.")
|
95 |
+
return False
|
96 |
+
|
97 |
+
try:
|
98 |
+
logger.info("Creating virtual environment...")
|
99 |
+
venv.create(self.venv_path, with_pip=True)
|
100 |
+
|
101 |
+
# Verify the virtual environment was created properly
|
102 |
+
python_exe = self.get_venv_python()
|
103 |
+
if python_exe.exists():
|
104 |
+
logger.info("Virtual environment created successfully")
|
105 |
+
return True
|
106 |
+
else:
|
107 |
+
logger.error("Virtual environment creation failed - Python executable not found")
|
108 |
+
return False
|
109 |
+
|
110 |
+
except Exception as e:
|
111 |
+
logger.error(f"Failed to create virtual environment: {e}")
|
112 |
+
return False
|
113 |
+
|
114 |
+
def get_venv_python(self) -> Path:
|
115 |
+
"""Get path to Python executable in virtual environment"""
|
116 |
+
# If we're already in a virtual environment, use the current Python executable
|
117 |
+
if sys.prefix != sys.base_prefix or 'CONDA_DEFAULT_ENV' in os.environ:
|
118 |
+
return Path(sys.executable)
|
119 |
+
|
120 |
+
# Check for Conda environment first
|
121 |
+
if 'CONDA_DEFAULT_ENV' in os.environ:
|
122 |
+
return Path(sys.executable)
|
123 |
+
|
124 |
+
# Otherwise, construct the path to the venv Python executable
|
125 |
+
if self.is_windows:
|
126 |
+
return self.venv_path / "Scripts" / "python.exe"
|
127 |
+
else:
|
128 |
+
return self.venv_path / "bin" / "python"
|
129 |
+
|
130 |
+
def get_venv_pip(self) -> Path:
|
131 |
+
"""Get path to pip executable in virtual environment"""
|
132 |
+
# If we're already in a virtual environment (including Conda), use python -m pip
|
133 |
+
if sys.prefix != sys.base_prefix or 'CONDA_DEFAULT_ENV' in os.environ:
|
134 |
+
return Path(sys.executable)
|
135 |
+
|
136 |
+
# Otherwise, construct the path to the venv pip executable
|
137 |
+
if self.is_windows:
|
138 |
+
return self.venv_path / "Scripts" / "pip.exe"
|
139 |
+
else:
|
140 |
+
return self.venv_path / "bin" / "pip"
|
141 |
+
|
142 |
+
def install_dependencies(self):
|
143 |
+
"""Install Python dependencies"""
|
144 |
+
try:
|
145 |
+
logger.info("Installing dependencies...")
|
146 |
+
|
147 |
+
# Get executable paths
|
148 |
+
python_executable = self.get_venv_python()
|
149 |
+
|
150 |
+
# Check if we're in a virtual environment (including Conda)
|
151 |
+
in_venv = sys.prefix != sys.base_prefix or 'CONDA_DEFAULT_ENV' in os.environ
|
152 |
+
|
153 |
+
if in_venv:
|
154 |
+
logger.info("Running from within virtual environment, using current Python executable")
|
155 |
+
if 'CONDA_DEFAULT_ENV' in os.environ:
|
156 |
+
logger.info(f"Conda environment detected: {os.environ['CONDA_DEFAULT_ENV']}")
|
157 |
+
else:
|
158 |
+
# Check if executables exist
|
159 |
+
if not python_executable.exists():
|
160 |
+
logger.error(f"Python executable not found at: {python_executable}")
|
161 |
+
return False
|
162 |
+
|
163 |
+
pip_executable = self.get_venv_pip()
|
164 |
+
if not pip_executable.exists():
|
165 |
+
logger.error(f"Pip executable not found at: {pip_executable}")
|
166 |
+
return False
|
167 |
+
|
168 |
+
# Skip pip upgrade for Conda environments due to potential pyexpat issues
|
169 |
+
if 'CONDA_DEFAULT_ENV' not in os.environ:
|
170 |
+
logger.info("Upgrading pip...")
|
171 |
+
try:
|
172 |
+
result = subprocess.run([
|
173 |
+
str(python_executable), "-m", "pip", "install", "--upgrade", "pip"
|
174 |
+
], check=True, capture_output=True, text=True, cwd=self.project_root, timeout=60)
|
175 |
+
logger.info("Pip upgraded successfully")
|
176 |
+
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
|
177 |
+
logger.warning("Pip upgrade failed, skipping and continuing with installation")
|
178 |
+
logger.debug(f"Pip upgrade error: {e}")
|
179 |
+
else:
|
180 |
+
logger.info("Skipping pip upgrade in Conda environment")
|
181 |
+
|
182 |
+
# Install requirements
|
183 |
+
requirements_file = self.project_root / "requirements.txt"
|
184 |
+
if requirements_file.exists():
|
185 |
+
logger.info("Installing requirements from requirements.txt...")
|
186 |
+
try:
|
187 |
+
# For Conda environments, use --no-deps to avoid conflicts
|
188 |
+
cmd = [str(python_executable), "-m", "pip", "install", "-r", str(requirements_file)]
|
189 |
+
if 'CONDA_DEFAULT_ENV' in os.environ:
|
190 |
+
cmd.insert(-2, "--no-deps")
|
191 |
+
logger.info("Using --no-deps flag for Conda environment")
|
192 |
+
|
193 |
+
result = subprocess.run(
|
194 |
+
cmd,
|
195 |
+
check=True,
|
196 |
+
capture_output=True,
|
197 |
+
text=True,
|
198 |
+
cwd=self.project_root,
|
199 |
+
timeout=600
|
200 |
+
)
|
201 |
+
logger.info("Requirements installed successfully")
|
202 |
+
except subprocess.TimeoutExpired:
|
203 |
+
logger.error("Requirements installation timed out")
|
204 |
+
return False
|
205 |
+
else:
|
206 |
+
logger.warning("requirements.txt not found")
|
207 |
+
|
208 |
+
logger.info("Dependencies installed successfully")
|
209 |
+
return True
|
210 |
+
|
211 |
+
except subprocess.CalledProcessError as e:
|
212 |
+
logger.error(f"Failed to install dependencies: {e.stderr}")
|
213 |
+
# Try a fallback installation of critical packages
|
214 |
+
logger.info("Attempting fallback installation of critical packages...")
|
215 |
+
return self._install_critical_packages()
|
216 |
+
except Exception as e:
|
217 |
+
logger.error(f"Unexpected error during dependency installation: {e}")
|
218 |
+
return False
|
219 |
+
|
220 |
+
def _install_critical_packages(self):
|
221 |
+
"""Install only the most critical packages for ResearchMate to run"""
|
222 |
+
try:
|
223 |
+
python_executable = self.get_venv_python()
|
224 |
+
critical_packages = [
|
225 |
+
"fastapi", "uvicorn", "pydantic", "jinja2",
|
226 |
+
"python-dotenv", "groq", "requests"
|
227 |
+
]
|
228 |
+
|
229 |
+
logger.info("Installing critical packages individually...")
|
230 |
+
for package in critical_packages:
|
231 |
+
try:
|
232 |
+
subprocess.run([
|
233 |
+
str(python_executable), "-m", "pip", "install", package, "--no-deps"
|
234 |
+
], check=True, capture_output=True, text=True, cwd=self.project_root, timeout=60)
|
235 |
+
logger.info(f"Installed {package}")
|
236 |
+
except Exception as e:
|
237 |
+
logger.warning(f"Failed to install {package}: {e}")
|
238 |
+
|
239 |
+
return True
|
240 |
+
except Exception as e:
|
241 |
+
logger.error(f"Critical package installation failed: {e}")
|
242 |
+
return False
|
243 |
+
|
244 |
+
def create_directories(self) -> bool:
|
245 |
+
"""Create necessary directories"""
|
246 |
+
directories = [
|
247 |
+
"uploads", # User file uploads
|
248 |
+
"chroma_db", # ChromaDB database files
|
249 |
+
"chroma_persist", # ChromaDB persistence
|
250 |
+
"logs", # Application logs
|
251 |
+
"backups", # System backups (for manager.py)
|
252 |
+
"config" # Configuration files
|
253 |
+
]
|
254 |
+
|
255 |
+
try:
|
256 |
+
logger.info("Creating directories...")
|
257 |
+
for directory in directories:
|
258 |
+
dir_path = self.project_root / directory
|
259 |
+
dir_path.mkdir(parents=True, exist_ok=True)
|
260 |
+
logger.info(f"Created directory: {directory}")
|
261 |
+
|
262 |
+
# Ensure src/static exists (but don't recreate if it exists)
|
263 |
+
static_dir = self.project_root / "src" / "static"
|
264 |
+
static_dir.mkdir(parents=True, exist_ok=True)
|
265 |
+
logger.info("Verified src/static directory exists")
|
266 |
+
|
267 |
+
return True
|
268 |
+
except Exception as e:
|
269 |
+
logger.error(f"Failed to create directories: {e}")
|
270 |
+
return False
|
271 |
+
|
272 |
+
def check_environment_variables(self) -> bool:
|
273 |
+
"""Check for required environment variables"""
|
274 |
+
required_vars = ["GROQ_API_KEY"]
|
275 |
+
missing_vars = []
|
276 |
+
|
277 |
+
logger.info("Checking environment variables...")
|
278 |
+
|
279 |
+
for var in required_vars:
|
280 |
+
if not os.getenv(var):
|
281 |
+
missing_vars.append(var)
|
282 |
+
|
283 |
+
if missing_vars:
|
284 |
+
logger.warning("Missing environment variables:")
|
285 |
+
for var in missing_vars:
|
286 |
+
logger.warning(f" - {var}")
|
287 |
+
|
288 |
+
logger.info("Please set the missing variables:")
|
289 |
+
if self.is_windows:
|
290 |
+
for var in missing_vars:
|
291 |
+
logger.info(f" set {var}=your_value_here")
|
292 |
+
else:
|
293 |
+
for var in missing_vars:
|
294 |
+
logger.info(f" export {var}='your_value_here'")
|
295 |
+
|
296 |
+
logger.info("Get your Groq API key from: https://console.groq.com/keys")
|
297 |
+
return False
|
298 |
+
|
299 |
+
logger.info("All required environment variables are set")
|
300 |
+
return True
|
301 |
+
|
302 |
+
def test_imports(self) -> bool:
|
303 |
+
"""Test if all required modules can be imported"""
|
304 |
+
try:
|
305 |
+
logger.info("Testing imports...")
|
306 |
+
python_path = self.get_venv_python()
|
307 |
+
|
308 |
+
test_script = """
|
309 |
+
import sys
|
310 |
+
sys.path.append('.')
|
311 |
+
try:
|
312 |
+
from src.components import ResearchMate
|
313 |
+
from fastapi import FastAPI
|
314 |
+
from groq import Groq
|
315 |
+
import chromadb
|
316 |
+
print("All imports successful")
|
317 |
+
except ImportError as e:
|
318 |
+
print(f"Import error: {e}")
|
319 |
+
sys.exit(1)
|
320 |
+
"""
|
321 |
+
|
322 |
+
result = subprocess.run([
|
323 |
+
str(python_path), "-c", test_script
|
324 |
+
], capture_output=True, text=True, cwd=self.project_root)
|
325 |
+
|
326 |
+
if result.returncode == 0:
|
327 |
+
logger.info("All imports successful")
|
328 |
+
return True
|
329 |
+
else:
|
330 |
+
logger.error(f"Import test failed: {result.stderr}")
|
331 |
+
logger.error(f"Import test stdout: {result.stdout}")
|
332 |
+
return False
|
333 |
+
except Exception as e:
|
334 |
+
logger.error(f"Failed to test imports: {e}")
|
335 |
+
return False
|
336 |
+
|
337 |
+
def deploy(self) -> bool:
|
338 |
+
"""Run complete deployment process"""
|
339 |
+
self.print_banner()
|
340 |
+
|
341 |
+
steps = [
|
342 |
+
("Checking Python version", self.check_python_version),
|
343 |
+
("Creating virtual environment", self.create_virtual_environment),
|
344 |
+
("Installing dependencies", self.install_dependencies),
|
345 |
+
("Creating directories", self.create_directories),
|
346 |
+
("Checking environment variables", self.check_environment_variables),
|
347 |
+
("Testing imports", self.test_imports),
|
348 |
+
]
|
349 |
+
|
350 |
+
for step_name, step_func in steps:
|
351 |
+
logger.info(f"Running: {step_name}")
|
352 |
+
if not step_func():
|
353 |
+
logger.error(f"Failed at step: {step_name}")
|
354 |
+
return False
|
355 |
+
|
356 |
+
logger.info("Deployment completed successfully!")
|
357 |
+
logger.info("Web Interface: http://localhost:8000")
|
358 |
+
logger.info("API Documentation: http://localhost:8000/docs")
|
359 |
+
logger.info("Use Ctrl+C to stop the server")
|
360 |
+
|
361 |
+
return True
|
362 |
+
|
363 |
+
def start_server(self, host: str = None, port: int = None, reload: bool = False):
|
364 |
+
"""Start the ResearchMate server"""
|
365 |
+
try:
|
366 |
+
# Import settings to get default values
|
367 |
+
sys.path.append(str(self.project_root))
|
368 |
+
from src.settings import get_settings
|
369 |
+
settings = get_settings()
|
370 |
+
|
371 |
+
# Use provided values or defaults from settings
|
372 |
+
host = host or settings.server.host
|
373 |
+
port = port or settings.server.port
|
374 |
+
|
375 |
+
python_path = self.get_venv_python()
|
376 |
+
|
377 |
+
cmd = [
|
378 |
+
str(python_path), "-m", "uvicorn",
|
379 |
+
"main:app",
|
380 |
+
"--host", host,
|
381 |
+
"--port", str(port)
|
382 |
+
]
|
383 |
+
|
384 |
+
if reload:
|
385 |
+
cmd.append("--reload")
|
386 |
+
|
387 |
+
logger.info(f"Starting server on {host}:{port}")
|
388 |
+
subprocess.run(cmd, cwd=self.project_root)
|
389 |
+
|
390 |
+
except KeyboardInterrupt:
|
391 |
+
logger.info("Server stopped by user")
|
392 |
+
except Exception as e:
|
393 |
+
logger.error(f"Failed to start server: {e}")
|
394 |
+
|
395 |
+
def main():
|
396 |
+
"""Main deployment function"""
|
397 |
+
import argparse
|
398 |
+
|
399 |
+
parser = argparse.ArgumentParser(description="ResearchMate Deployment System")
|
400 |
+
parser.add_argument("--deploy-only", action="store_true", help="Only run deployment, don't start server")
|
401 |
+
parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
|
402 |
+
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
|
403 |
+
parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
|
404 |
+
|
405 |
+
args = parser.parse_args()
|
406 |
+
|
407 |
+
deployer = ResearchMateDeployer()
|
408 |
+
|
409 |
+
if deployer.deploy():
|
410 |
+
if not args.deploy_only:
|
411 |
+
deployer.start_server(host=args.host, port=args.port, reload=args.reload)
|
412 |
+
else:
|
413 |
+
sys.exit(1)
|
414 |
+
|
415 |
+
if __name__ == "__main__":
|
416 |
+
main()
|
src/scripts/dev_server.py
ADDED
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
ResearchMate Development Server
|
4 |
+
A complete Python-based development environment for ResearchMate
|
5 |
+
"""
|
6 |
+
|
7 |
+
import os
|
8 |
+
import sys
|
9 |
+
import subprocess
|
10 |
+
import threading
|
11 |
+
import time
|
12 |
+
import logging
|
13 |
+
from pathlib import Path
|
14 |
+
from typing import Dict, List, Optional
|
15 |
+
import signal
|
16 |
+
import webbrowser
|
17 |
+
from watchdog.observers import Observer
|
18 |
+
from watchdog.events import FileSystemEventHandler
|
19 |
+
import platform
|
20 |
+
import uvicorn
|
21 |
+
import socket
|
22 |
+
|
23 |
+
# Add the project root to Python path
|
24 |
+
sys.path.append(str(Path(__file__).parent.parent.parent))
|
25 |
+
|
26 |
+
# Import the main app from main.py
|
27 |
+
from main import app
|
28 |
+
|
29 |
+
# Setup logging
|
30 |
+
logging.basicConfig(
|
31 |
+
level=logging.INFO,
|
32 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
33 |
+
handlers=[
|
34 |
+
logging.FileHandler(Path(__file__).parent.parent.parent / 'logs' / 'development.log'),
|
35 |
+
logging.StreamHandler()
|
36 |
+
]
|
37 |
+
)
|
38 |
+
|
39 |
+
logger = logging.getLogger(__name__)
|
40 |
+
|
41 |
+
class FileChangeHandler(FileSystemEventHandler):
|
42 |
+
"""Handle file changes for auto-reload"""
|
43 |
+
|
44 |
+
def __init__(self, callback):
|
45 |
+
self.callback = callback
|
46 |
+
self.last_modified = {}
|
47 |
+
|
48 |
+
def on_modified(self, event):
|
49 |
+
if event.is_directory:
|
50 |
+
return
|
51 |
+
|
52 |
+
# Only watch Python files
|
53 |
+
if not event.src_path.endswith('.py'):
|
54 |
+
return
|
55 |
+
|
56 |
+
# Debounce rapid changes
|
57 |
+
current_time = time.time()
|
58 |
+
if event.src_path in self.last_modified:
|
59 |
+
if current_time - self.last_modified[event.src_path] < 1:
|
60 |
+
return
|
61 |
+
|
62 |
+
self.last_modified[event.src_path] = current_time
|
63 |
+
logger.info(f"File changed: {event.src_path}")
|
64 |
+
self.callback()
|
65 |
+
|
66 |
+
class ResearchMateDevServer:
|
67 |
+
"""Development server for ResearchMate"""
|
68 |
+
|
69 |
+
def __init__(self, project_root: Optional[Path] = None):
|
70 |
+
self.project_root = project_root or Path(__file__).parent.parent.parent
|
71 |
+
self.venv_path = self.project_root / "venv"
|
72 |
+
self.server_thread = None
|
73 |
+
self.observer = None
|
74 |
+
self.is_running = False
|
75 |
+
self.is_windows = platform.system() == "Windows"
|
76 |
+
# Store server config for restarts
|
77 |
+
self.server_host = "127.0.0.1"
|
78 |
+
self.server_port = 8000
|
79 |
+
|
80 |
+
def print_banner(self):
|
81 |
+
"""Print development server banner"""
|
82 |
+
banner = """
|
83 |
+
ResearchMate Development Server
|
84 |
+
=================================
|
85 |
+
AI Research Assistant - Development Mode
|
86 |
+
Auto-reload enabled for Python files
|
87 |
+
"""
|
88 |
+
print(banner)
|
89 |
+
logger.info("Starting ResearchMate development server")
|
90 |
+
|
91 |
+
def get_venv_python(self) -> Path:
|
92 |
+
"""Get path to Python executable in virtual environment"""
|
93 |
+
# If we're already in a virtual environment (including Conda), use the current Python executable
|
94 |
+
if sys.prefix != sys.base_prefix or 'CONDA_DEFAULT_ENV' in os.environ:
|
95 |
+
return Path(sys.executable)
|
96 |
+
|
97 |
+
# Otherwise, construct the path to the venv Python executable
|
98 |
+
if self.is_windows:
|
99 |
+
return self.venv_path / "Scripts" / "python.exe"
|
100 |
+
else:
|
101 |
+
return self.venv_path / "bin" / "python"
|
102 |
+
|
103 |
+
def check_virtual_environment(self) -> bool:
|
104 |
+
"""Check if virtual environment exists"""
|
105 |
+
# Since we're importing directly, just check if we can import the modules
|
106 |
+
try:
|
107 |
+
import main
|
108 |
+
logger.info("Successfully imported main application")
|
109 |
+
return True
|
110 |
+
except ImportError as e:
|
111 |
+
logger.error(f"Failed to import main application: {e}")
|
112 |
+
logger.error("Make sure you're in the correct environment with all dependencies installed")
|
113 |
+
return False
|
114 |
+
|
115 |
+
def check_port_available(self, host: str, port: int) -> bool:
|
116 |
+
"""Check if a port is available"""
|
117 |
+
try:
|
118 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
119 |
+
sock.bind((host, port))
|
120 |
+
return True
|
121 |
+
except OSError:
|
122 |
+
return False
|
123 |
+
|
124 |
+
def find_available_port(self, host: str, start_port: int = 8000, max_attempts: int = 10) -> Optional[int]:
|
125 |
+
"""Find an available port starting from start_port"""
|
126 |
+
for port in range(start_port, start_port + max_attempts):
|
127 |
+
if self.check_port_available(host, port):
|
128 |
+
return port
|
129 |
+
return None
|
130 |
+
|
131 |
+
def start_server_process(self, host: str = "127.0.0.1", port: int = 8000):
|
132 |
+
"""Start the server using uvicorn directly with the imported app"""
|
133 |
+
try:
|
134 |
+
# Check if the requested port is available
|
135 |
+
if not self.check_port_available(host, port):
|
136 |
+
logger.warning(f"Port {port} is already in use on {host}")
|
137 |
+
available_port = self.find_available_port(host, port)
|
138 |
+
if available_port:
|
139 |
+
logger.info(f"Using available port {available_port} instead")
|
140 |
+
port = available_port
|
141 |
+
self.server_port = port # Update stored port
|
142 |
+
else:
|
143 |
+
logger.error(f"No available ports found starting from {port}")
|
144 |
+
return False
|
145 |
+
|
146 |
+
logger.info(f"Starting server on {host}:{port}")
|
147 |
+
|
148 |
+
# Run uvicorn with the imported app in a separate thread
|
149 |
+
def run_server():
|
150 |
+
uvicorn.run(
|
151 |
+
app,
|
152 |
+
host=host,
|
153 |
+
port=port,
|
154 |
+
reload=False, # We handle reload ourselves with file watcher
|
155 |
+
log_level="info"
|
156 |
+
)
|
157 |
+
|
158 |
+
# Start server in background thread
|
159 |
+
self.server_thread = threading.Thread(target=run_server, daemon=True)
|
160 |
+
self.server_thread.start()
|
161 |
+
|
162 |
+
# Wait a moment for server to start
|
163 |
+
time.sleep(2)
|
164 |
+
|
165 |
+
logger.info("Server process started successfully")
|
166 |
+
return True
|
167 |
+
|
168 |
+
except Exception as e:
|
169 |
+
logger.error(f"Failed to start server: {e}")
|
170 |
+
import traceback
|
171 |
+
logger.error(f"Traceback: {traceback.format_exc()}")
|
172 |
+
return False
|
173 |
+
|
174 |
+
def stop_server_process(self):
|
175 |
+
"""Stop the server process"""
|
176 |
+
if self.server_thread:
|
177 |
+
logger.info("Stopping server...")
|
178 |
+
# Note: For development, we'll let the thread finish naturally
|
179 |
+
# In a real implementation, you might want to implement graceful shutdown
|
180 |
+
self.server_thread = None
|
181 |
+
|
182 |
+
def restart_server(self):
|
183 |
+
"""Restart the server"""
|
184 |
+
logger.info("File change detected - restarting server...")
|
185 |
+
logger.info("Note: For full restart, please stop and start the dev server manually")
|
186 |
+
# Note: Auto-restart is complex with embedded uvicorn
|
187 |
+
# For now, just log the change. User can manually restart.
|
188 |
+
|
189 |
+
def setup_file_watcher(self):
|
190 |
+
"""Setup file watcher for auto-reload"""
|
191 |
+
try:
|
192 |
+
self.observer = Observer()
|
193 |
+
|
194 |
+
# Watch source files
|
195 |
+
watch_paths = [
|
196 |
+
self.project_root / "src",
|
197 |
+
self.project_root / "main.py"
|
198 |
+
]
|
199 |
+
|
200 |
+
handler = FileChangeHandler(self.restart_server)
|
201 |
+
|
202 |
+
for path in watch_paths:
|
203 |
+
if path.exists():
|
204 |
+
if path.is_file():
|
205 |
+
self.observer.schedule(handler, str(path.parent), recursive=False)
|
206 |
+
else:
|
207 |
+
self.observer.schedule(handler, str(path), recursive=True)
|
208 |
+
|
209 |
+
self.observer.start()
|
210 |
+
logger.info("File watcher started")
|
211 |
+
|
212 |
+
except Exception as e:
|
213 |
+
logger.error(f"Failed to setup file watcher: {e}")
|
214 |
+
|
215 |
+
def stop_file_watcher(self):
|
216 |
+
"""Stop file watcher"""
|
217 |
+
if self.observer:
|
218 |
+
self.observer.stop()
|
219 |
+
self.observer.join()
|
220 |
+
self.observer = None
|
221 |
+
|
222 |
+
def open_browser(self, url: str):
|
223 |
+
"""Open browser after server starts"""
|
224 |
+
def open_after_delay():
|
225 |
+
time.sleep(3) # Wait for server to start
|
226 |
+
try:
|
227 |
+
webbrowser.open(url)
|
228 |
+
logger.info(f"Opened browser at {url}")
|
229 |
+
except Exception as e:
|
230 |
+
logger.warning(f"Could not open browser: {e}")
|
231 |
+
|
232 |
+
thread = threading.Thread(target=open_after_delay)
|
233 |
+
thread.daemon = True
|
234 |
+
thread.start()
|
235 |
+
|
236 |
+
def run_tests(self):
|
237 |
+
"""Run project tests"""
|
238 |
+
try:
|
239 |
+
logger.info("Running tests...")
|
240 |
+
logger.info("No tests configured - skipping test run")
|
241 |
+
|
242 |
+
except Exception as e:
|
243 |
+
logger.error(f"Failed to run tests: {e}")
|
244 |
+
|
245 |
+
def check_code_quality(self):
|
246 |
+
"""Check code quality with linting"""
|
247 |
+
try:
|
248 |
+
logger.info("Checking code quality...")
|
249 |
+
python_path = self.get_venv_python()
|
250 |
+
|
251 |
+
# Run flake8 if available
|
252 |
+
try:
|
253 |
+
result = subprocess.run([
|
254 |
+
str(python_path), "-m", "flake8",
|
255 |
+
"src/", "main.py", "--max-line-length=88"
|
256 |
+
], cwd=self.project_root, capture_output=True, text=True)
|
257 |
+
|
258 |
+
if result.returncode == 0:
|
259 |
+
logger.info("Code quality checks passed")
|
260 |
+
else:
|
261 |
+
logger.warning("Code quality issues found:")
|
262 |
+
print(result.stdout)
|
263 |
+
|
264 |
+
except FileNotFoundError:
|
265 |
+
logger.info("flake8 not installed, skipping code quality check")
|
266 |
+
|
267 |
+
except Exception as e:
|
268 |
+
logger.error(f"Failed to check code quality: {e}")
|
269 |
+
|
270 |
+
def start(self, host: str = "127.0.0.1", port: int = 8000, open_browser: bool = True):
|
271 |
+
"""Start the development server"""
|
272 |
+
self.print_banner()
|
273 |
+
|
274 |
+
if not self.check_virtual_environment():
|
275 |
+
return False
|
276 |
+
|
277 |
+
# Setup signal handlers
|
278 |
+
def signal_handler(signum, frame):
|
279 |
+
logger.info("Received interrupt signal")
|
280 |
+
self.stop()
|
281 |
+
sys.exit(0)
|
282 |
+
|
283 |
+
signal.signal(signal.SIGINT, signal_handler)
|
284 |
+
signal.signal(signal.SIGTERM, signal_handler)
|
285 |
+
|
286 |
+
try:
|
287 |
+
self.is_running = True
|
288 |
+
|
289 |
+
# Store server config for restarts
|
290 |
+
self.server_host = host
|
291 |
+
self.server_port = port
|
292 |
+
|
293 |
+
# Start server
|
294 |
+
if not self.start_server_process(host, port):
|
295 |
+
return False
|
296 |
+
|
297 |
+
# Use the actual port (might have changed if original was busy)
|
298 |
+
actual_port = self.server_port
|
299 |
+
|
300 |
+
# Setup file watcher
|
301 |
+
self.setup_file_watcher()
|
302 |
+
|
303 |
+
# Open browser
|
304 |
+
if open_browser:
|
305 |
+
self.open_browser(f"http://{host}:{actual_port}")
|
306 |
+
|
307 |
+
logger.info("Development server started successfully!")
|
308 |
+
logger.info(f"Web Interface: http://{host}:{actual_port}")
|
309 |
+
logger.info(f"API Documentation: http://{host}:{actual_port}/docs")
|
310 |
+
logger.info("File watcher enabled (manual restart required for changes)")
|
311 |
+
logger.info("Use Ctrl+C to stop")
|
312 |
+
|
313 |
+
# Keep the main thread alive
|
314 |
+
while self.is_running:
|
315 |
+
time.sleep(1)
|
316 |
+
|
317 |
+
except KeyboardInterrupt:
|
318 |
+
logger.info("Server stopped by user")
|
319 |
+
except Exception as e:
|
320 |
+
logger.error(f"Development server error: {e}")
|
321 |
+
finally:
|
322 |
+
self.stop()
|
323 |
+
|
324 |
+
def stop(self):
|
325 |
+
"""Stop the development server"""
|
326 |
+
self.is_running = False
|
327 |
+
self.stop_file_watcher()
|
328 |
+
self.stop_server_process()
|
329 |
+
logger.info("Development server stopped")
|
330 |
+
|
331 |
+
def main():
|
332 |
+
"""Main development server function"""
|
333 |
+
import argparse
|
334 |
+
|
335 |
+
parser = argparse.ArgumentParser(description="ResearchMate Development Server")
|
336 |
+
parser.add_argument("--host", default="127.0.0.1", help="Host to bind to")
|
337 |
+
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
|
338 |
+
parser.add_argument("--no-browser", action="store_true", help="Don't open browser")
|
339 |
+
parser.add_argument("--test", action="store_true", help="Run tests only")
|
340 |
+
parser.add_argument("--lint", action="store_true", help="Check code quality only")
|
341 |
+
|
342 |
+
args = parser.parse_args()
|
343 |
+
|
344 |
+
dev_server = ResearchMateDevServer()
|
345 |
+
|
346 |
+
if args.test:
|
347 |
+
dev_server.run_tests()
|
348 |
+
elif args.lint:
|
349 |
+
dev_server.check_code_quality()
|
350 |
+
else:
|
351 |
+
dev_server.start(
|
352 |
+
host=args.host,
|
353 |
+
port=args.port,
|
354 |
+
open_browser=not args.no_browser
|
355 |
+
)
|
356 |
+
|
357 |
+
if __name__ == "__main__":
|
358 |
+
main()
|