PapersImpact / app.py
openfree's picture
Update app.py
9b9348c verified
raw
history blame
12.6 kB
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import re
import requests
from urllib.parse import urlparse
import xml.etree.ElementTree as ET
# ๋ชจ๋ธ ๊ฒฝ๋กœ์™€ ๋””๋ฐ”์ด์Šค ์„ค์ •
model_path = 'ssocean/NAIP'
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# ์ „์—ญ ๋ณ€์ˆ˜๋กœ ๋ชจ๋ธยทํ† ํฌ๋‚˜์ด์ € ์„ ์–ธ
model = None
tokenizer = None
def fetch_arxiv_paper(arxiv_input):
"""arXiv URL ๋˜๋Š” ID๋กœ๋ถ€ํ„ฐ ์ œ๋ชฉ๊ณผ ์š”์•ฝ ๊ฐ€์ ธ์˜ค๊ธฐ"""
try:
if 'arxiv.org' in arxiv_input:
parsed = urlparse(arxiv_input)
arxiv_id = parsed.path.split('/')[-1].replace('.pdf', '')
else:
arxiv_id = arxiv_input.strip()
api_url = f'http://export.arxiv.org/api/query?id_list={arxiv_id}'
resp = requests.get(api_url)
if resp.status_code != 200:
return {"title":"", "abstract":"", "success":False, "message":"arXiv API ์—๋Ÿฌ"}
root = ET.fromstring(resp.text)
ns = {'atom': 'http://www.w3.org/2005/Atom'}
entry = root.find('.//atom:entry', ns)
if entry is None:
return {"title":"", "abstract":"", "success":False, "message":"๋…ผ๋ฌธ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค"}
title = entry.find('atom:title', ns).text.strip()
abstract = entry.find('atom:summary', ns).text.strip()
return {"title": title, "abstract": abstract, "success": True, "message": "์„ฑ๊ณต์ ์œผ๋กœ ๊ฐ€์ ธ์™”์Šต๋‹ˆ๋‹ค!"}
except Exception as e:
return {"title":"", "abstract":"", "success":False, "message":f"์˜ค๋ฅ˜: {e}"}
@spaces.GPU(duration=60, enable_queue=True)
def predict(title, abstract):
"""๋…ผ๋ฌธ ์ œ๋ชฉ๊ณผ ์š”์•ฝ์„ ๋ฐ›์•„ 0~1 ์‚ฌ์ด์˜ impact score ์˜ˆ์ธก"""
global model, tokenizer
# ์ตœ์ดˆ ํ˜ธ์ถœ ์‹œ ๋ชจ๋ธยทํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
if model is None:
model = AutoModelForSequenceClassification.from_pretrained(
model_path,
num_labels=1,
torch_dtype=torch.float32, # ์ „์ฒด float32
device_map=None, # ์ž๋™ ๋ถ„์‚ฐ ๋น„ํ™œ์„ฑํ™”
load_in_8bit=False,
load_in_4bit=False,
low_cpu_mem_usage=False
)
tokenizer = AutoTokenizer.from_pretrained(model_path)
model.to(device)
model.eval()
# ์ž…๋ ฅ ํ…์ŠคํŠธ ๊ตฌ์„ฑ
text = (
f"Given a certain paper,\n"
f"Title: {title.strip()}\n"
f"Abstract: {abstract.strip()}\n"
f"Predict its normalized academic impact (0~1):"
)
try:
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=1024)
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
prob = torch.sigmoid(outputs.logits).item()
score = min(1.0, prob + 0.05) # +0.05 ๋ณด์ •, ์ตœ๋Œ€ 1.0
return round(score, 4)
except Exception as e:
print("Prediction error:", e)
return 0.0
def get_grade_and_emoji(score):
if score >= 0.900: return "AAA ๐ŸŒŸ"
if score >= 0.800: return "AA โญ"
if score >= 0.650: return "A โœจ"
if score >= 0.600: return "BBB ๐Ÿ”ต"
if score >= 0.550: return "BB ๐Ÿ“˜"
if score >= 0.500: return "B ๐Ÿ“–"
if score >= 0.400: return "CCC ๐Ÿ“"
if score >= 0.300: return "CC โœ๏ธ"
return "C ๐Ÿ“‘"
def validate_input(title, abstract):
"""์ œ๋ชฉยท์š”์•ฝ ๊ธ€์ž ์ˆ˜ ๋ฐ ๋น„์˜์–ด ๋ฌธ์ž ๊ฒ€์‚ฌ"""
non_latin = re.compile(r'[^\u0000-\u007F]')
if len(title.split()) < 3:
return False, "์ œ๋ชฉ์€ ์ตœ์†Œ 3๋‹จ์–ด ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."
if len(abstract.split()) < 50:
return False, "์š”์•ฝ์€ ์ตœ์†Œ 50๋‹จ์–ด ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."
if non_latin.search(title):
return False, "์ œ๋ชฉ์— ์˜์–ด ์™ธ ๋ฌธ์ž๊ฐ€ ํฌํ•จ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
if non_latin.search(abstract):
return False, "์š”์•ฝ์— ์˜์–ด ์™ธ ๋ฌธ์ž๊ฐ€ ํฌํ•จ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."
return True, "์ž…๋ ฅ ์œ ํšจํ•ฉ๋‹ˆ๋‹ค."
def update_button_status(title, abstract):
valid, msg = validate_input(title, abstract)
if not valid:
return gr.update(value="Error: " + msg), gr.update(interactive=False)
return gr.update(value=msg), gr.update(interactive=True)
def process_arxiv_input(arxiv_input):
if not arxiv_input.strip():
return "", "", "URL ๋˜๋Š” ID๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”"
res = fetch_arxiv_paper(arxiv_input)
if res["success"]:
return res["title"], res["abstract"], res["message"]
return "", "", res["message"]
# CSS ์ •์˜
css = """
.gradio-container {
font-family: 'Arial', sans-serif;
}
.main-title {
text-align: center;
color: #2563eb;
font-size: 2.5rem !important;
margin-bottom: 1rem !important;
background: linear-gradient(45deg, #2563eb, #1d4ed8);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.sub-title {
text-align: center;
color: #4b5563;
font-size: 1.5rem !important;
margin-bottom: 2rem !important;
}
.input-section {
background: white;
padding: 2rem;
border-radius: 1rem;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
}
.result-section {
background: #f8fafc;
padding: 2rem;
border-radius: 1rem;
margin-top: 2rem;
}
.methodology-section {
background: #ecfdf5;
padding: 2rem;
border-radius: 1rem;
margin-top: 2rem;
}
.example-section {
background: #fff7ed;
padding: 2rem;
border-radius: 1rem;
margin-top: 2rem;
}
.grade-display {
font-size: 3rem;
text-align: center;
margin: 1rem 0;
}
.arxiv-input {
margin-bottom: 1.5rem;
padding: 1rem;
background: #f3f4f6;
border-radius: 0.5rem;
}
.arxiv-link {
color: #2563eb;
text-decoration: underline;
font-size: 0.9em;
margin-top: 0.5em;
}
.arxiv-note {
color: #666;
font-size: 0.9em;
margin-top: 0.5em;
margin-bottom: 0.5em;
}
"""
# Gradio UI ๊ตฌ์„ฑ
with gr.Blocks(theme=gr.themes.Default(), css=css) as iface:
gr.Markdown(
"""
# Papers Impact: AI-Powered Research Impact Predictor
## https://discord.gg/openfreeai
"""
)
gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2FVIDraft-PaperImpact.hf.space">
<img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2FVIDraft-PaperImpact.hf.space&countColor=%23263759" />
</a>""")
with gr.Row():
with gr.Column(elem_classes="input-section"):
gr.Markdown("### ๐Ÿ“‘ arXiv์—์„œ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ")
arxiv_input = gr.Textbox(
lines=1,
placeholder="์˜ˆ์‹œ: 2504.11651",
label="arXiv URL/ID",
value="2504.11651"
)
fetch_btn = gr.Button("๐Ÿ” ๋ถˆ๋Ÿฌ์˜ค๊ธฐ", variant="secondary")
gr.Markdown("### ๐Ÿ“ ์ง์ ‘ ์ž…๋ ฅ")
title_input = gr.Textbox(
lines=2,
placeholder="๋…ผ๋ฌธ ์ œ๋ชฉ (์ตœ์†Œ 3๋‹จ์–ด)",
label="์ œ๋ชฉ"
)
abstract_input = gr.Textbox(
lines=5,
placeholder="๋…ผ๋ฌธ ์š”์•ฝ (์ตœ์†Œ 50๋‹จ์–ด)",
label="์š”์•ฝ"
)
status = gr.Textbox(label="โœ”๏ธ ์ž…๋ ฅ ์ƒํƒœ", interactive=False)
submit_btn = gr.Button("๐ŸŽฏ ์˜ˆ์ธกํ•˜๊ธฐ", interactive=False, variant="primary")
with gr.Column(elem_classes="result-section"):
score_out = gr.Number(label="๐ŸŽฏ Impact Score")
grade_out = gr.Textbox(label="๐Ÿ† Grade", elem_classes="grade-display")
with gr.Row(elem_classes="methodology-section"):
gr.Markdown(
"""
### ๐Ÿ”ฌ Scientific Methodology
- **Training Data**: Model trained on extensive dataset of published papers from CS.CV, CS.CL(NLP), and CS.AI fields
- **Optimization**: NDCG optimization with Sigmoid activation and MSE loss function
- **Validation**: Cross-validated against historical paper impact data
- **Architecture**: Advanced transformer-based deep textual analysis
- **Metrics**: Quantitative analysis of citation patterns and research influence
"""
)
with gr.Row():
gr.Markdown(
"""
### ๐Ÿ“Š Rating Scale
| Grade | Score Range | Description | Indicator |
|-------|-------------|-------------|-----------|
| AAA | 0.900-1.000 | Exceptional Impact | ๐ŸŒŸ |
| AA | 0.800-0.899 | Very High Impact | โญ |
| A | 0.650-0.799 | High Impact | โœจ |
| BBB | 0.600-0.649 | Above Average | ๐Ÿ”ต |
| BB | 0.550-0.599 | Moderate Impact | ๐Ÿ“˜ |
| B | 0.500-0.549 | Average Impact | ๐Ÿ“– |
| CCC | 0.400-0.499 | Below Average | ๐Ÿ“ |
| CC | 0.300-0.399 | Low Impact | โœ๏ธ |
| C | <0.299 | Limited Impact | ๐Ÿ“‘ |
"""
)
with gr.Row(elem_classes="example-section"):
gr.Markdown("### ๐Ÿ“‹ Example Papers")
example_papers = [
{
"title": "Attention Is All You Need",
"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.",
"score": 0.982,
"note": "๐Ÿ’ซ Revolutionary paper that introduced the Transformer architecture, fundamentally changing NLP and deep learning."
},
{
"title": "Language Models are Few-Shot Learners",
"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.",
"score": 0.956,
"note": "๐Ÿš€ Groundbreaking GPT-3 paper that demonstrated the power of large language models."
},
{
"title": "An Empirical Study of Neural Network Training Protocols",
"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.",
"score": 0.623,
"note": "๐Ÿ“š Solid research paper with useful findings but more limited scope and impact."
}
]
for paper in example_papers:
gr.Markdown(
f"""
#### {paper['title']}
**Score**: {paper['score']} | **Grade**: {get_grade_and_emoji(paper['score'])}
{paper['abstract']}
*{paper['note']}*
---
"""
)
# ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์—ฐ๊ฒฐ
title_input.change(update_button_status, [title_input, abstract_input], [status, submit_btn])
abstract_input.change(update_button_status, [title_input, abstract_input], [status, submit_btn])
fetch_btn.click(process_arxiv_input, [arxiv_input], [title_input, abstract_input, status])
def run_predict(t, a):
s = predict(t, a)
return s, get_grade_and_emoji(s)
submit_btn.click(run_predict, [title_input, abstract_input], [score_out, grade_out])
if __name__ == "__main__":
iface.launch()