Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,13 +5,14 @@ import gradio as gr
|
|
5 |
import time
|
6 |
import os
|
7 |
import json
|
|
|
|
|
|
|
|
|
|
|
8 |
import re
|
9 |
from datetime import datetime
|
10 |
-
import
|
11 |
-
from transformers import AutoTokenizer, AutoModel
|
12 |
-
import networkx as nx
|
13 |
-
from pyvis.network import Network
|
14 |
-
import matplotlib.pyplot as plt
|
15 |
|
16 |
# ๐งโโ๏ธ Magical Utility Functions ๐งโโ๏ธ
|
17 |
|
@@ -19,6 +20,31 @@ def safe_filename(title):
|
|
19 |
"""Convert a string to a safe filename. No more 'file not found' nightmares! ๐
โโ๏ธ๐"""
|
20 |
return re.sub(r'[^\w\-_\. ]', '_', title)
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
# ๐ต๏ธโโ๏ธ Data Fetching and Caching Shenanigans ๐ต๏ธโโ๏ธ
|
23 |
|
24 |
def get_rank_papers(url, progress=gr.Progress(track_tqdm=True)):
|
@@ -54,8 +80,19 @@ def get_rank_papers(url, progress=gr.Progress(track_tqdm=True)):
|
|
54 |
|
55 |
Github_Star = ppr.find('span', class_='badge badge-secondary').text.strip().replace(',', '') if ppr.find('span', class_='badge badge-secondary') else "0"
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
if title not in data_list:
|
58 |
-
data_list[title] = {'link': link, 'Github Star': int(Github_Star), '
|
59 |
else:
|
60 |
break_duplicate -= 1
|
61 |
if break_duplicate == 0:
|
@@ -90,53 +127,119 @@ def load_and_cache_data(url, cache_file):
|
|
90 |
save_cached_data(new_data, cache_file)
|
91 |
return new_data
|
92 |
|
93 |
-
#
|
94 |
|
95 |
-
def
|
96 |
-
"""
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
for title in titles:
|
104 |
-
tokens = tokenizer(title, return_tensors="pt", padding=True, truncation=True)
|
105 |
-
output = model(**tokens)
|
106 |
-
embeddings.append(output.last_hidden_state.mean(dim=1).squeeze())
|
107 |
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
|
115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
122 |
|
123 |
-
|
124 |
|
125 |
-
def
|
126 |
-
"""
|
127 |
-
|
|
|
|
|
128 |
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
|
138 |
-
def
|
139 |
-
"""
|
140 |
all_data = {}
|
141 |
for category in ["top", "latest", "greatest"]:
|
142 |
cache_file = f"{category}_papers_cache.json"
|
@@ -144,35 +247,27 @@ def analyze_and_generate_graph(progress=gr.Progress()):
|
|
144 |
if data:
|
145 |
all_data.update(data)
|
146 |
|
147 |
-
|
|
|
148 |
|
149 |
-
|
150 |
-
|
|
|
|
|
151 |
|
152 |
-
|
153 |
-
|
|
|
|
|
|
|
|
|
154 |
|
155 |
-
|
156 |
-
graph_file = visualize_graph(G, titles)
|
157 |
-
|
158 |
-
summary = f"๐ Papers analyzed: {len(titles)}\n"
|
159 |
-
summary += f"โ
Graph generated and visualized.\n"
|
160 |
-
|
161 |
-
return summary, graph_file
|
162 |
-
|
163 |
-
# ๐ Define load_all_data Properly ๐
|
164 |
-
|
165 |
-
def load_all_data():
|
166 |
-
"""Load data for all categories and prepare for display."""
|
167 |
-
top_count, top_html = update_display("top")
|
168 |
-
new_count, new_html = update_display("latest")
|
169 |
-
greatest_count, greatest_html = update_display("greatest")
|
170 |
-
return top_count, top_html, new_count, new_html, greatest_count, greatest_html
|
171 |
|
172 |
# ๐ญ Gradio Interface: Where the Magic Happens ๐ญ
|
173 |
|
174 |
with gr.Blocks() as demo:
|
175 |
-
gr.Markdown("<h1><center>Papers Leaderboard
|
176 |
|
177 |
with gr.Tab("Top Trending Papers"):
|
178 |
top_count = gr.Textbox(label="Number of Papers Fetched")
|
@@ -192,15 +287,16 @@ with gr.Blocks() as demo:
|
|
192 |
greatest_button = gr.Button("Refresh Leaderboard")
|
193 |
greatest_button.click(fn=lambda: update_display("greatest"), inputs=None, outputs=[greatest_count, greatest_html])
|
194 |
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
|
|
200 |
|
201 |
# Load initial data for all tabs
|
202 |
demo.load(fn=load_all_data, outputs=[top_count, top_html, new_count, new_html, greatest_count, greatest_html])
|
203 |
|
204 |
# ๐ Launch the Gradio interface with a public link
|
205 |
-
print("๐ญ Launching the Papers Leaderboard
|
206 |
demo.launch(share=True)
|
|
|
5 |
import time
|
6 |
import os
|
7 |
import json
|
8 |
+
import PyPDF2
|
9 |
+
import io
|
10 |
+
import asyncio
|
11 |
+
import aiohttp
|
12 |
+
import aiofiles
|
13 |
import re
|
14 |
from datetime import datetime
|
15 |
+
import base64
|
|
|
|
|
|
|
|
|
16 |
|
17 |
# ๐งโโ๏ธ Magical Utility Functions ๐งโโ๏ธ
|
18 |
|
|
|
20 |
"""Convert a string to a safe filename. No more 'file not found' nightmares! ๐
โโ๏ธ๐"""
|
21 |
return re.sub(r'[^\w\-_\. ]', '_', title)
|
22 |
|
23 |
+
def create_date_directory():
|
24 |
+
"""Create a directory named with the current date. It's like a time capsule for your downloads! ๐๏ธ๐ฆ"""
|
25 |
+
date_str = datetime.now().strftime("%Y-%m-%d")
|
26 |
+
os.makedirs(date_str, exist_ok=True)
|
27 |
+
return date_str
|
28 |
+
|
29 |
+
def get_base64_download_link(content, filename):
|
30 |
+
"""Create a base64 download link for text content. It's like teleportation for your files! ๐๐ฒ"""
|
31 |
+
b64 = base64.b64encode(content.encode()).decode()
|
32 |
+
return f'<a href="data:text/plain;base64,{b64}" download="{filename}">Download {filename}</a>'
|
33 |
+
|
34 |
+
# ๐ฌ Animated Banner Messages ๐ฌ
|
35 |
+
def animated_banner(message, emoji):
|
36 |
+
"""Create an animated banner message. It's like a tiny parade for your console! ๐๐ฉ"""
|
37 |
+
frames = [
|
38 |
+
f"โโโโโ {emoji} โโโโโ\nโ {message:^16} โ\nโโโโโโโโโโโโโโ",
|
39 |
+
f"โโโโโ {emoji} โโโโโ\nโ {message:^16} โ\nโโโโโโโโโโโโโโ",
|
40 |
+
f"โโโโโ{emoji}โโโโโ\nโ {message:^14} โ\nโโโโโโโโโโโโ",
|
41 |
+
f"โโโโ{emoji}โโโโ\nโ {message:^12} โ\nโโโโโโโโโโ",
|
42 |
+
f"โโโ{emoji}โโโ\nโ {message:^10} โ\nโโโโโโโโ",
|
43 |
+
f"โโ{emoji}โโ\nโ {message:^8} โ\nโโโโโโ",
|
44 |
+
f"โ{emoji}โ\nโ {message:^6} โ\nโโโโ",
|
45 |
+
]
|
46 |
+
return frames
|
47 |
+
|
48 |
# ๐ต๏ธโโ๏ธ Data Fetching and Caching Shenanigans ๐ต๏ธโโ๏ธ
|
49 |
|
50 |
def get_rank_papers(url, progress=gr.Progress(track_tqdm=True)):
|
|
|
80 |
|
81 |
Github_Star = ppr.find('span', class_='badge badge-secondary').text.strip().replace(',', '') if ppr.find('span', class_='badge badge-secondary') else "0"
|
82 |
|
83 |
+
pdf_link = ''
|
84 |
+
try:
|
85 |
+
response_link = session.get(link, headers=headers)
|
86 |
+
soup_link = BeautifulSoup(response_link.text, 'html.parser')
|
87 |
+
paper_info_link = soup_link.find_all('div', class_='paper-abstract')
|
88 |
+
pdf_link = paper_info_link[0].find('div', class_='col-md-12').find('a')['href']
|
89 |
+
except Exception as e:
|
90 |
+
print(f"Failed to retrieve PDF link for {title}: {e}")
|
91 |
+
|
92 |
+
print(f"Title: {title}, Link: {link}, Github Star: {Github_Star}, PDF Link: {pdf_link}")
|
93 |
+
|
94 |
if title not in data_list:
|
95 |
+
data_list[title] = {'link': link, 'Github Star': int(Github_Star), 'pdf_link': pdf_link.strip()}
|
96 |
else:
|
97 |
break_duplicate -= 1
|
98 |
if break_duplicate == 0:
|
|
|
127 |
save_cached_data(new_data, cache_file)
|
128 |
return new_data
|
129 |
|
130 |
+
# ๐ Data Processing and Display Magic ๐
|
131 |
|
132 |
+
def format_dataframe(data):
|
133 |
+
"""Format data into a pretty DataFrame. It's like giving your data a makeover! ๐
๐"""
|
134 |
+
if not data:
|
135 |
+
print("No data found to format.")
|
136 |
+
return pd.DataFrame()
|
137 |
|
138 |
+
df = pd.DataFrame(data).T
|
139 |
+
df['title'] = df.index
|
|
|
|
|
|
|
|
|
140 |
|
141 |
+
# Check if required columns are present
|
142 |
+
if 'Github Star' in df.columns and 'link' in df.columns and 'pdf_link' in df.columns:
|
143 |
+
df = df[['title', 'Github Star', 'link', 'pdf_link']]
|
144 |
+
df = df.sort_values(by='Github Star', ascending=False)
|
145 |
+
df['link'] = df['link'].apply(lambda x: f'<a href="{x}" target="_blank">Link</a>')
|
146 |
+
df['pdf_link'] = df['pdf_link'].apply(lambda x: f'<a href="{x}" target="_blank">{x}</a>')
|
147 |
+
else:
|
148 |
+
print("Required columns are missing in the dataframe.")
|
149 |
+
print(f"Columns available: {df.columns}")
|
150 |
+
|
151 |
+
return df
|
152 |
|
153 |
+
def update_display(category):
|
154 |
+
"""Update the display for a category. Freshen up your data like it's spring cleaning! ๐งน๐ธ"""
|
155 |
+
cache_file = f"{category}_papers_cache.json"
|
156 |
+
url = f"https://paperswithcode.com/{category}" if category != "top" else "https://paperswithcode.com/"
|
157 |
+
|
158 |
+
data = load_and_cache_data(url, cache_file)
|
159 |
+
df = format_dataframe(data)
|
160 |
+
|
161 |
+
return len(df), df.to_html(escape=False, index=False)
|
162 |
|
163 |
+
def load_all_data():
|
164 |
+
"""Load data for all categories. It's like a buffet for your brain! ๐ง ๐ฝ๏ธ"""
|
165 |
+
top_count, top_html = update_display("top")
|
166 |
+
new_count, new_html = update_display("latest")
|
167 |
+
greatest_count, greatest_html = update_display("greatest")
|
168 |
+
return top_count, top_html, new_count, new_html, greatest_count, greatest_html
|
169 |
|
170 |
+
# ๐ Asynchronous Paper Processing Wizardry ๐
|
171 |
|
172 |
+
async def download_and_process_pdf(session, title, paper_info, directory):
|
173 |
+
"""Download and process a PDF. It's like turning lead into gold, but with papers! ๐โจ"""
|
174 |
+
pdf_url = paper_info['pdf_link']
|
175 |
+
if not pdf_url:
|
176 |
+
return f"๐ซ No PDF link for: {title}. It's playing hide and seek! ๐", None, None
|
177 |
|
178 |
+
try:
|
179 |
+
timeout = aiohttp.ClientTimeout(total=60) # 60 seconds timeout
|
180 |
+
async with session.get(pdf_url, timeout=timeout) as response:
|
181 |
+
if response.status != 200:
|
182 |
+
return f"๐จ Failed to grab PDF for {title}: HTTP {response.status}. The internet gremlins strike again! ๐น", None, None
|
183 |
+
pdf_content = await response.read()
|
184 |
+
|
185 |
+
file_length = len(pdf_content)
|
186 |
+
if file_length < 5000: # Check if the PDF is less than 5KB
|
187 |
+
return f"๐ PDF for {title} is tiny ({file_length} bytes). It's like a paper for ants! ๐๐", None, None
|
188 |
+
|
189 |
+
# Convert PDF to text
|
190 |
+
pdf_file = io.BytesIO(pdf_content)
|
191 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
192 |
+
text = ""
|
193 |
+
for page in pdf_reader.pages:
|
194 |
+
text += page.extract_text()
|
195 |
+
|
196 |
+
if len(text) < 5000: # Check if the extracted text is less than 5KB
|
197 |
+
return f"๐ Extracted text for {title} is too small ({len(text)} characters). It's not you, it's the PDF! ๐", None, None
|
198 |
+
|
199 |
+
safe_title = safe_filename(title)
|
200 |
+
txt_filename = f"{safe_title}.txt"
|
201 |
+
txt_filepath = os.path.join(directory, txt_filename)
|
202 |
+
|
203 |
+
async with aiofiles.open(txt_filepath, 'w', encoding='utf-8') as f:
|
204 |
+
await f.write(text)
|
205 |
+
|
206 |
+
return f"๐ Successfully processed: {txt_filename} (File length: {file_length} bytes). It's alive! ๐งฌ", txt_filepath, text
|
207 |
+
except asyncio.TimeoutError:
|
208 |
+
return f"โณ Timeout for {title}. The PDF is playing hard to get! ๐", None, None
|
209 |
+
except Exception as e:
|
210 |
+
return f"๐ฅ Oops! Error processing {title}: {str(e)}. Gremlins in the system! ๐ ๏ธ", None, None
|
211 |
|
212 |
+
async def process_papers(data, directory, progress=gr.Progress()):
|
213 |
+
"""Process multiple papers asynchronously. It's like juggling papers, but faster! ๐คนโโ๏ธ๐"""
|
214 |
+
async with aiohttp.ClientSession() as session:
|
215 |
+
tasks = []
|
216 |
+
for title, paper_info in data.items():
|
217 |
+
task = asyncio.ensure_future(download_and_process_pdf(session, title, paper_info, directory))
|
218 |
+
tasks.append(task)
|
219 |
+
|
220 |
+
results = []
|
221 |
+
successful_downloads = []
|
222 |
+
errors = []
|
223 |
+
for i, task in enumerate(asyncio.as_completed(tasks), start=1):
|
224 |
+
result, filepath, text = await task
|
225 |
+
results.append(result)
|
226 |
+
if filepath and text:
|
227 |
+
successful_downloads.append((filepath, text))
|
228 |
+
else:
|
229 |
+
errors.append(result)
|
230 |
+
progress(i / len(tasks), f"๐ Processed {i}/{len(tasks)} papers. Science waits for no one!")
|
231 |
+
|
232 |
+
# Display animated banner
|
233 |
+
banner_frames = animated_banner("Processing", "๐")
|
234 |
+
for frame in banner_frames:
|
235 |
+
print(frame, end='\r')
|
236 |
+
await asyncio.sleep(0.1)
|
237 |
+
print(" " * len(banner_frames[-1]), end='\r') # Clear the last frame
|
238 |
+
|
239 |
+
return results, successful_downloads, errors
|
240 |
|
241 |
+
def download_all_papers(progress=gr.Progress()):
|
242 |
+
"""Download and process all papers. It's like hosting a paper party, and everyone's invited! ๐๐"""
|
243 |
all_data = {}
|
244 |
for category in ["top", "latest", "greatest"]:
|
245 |
cache_file = f"{category}_papers_cache.json"
|
|
|
247 |
if data:
|
248 |
all_data.update(data)
|
249 |
|
250 |
+
date_directory = create_date_directory()
|
251 |
+
results, successful_downloads, errors = asyncio.run(process_papers(all_data, date_directory, progress))
|
252 |
|
253 |
+
summary = f"๐ Papers processed: {len(all_data)} (We're basically librarians now!)\n"
|
254 |
+
summary += f"โ
Successfully downloaded and converted: {len(successful_downloads)} (Take that, PDF gremlins!)\n"
|
255 |
+
summary += f"โ Errors: {len(errors)} (Even superheroes have off days)\n\n"
|
256 |
+
summary += "๐จ Error List (AKA 'The Wall of Shame'):\n" + "\n".join(errors) if errors else "No errors occurred. It's a miracle! ๐"
|
257 |
|
258 |
+
download_links = []
|
259 |
+
text_contents = []
|
260 |
+
for filepath, text in successful_downloads:
|
261 |
+
filename = os.path.basename(filepath)
|
262 |
+
download_links.append(get_base64_download_link(text, filename))
|
263 |
+
text_contents.append(f"--- {filename} ---\n\n{text[:1000]}... (There's more, but we don't want to spoil the ending! ๐๐ฎ)\n\n")
|
264 |
|
265 |
+
return summary, "<br>".join(download_links), "\n".join(text_contents)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
266 |
|
267 |
# ๐ญ Gradio Interface: Where the Magic Happens ๐ญ
|
268 |
|
269 |
with gr.Blocks() as demo:
|
270 |
+
gr.Markdown("<h1><center>Papers Leaderboard</center></h1>")
|
271 |
|
272 |
with gr.Tab("Top Trending Papers"):
|
273 |
top_count = gr.Textbox(label="Number of Papers Fetched")
|
|
|
287 |
greatest_button = gr.Button("Refresh Leaderboard")
|
288 |
greatest_button.click(fn=lambda: update_display("greatest"), inputs=None, outputs=[greatest_count, greatest_html])
|
289 |
|
290 |
+
download_button = gr.Button("๐ Download All Papers", variant="primary")
|
291 |
+
download_output = gr.Textbox(label="Download Status")
|
292 |
+
download_links = gr.HTML(label="Download Links")
|
293 |
+
# Updated this to gr.Code with Python as language for displaying paper contents
|
294 |
+
text_output = gr.Code(label="Paper Contents", language="python")
|
295 |
+
download_button.click(fn=download_all_papers, inputs=None, outputs=[download_output, download_links, text_output])
|
296 |
|
297 |
# Load initial data for all tabs
|
298 |
demo.load(fn=load_all_data, outputs=[top_count, top_html, new_count, new_html, greatest_count, greatest_html])
|
299 |
|
300 |
# ๐ Launch the Gradio interface with a public link
|
301 |
+
print("๐ญ Launching the Papers Leaderboard! Get ready for a wild ride through the land of academia! ๐ข๐")
|
302 |
demo.launch(share=True)
|