awacke1 commited on
Commit
ec00f80
ยท
verified ยท
1 Parent(s): 3e3cb70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -71
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 torch
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), 'title': title}
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
- # ๐Ÿš€ Transformer-based Word and Context Analysis ๐Ÿš€
94
 
95
- def generate_embeddings(titles):
96
- """Generate word embeddings using a transformer model."""
97
- model_name = "sentence-transformers/all-MiniLM-L6-v2"
98
- tokenizer = AutoTokenizer.from_pretrained(model_name)
99
- model = AutoModel.from_pretrained(model_name)
100
 
101
- embeddings = []
102
- with torch.no_grad():
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
- return embeddings
109
-
110
- def build_graph(titles, embeddings, threshold=0.7):
111
- """Build a graph of words based on similarity between titles."""
112
- G = nx.Graph()
 
 
 
 
 
 
113
 
114
- for i, title in enumerate(titles):
115
- G.add_node(i, label=title)
 
 
 
 
 
 
 
116
 
117
- for i in range(len(embeddings)):
118
- for j in range(i+1, len(embeddings)):
119
- sim = torch.cosine_similarity(embeddings[i], embeddings[j], dim=0).item()
120
- if sim > threshold:
121
- G.add_edge(i, j, weight=sim)
 
122
 
123
- return G
124
 
125
- def visualize_graph(G, titles):
126
- """Visualize the graph using pyvis and show it as a mind map."""
127
- net = Network(height="750px", width="100%", notebook=True)
 
 
128
 
129
- for node in G.nodes(data=True):
130
- net.add_node(node[0], label=titles[node[0]])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
- for edge in G.edges(data=True):
133
- net.add_edge(edge[0], edge[1], value=edge[2]['weight'])
134
-
135
- net.show("paper_network.html")
136
- return "paper_network.html"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
- def analyze_and_generate_graph(progress=gr.Progress()):
139
- """Analyze papers, generate embeddings, and visualize the relationship graph."""
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
- titles = [paper['title'] for paper in all_data.values()]
 
148
 
149
- # Generate embeddings
150
- embeddings = generate_embeddings(titles)
 
 
151
 
152
- # Build a similarity graph based on the embeddings
153
- G = build_graph(titles, embeddings)
 
 
 
 
154
 
155
- # Visualize the graph as a mind map
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 with Context Analysis</center></h1>")
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
- analyze_button = gr.Button("๐Ÿ” Analyze and Generate Graph", variant="primary")
196
- analyze_output = gr.Textbox(label="Analysis Status")
197
- graph_output = gr.HTML(label="Graph Visualization")
198
-
199
- analyze_button.click(fn=analyze_and_generate_graph, inputs=None, outputs=[analyze_output, graph_output])
 
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 with Context Analysis! Get ready to explore the relationships between papers! ๐ŸŽข๐Ÿ“š")
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)