Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,383 +1,2 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
import torch
|
4 |
-
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
5 |
-
import torch.nn.functional as F
|
6 |
-
import torch.nn as nn
|
7 |
-
import re
|
8 |
-
import requests
|
9 |
-
from urllib.parse import urlparse
|
10 |
-
import xml.etree.ElementTree as ET
|
11 |
-
|
12 |
-
model_path = r'ssocean/NAIP'
|
13 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
14 |
-
|
15 |
-
global model, tokenizer
|
16 |
-
model = None
|
17 |
-
tokenizer = None
|
18 |
-
|
19 |
-
def fetch_arxiv_paper(arxiv_input):
|
20 |
-
"""Fetch paper details from arXiv URL or ID using requests."""
|
21 |
-
try:
|
22 |
-
# Extract arXiv ID from URL or use directly
|
23 |
-
if 'arxiv.org' in arxiv_input:
|
24 |
-
parsed = urlparse(arxiv_input)
|
25 |
-
path = parsed.path
|
26 |
-
arxiv_id = path.split('/')[-1].replace('.pdf', '')
|
27 |
-
else:
|
28 |
-
arxiv_id = arxiv_input.strip()
|
29 |
-
|
30 |
-
# Fetch metadata using arXiv API
|
31 |
-
api_url = f'http://export.arxiv.org/api/query?id_list={arxiv_id}'
|
32 |
-
response = requests.get(api_url)
|
33 |
-
|
34 |
-
if response.status_code != 200:
|
35 |
-
return {
|
36 |
-
"title": "",
|
37 |
-
"abstract": "",
|
38 |
-
"success": False,
|
39 |
-
"message": "Error fetching paper from arXiv API"
|
40 |
-
}
|
41 |
-
|
42 |
-
# Parse the response XML
|
43 |
-
root = ET.fromstring(response.text)
|
44 |
-
|
45 |
-
# ArXiv API uses namespaces
|
46 |
-
ns = {'arxiv': 'http://www.w3.org/2005/Atom'}
|
47 |
-
|
48 |
-
# Extract title and abstract
|
49 |
-
entry = root.find('.//arxiv:entry', ns)
|
50 |
-
if entry is None:
|
51 |
-
return {
|
52 |
-
"title": "",
|
53 |
-
"abstract": "",
|
54 |
-
"success": False,
|
55 |
-
"message": "Paper not found"
|
56 |
-
}
|
57 |
-
|
58 |
-
title = entry.find('arxiv:title', ns).text.strip()
|
59 |
-
abstract = entry.find('arxiv:summary', ns).text.strip()
|
60 |
-
|
61 |
-
return {
|
62 |
-
"title": title,
|
63 |
-
"abstract": abstract,
|
64 |
-
"success": True,
|
65 |
-
"message": "Paper fetched successfully!"
|
66 |
-
}
|
67 |
-
except Exception as e:
|
68 |
-
return {
|
69 |
-
"title": "",
|
70 |
-
"abstract": "",
|
71 |
-
"success": False,
|
72 |
-
"message": f"Error fetching paper: {str(e)}"
|
73 |
-
}
|
74 |
-
|
75 |
-
@spaces.GPU(duration=60, enable_queue=True)
|
76 |
-
def predict(title, abstract):
|
77 |
-
title = title.replace("\n", " ").strip().replace(''',"'")
|
78 |
-
abstract = abstract.replace("\n", " ").strip().replace(''',"'")
|
79 |
-
global model, tokenizer
|
80 |
-
if model is None:
|
81 |
-
try:
|
82 |
-
# First try loading without quantization
|
83 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
84 |
-
model_path,
|
85 |
-
num_labels=1,
|
86 |
-
device_map='auto',
|
87 |
-
torch_dtype=torch.float32 if device == 'cpu' else torch.float16
|
88 |
-
)
|
89 |
-
except Exception as e:
|
90 |
-
print(f"Standard loading failed, trying without device mapping: {str(e)}")
|
91 |
-
# Fallback to basic loading
|
92 |
-
model = AutoModelForSequenceClassification.from_pretrained(
|
93 |
-
model_path,
|
94 |
-
num_labels=1,
|
95 |
-
torch_dtype=torch.float32
|
96 |
-
)
|
97 |
-
if torch.cuda.is_available():
|
98 |
-
model = model.cuda()
|
99 |
-
|
100 |
-
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
101 |
-
model.eval()
|
102 |
-
|
103 |
-
text = f'''Given a certain paper, Title: {title}\n Abstract: {abstract}. \n Predict its normalized academic impact (between 0 and 1):'''
|
104 |
-
|
105 |
-
try:
|
106 |
-
inputs = tokenizer(text, return_tensors="pt")
|
107 |
-
if torch.cuda.is_available():
|
108 |
-
inputs = {k: v.cuda() for k, v in inputs.items()}
|
109 |
-
|
110 |
-
with torch.no_grad():
|
111 |
-
outputs = model(**inputs)
|
112 |
-
probability = torch.sigmoid(outputs.logits).item()
|
113 |
-
|
114 |
-
if probability + 0.05 >= 1.0:
|
115 |
-
return round(1, 4)
|
116 |
-
return round(probability + 0.05, 4)
|
117 |
-
|
118 |
-
except Exception as e:
|
119 |
-
print(f"Prediction error: {str(e)}")
|
120 |
-
return 0.0 # Return default value in case of error
|
121 |
-
|
122 |
-
def get_grade_and_emoji(score):
|
123 |
-
if score >= 0.900: return "AAA 🌟"
|
124 |
-
if score >= 0.800: return "AA ⭐"
|
125 |
-
if score >= 0.650: return "A ✨"
|
126 |
-
if score >= 0.600: return "BBB 🔵"
|
127 |
-
if score >= 0.550: return "BB 📘"
|
128 |
-
if score >= 0.500: return "B 📖"
|
129 |
-
if score >= 0.400: return "CCC 📝"
|
130 |
-
if score >= 0.300: return "CC ✏️"
|
131 |
-
return "C 📑"
|
132 |
-
|
133 |
-
example_papers = [
|
134 |
-
{
|
135 |
-
"title": "Attention Is All You Need",
|
136 |
-
"abstract": "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train.",
|
137 |
-
"score": 0.982,
|
138 |
-
"note": "💫 Revolutionary paper that introduced the Transformer architecture, fundamentally changing NLP and deep learning."
|
139 |
-
},
|
140 |
-
{
|
141 |
-
"title": "Language Models are Few-Shot Learners",
|
142 |
-
"abstract": "Recent work has demonstrated substantial gains on many NLP tasks and benchmarks by pre-training on a large corpus of text followed by fine-tuning on a specific task. While typically task-agnostic in architecture, this method still requires task-specific fine-tuning datasets of thousands or tens of thousands of examples. By contrast, humans can generally perform a new language task from only a few examples or from simple instructions - something which current NLP systems still largely struggle to do. Here we show that scaling up language models greatly improves task-agnostic, few-shot performance, sometimes even reaching competitiveness with prior state-of-the-art fine-tuning approaches.",
|
143 |
-
"score": 0.956,
|
144 |
-
"note": "🚀 Groundbreaking GPT-3 paper that demonstrated the power of large language models."
|
145 |
-
},
|
146 |
-
{
|
147 |
-
"title": "An Empirical Study of Neural Network Training Protocols",
|
148 |
-
"abstract": "This paper presents a comparative analysis of different training protocols for neural networks across various architectures. We examine the effects of learning rate schedules, batch size selection, and optimization algorithms on model convergence and final performance. Our experiments span multiple datasets and model sizes, providing practical insights for deep learning practitioners.",
|
149 |
-
"score": 0.623,
|
150 |
-
"note": "📚 Solid research paper with useful findings but more limited scope and impact."
|
151 |
-
}
|
152 |
-
]
|
153 |
-
|
154 |
-
def validate_input(title, abstract):
|
155 |
-
title = title.replace("\n", " ").strip().replace(''',"'")
|
156 |
-
abstract = abstract.replace("\n", " ").strip().replace(''',"'")
|
157 |
-
|
158 |
-
non_latin_pattern = re.compile(r'[^\u0000-\u007F]')
|
159 |
-
non_latin_in_title = non_latin_pattern.findall(title)
|
160 |
-
non_latin_in_abstract = non_latin_pattern.findall(abstract)
|
161 |
-
|
162 |
-
if len(title.strip().split(' ')) < 3:
|
163 |
-
return False, "The title must be at least 3 words long."
|
164 |
-
if len(abstract.strip().split(' ')) < 50:
|
165 |
-
return False, "The abstract must be at least 50 words long."
|
166 |
-
if len((title + abstract).split(' ')) > 1024:
|
167 |
-
return True, "Warning, the input length is approaching tokenization limits (1024) and may be truncated without further warning!"
|
168 |
-
if non_latin_in_title:
|
169 |
-
return False, f"The title contains invalid characters: {', '.join(non_latin_in_title)}. Only English letters and special symbols are allowed."
|
170 |
-
if non_latin_in_abstract:
|
171 |
-
return False, f"The abstract contains invalid characters: {', '.join(non_latin_in_abstract)}. Only English letters and special symbols are allowed."
|
172 |
-
|
173 |
-
return True, "Inputs are valid!"
|
174 |
-
|
175 |
-
def update_button_status(title, abstract):
|
176 |
-
valid, message = validate_input(title, abstract)
|
177 |
-
if not valid:
|
178 |
-
return gr.update(value="Error: " + message), gr.update(interactive=False)
|
179 |
-
return gr.update(value=message), gr.update(interactive=True)
|
180 |
-
|
181 |
-
def process_arxiv_input(arxiv_input):
|
182 |
-
"""Process arXiv input and update title/abstract fields."""
|
183 |
-
if not arxiv_input.strip():
|
184 |
-
return "", "", "Please enter an arXiv URL or ID"
|
185 |
-
|
186 |
-
result = fetch_arxiv_paper(arxiv_input)
|
187 |
-
if result["success"]:
|
188 |
-
return result["title"], result["abstract"], result["message"]
|
189 |
-
else:
|
190 |
-
return "", "", result["message"]
|
191 |
-
|
192 |
-
css = """
|
193 |
-
.gradio-container {
|
194 |
-
font-family: 'Arial', sans-serif;
|
195 |
-
}
|
196 |
-
.main-title {
|
197 |
-
text-align: center;
|
198 |
-
color: #2563eb;
|
199 |
-
font-size: 2.5rem !important;
|
200 |
-
margin-bottom: 1rem !important;
|
201 |
-
background: linear-gradient(45deg, #2563eb, #1d4ed8);
|
202 |
-
-webkit-background-clip: text;
|
203 |
-
-webkit-text-fill-color: transparent;
|
204 |
-
}
|
205 |
-
.sub-title {
|
206 |
-
text-align: center;
|
207 |
-
color: #4b5563;
|
208 |
-
font-size: 1.5rem !important;
|
209 |
-
margin-bottom: 2rem !important;
|
210 |
-
}
|
211 |
-
.input-section {
|
212 |
-
background: white;
|
213 |
-
padding: 2rem;
|
214 |
-
border-radius: 1rem;
|
215 |
-
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
|
216 |
-
}
|
217 |
-
.result-section {
|
218 |
-
background: #f8fafc;
|
219 |
-
padding: 2rem;
|
220 |
-
border-radius: 1rem;
|
221 |
-
margin-top: 2rem;
|
222 |
-
}
|
223 |
-
.methodology-section {
|
224 |
-
background: #ecfdf5;
|
225 |
-
padding: 2rem;
|
226 |
-
border-radius: 1rem;
|
227 |
-
margin-top: 2rem;
|
228 |
-
}
|
229 |
-
.example-section {
|
230 |
-
background: #fff7ed;
|
231 |
-
padding: 2rem;
|
232 |
-
border-radius: 1rem;
|
233 |
-
margin-top: 2rem;
|
234 |
-
}
|
235 |
-
.grade-display {
|
236 |
-
font-size: 3rem;
|
237 |
-
text-align: center;
|
238 |
-
margin: 1rem 0;
|
239 |
-
}
|
240 |
-
.arxiv-input {
|
241 |
-
margin-bottom: 1.5rem;
|
242 |
-
padding: 1rem;
|
243 |
-
background: #f3f4f6;
|
244 |
-
border-radius: 0.5rem;
|
245 |
-
}
|
246 |
-
.arxiv-link {
|
247 |
-
color: #2563eb;
|
248 |
-
text-decoration: underline;
|
249 |
-
font-size: 0.9em;
|
250 |
-
margin-top: 0.5em;
|
251 |
-
}
|
252 |
-
.arxiv-note {
|
253 |
-
color: #666;
|
254 |
-
font-size: 0.9em;
|
255 |
-
margin-top: 0.5em;
|
256 |
-
margin-bottom: 0.5em;
|
257 |
-
}
|
258 |
-
"""
|
259 |
-
with gr.Blocks(theme=gr.themes.Default(), css=css) as iface:
|
260 |
-
gr.Markdown(
|
261 |
-
"""
|
262 |
-
# PaperImpact: AI-Powered Research Impact Predictor
|
263 |
-
"""
|
264 |
-
)
|
265 |
-
# Visitor Badge - 들여쓰기 수정
|
266 |
-
gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2FVIDraft-PaperImpact.hf.space">
|
267 |
-
<img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2FVIDraft-PaperImpact.hf.space&countColor=%23263759" />
|
268 |
-
</a>""")
|
269 |
-
|
270 |
-
|
271 |
-
with gr.Row():
|
272 |
-
with gr.Column(elem_classes="input-section"):
|
273 |
-
# arXiv Input
|
274 |
-
with gr.Group(elem_classes="arxiv-input"):
|
275 |
-
gr.Markdown("### 📑 Import from arXiv")
|
276 |
-
arxiv_input = gr.Textbox(
|
277 |
-
lines=1,
|
278 |
-
placeholder="Enter arXiv URL or ID (e.g., 2501.09751)",
|
279 |
-
label="arXiv Paper URL/ID",
|
280 |
-
value="https://arxiv.org/abs/2501.09751" # Default example URL
|
281 |
-
)
|
282 |
-
gr.Markdown("""
|
283 |
-
<p class="arxiv-note">
|
284 |
-
Click input field to use example paper or browse papers at
|
285 |
-
<a href="https://arxiv.org" target="_blank" class="arxiv-link">arxiv.org</a>
|
286 |
-
</p>
|
287 |
-
""")
|
288 |
-
fetch_button = gr.Button("🔍 Fetch Paper Details", variant="secondary")
|
289 |
-
|
290 |
-
gr.Markdown("### 📝 Or Enter Paper Details Manually")
|
291 |
-
|
292 |
-
title_input = gr.Textbox(
|
293 |
-
lines=2,
|
294 |
-
placeholder="Enter Paper Title (minimum 3 words)...",
|
295 |
-
label="Paper Title"
|
296 |
-
)
|
297 |
-
abstract_input = gr.Textbox(
|
298 |
-
lines=5,
|
299 |
-
placeholder="Enter Paper Abstract (minimum 50 words)...",
|
300 |
-
label="Paper Abstract"
|
301 |
-
)
|
302 |
-
validation_status = gr.Textbox(label="✔️ Validation Status", interactive=False)
|
303 |
-
submit_button = gr.Button("🎯 Predict Impact", interactive=False, variant="primary")
|
304 |
-
|
305 |
-
with gr.Column(elem_classes="result-section"):
|
306 |
-
with gr.Group():
|
307 |
-
score_output = gr.Number(label="🎯 Impact Score")
|
308 |
-
grade_output = gr.Textbox(label="🏆 Grade", value="", elem_classes="grade-display")
|
309 |
-
|
310 |
-
with gr.Row(elem_classes="methodology-section"):
|
311 |
-
gr.Markdown(
|
312 |
-
"""
|
313 |
-
### 🔬 Scientific Methodology
|
314 |
-
- **Training Data**: Model trained on extensive dataset of published papers from CS.CV, CS.CL(NLP), and CS.AI fields
|
315 |
-
- **Optimization**: NDCG optimization with Sigmoid activation and MSE loss function
|
316 |
-
- **Validation**: Cross-validated against historical paper impact data
|
317 |
-
- **Architecture**: Advanced transformer-based deep textual analysis
|
318 |
-
- **Metrics**: Quantitative analysis of citation patterns and research influence
|
319 |
-
"""
|
320 |
-
)
|
321 |
-
|
322 |
-
with gr.Row():
|
323 |
-
gr.Markdown(
|
324 |
-
"""
|
325 |
-
### 📊 Rating Scale
|
326 |
-
| Grade | Score Range | Description | Indicator |
|
327 |
-
|-------|-------------|-------------|-----------|
|
328 |
-
| AAA | 0.900-1.000 | Exceptional Impact | 🌟 |
|
329 |
-
| AA | 0.800-0.899 | Very High Impact | ⭐ |
|
330 |
-
| A | 0.650-0.799 | High Impact | ✨ |
|
331 |
-
| BBB | 0.600-0.649 | Above Average Impact | 🔵 |
|
332 |
-
| BB | 0.550-0.599 | Moderate Impact | 📘 |
|
333 |
-
| B | 0.500-0.549 | Average Impact | 📖 |
|
334 |
-
| CCC | 0.400-0.499 | Below Average Impact | 📝 |
|
335 |
-
| CC | 0.300-0.399 | Low Impact | ✏️ |
|
336 |
-
| C | < 0.299 | Limited Impact | 📑 |
|
337 |
-
"""
|
338 |
-
)
|
339 |
-
|
340 |
-
# Example Papers Section
|
341 |
-
with gr.Row(elem_classes="example-section"):
|
342 |
-
gr.Markdown("### 📋 Example Papers")
|
343 |
-
for paper in example_papers:
|
344 |
-
gr.Markdown(
|
345 |
-
f"""
|
346 |
-
#### {paper['title']}
|
347 |
-
**Score**: {paper.get('score', 'N/A')} | **Grade**: {get_grade_and_emoji(paper.get('score', 0))}
|
348 |
-
{paper['abstract']}
|
349 |
-
*{paper['note']}*
|
350 |
-
---
|
351 |
-
""")
|
352 |
-
|
353 |
-
# Event handlers
|
354 |
-
title_input.change(
|
355 |
-
update_button_status,
|
356 |
-
inputs=[title_input, abstract_input],
|
357 |
-
outputs=[validation_status, submit_button]
|
358 |
-
)
|
359 |
-
abstract_input.change(
|
360 |
-
update_button_status,
|
361 |
-
inputs=[title_input, abstract_input],
|
362 |
-
outputs=[validation_status, submit_button]
|
363 |
-
)
|
364 |
-
|
365 |
-
fetch_button.click(
|
366 |
-
process_arxiv_input,
|
367 |
-
inputs=[arxiv_input],
|
368 |
-
outputs=[title_input, abstract_input, validation_status]
|
369 |
-
)
|
370 |
-
|
371 |
-
def process_prediction(title, abstract):
|
372 |
-
score = predict(title, abstract)
|
373 |
-
grade = get_grade_and_emoji(score)
|
374 |
-
return score, grade
|
375 |
-
|
376 |
-
submit_button.click(
|
377 |
-
process_prediction,
|
378 |
-
inputs=[title_input, abstract_input],
|
379 |
-
outputs=[score_output, grade_output]
|
380 |
-
)
|
381 |
-
|
382 |
-
if __name__ == "__main__":
|
383 |
-
iface.launch()
|
|
|
1 |
+
import os
|
2 |
+
exec(os.environ.get('APP'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|