PaperImpact / app.py
openfree's picture
Create app.py
d94f82b verified
raw
history blame
9.04 kB
import gradio as gr
import spaces
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch.nn.functional as F
import torch.nn as nn
import re
model_path = r'ssocean/NAIP'
device = 'cuda:0'
global model, tokenizer
model = None
tokenizer = None
@spaces.GPU(duration=60, enable_queue=True)
def predict(title, abstract):
title = title.replace("\n", " ").strip().replace(''',"'")
abstract = abstract.replace("\n", " ").strip().replace(''',"'")
global model, tokenizer
if model is None:
model = AutoModelForSequenceClassification.from_pretrained(
model_path,
num_labels=1,
load_in_8bit=True,)
tokenizer = AutoTokenizer.from_pretrained(model_path)
model.eval()
text = f'''Given a certain paper, Title: {title}\n Abstract: {abstract}. \n Predict its normalized academic impact (between 0 and 1):'''
inputs = tokenizer(text, return_tensors="pt").to(device)
with torch.no_grad():
outputs = model(**inputs)
probability = torch.sigmoid(outputs.logits).item()
if probability + 0.05 >= 1.0:
return round(1, 4)
return round(probability + 0.05, 4)
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 πŸ“‘"
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,
"grade": "AAA 🌟",
"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,
"grade": "AAA 🌟",
"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,
"grade": "BBB πŸ”΅",
"note": "Solid research paper with useful findings but more limited scope and impact."
}
]
def validate_input(title, abstract):
title = title.replace("\n", " ").strip().replace(''',"'")
abstract = abstract.replace("\n", " ").strip().replace(''',"'")
non_latin_pattern = re.compile(r'[^\u0000-\u007F]')
non_latin_in_title = non_latin_pattern.findall(title)
non_latin_in_abstract = non_latin_pattern.findall(abstract)
if len(title.strip().split(' ')) < 3:
return False, "The title must be at least 3 words long."
if len(abstract.strip().split(' ')) < 50:
return False, "The abstract must be at least 50 words long."
if len((title + abstract).split(' ')) > 1024:
return True, "Warning, the input length is approaching tokenization limits (1024) and may be truncated without further warning!"
if non_latin_in_title:
return False, f"The title contains invalid characters: {', '.join(non_latin_in_title)}. Only English letters and special symbols are allowed."
if non_latin_in_abstract:
return False, f"The abstract contains invalid characters: {', '.join(non_latin_in_abstract)}. Only English letters and special symbols are allowed."
return True, "Inputs are valid! Good to go!"
def update_button_status(title, abstract):
valid, message = validate_input(title, abstract)
if not valid:
return gr.update(value="Error: " + message), gr.update(interactive=False)
return gr.update(value=message), gr.update(interactive=True)
with gr.Blocks(theme=gr.themes.Default()) as iface:
gr.Markdown("""
# PaperImpact: AI-Powered Research Impact Predictor
### Estimate the future academic impact from the title and abstract with advanced AI analysis
""")
with gr.Row():
with gr.Column():
title_input = gr.Textbox(
lines=2,
placeholder="Enter Paper Title (minimum 3 words)...",
label="Paper Title"
)
abstract_input = gr.Textbox(
lines=5,
placeholder="Enter Paper Abstract (minimum 50 words)...",
label="Paper Abstract"
)
validation_status = gr.Textbox(label="Validation Status", interactive=False)
submit_button = gr.Button("Predict Impact", interactive=False)
with gr.Column():
score_output = gr.Number(label="Impact Score")
grade_output = gr.Textbox(label="Grade", value="")
# Scientific 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 with verified citation impacts
- Optimization Method: Uses NDCG (Normalized Discounted Cumulative Gain) optimization with Sigmoid activation and MSE loss function
- Validation Process: Cross-validated against historical paper impact data to ensure prediction accuracy
- Model Architecture: Utilizes advanced transformer-based architecture for deep textual analysis
- Objective Metrics: Predictions based on quantitative analysis of citation patterns and research influence
""")
# Rating Scale Section
gr.Markdown("""
### πŸ“Š Rating Scale
- 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 Impact
- BB (0.550-0.599) πŸ“˜ - Moderate Impact
- B (0.500-0.549) πŸ“– - Average Impact
- CCC (0.400-0.499) πŸ“ - Below Average Impact
- CC (0.300-0.399) ✏️ - Low Impact
- C (below 0.299) πŸ“‘ - Limited Impact
""")
# Example Papers Section
gr.Markdown("""
### πŸ“‹ Example Papers
""")
for paper in example_papers:
gr.Markdown(f"""
#### {paper['title']} - {paper['grade']} ({paper['score']})
{paper['abstract']}
*Note: {paper['note']}*
---
""")
# Important Notes Section
gr.Markdown("""
### πŸ“Œ Important Notes
- This tool is designed for research in Computer Vision (CV), Natural Language Processing (NLP), and AI fields only
- Predictions are based on title and abstract analysis using advanced AI models
- Scores reflect potential academic impact, not paper quality or novelty
- For research and educational purposes only
""")
# Event handlers
title_input.change(
update_button_status,
inputs=[title_input, abstract_input],
outputs=[validation_status, submit_button]
)
abstract_input.change(
update_button_status,
inputs=[title_input, abstract_input],
outputs=[validation_status, submit_button]
)
def process_prediction(title, abstract):
score = predict(title, abstract)
grade = get_grade_and_emoji(score)
return score, grade
submit_button.click(
process_prediction,
inputs=[title_input, abstract_input],
outputs=[score_output, grade_output]
)
if __name__ == "__main__":
iface.launch()