m7n commited on
Commit
5460b58
·
1 Parent(s): 2282ec1

reverting to original code

Browse files
Files changed (1) hide show
  1. app.py +636 -57
app.py CHANGED
@@ -1,82 +1,661 @@
1
- import base64
2
- import json
3
- import gradio as gr
4
- import spaces
 
 
 
 
 
 
 
 
 
 
5
  import torch
6
- from spaces.zero.client import _get_token
 
 
 
7
  from fastapi import FastAPI
8
  from fastapi.staticfiles import StaticFiles
9
- from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # FastAPI setup
12
  app = FastAPI()
13
-
14
  static_dir = Path('./static')
15
  static_dir.mkdir(parents=True, exist_ok=True)
 
16
 
17
- # Create a sample HTML file in the static directory for demonstration
18
- with open(static_dir / "test.html", "w", encoding="utf-8") as f:
19
- f.write("<html><body><h1>Hello from static!</h1><p>We're serving this file without uvicorn!</p></body></html>")
20
 
21
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
 
 
 
 
 
 
 
 
 
22
 
 
 
 
23
 
24
- @spaces.GPU(duration=4*60) # Not possible with IP-based quotas on certain Spaces
25
- def inner():
26
- return "ok"
 
27
 
 
28
 
29
- def greet(request: gr.Request, n):
30
- """
31
- Example function that verifies GPU usage and decodes a token.
32
- """
33
- from spaces.zero.client import _get_token
34
- token = _get_token(request)
35
- print("Token:", token)
36
- # Check that the GPU-decorated function still works
37
- assert inner() == "ok"
38
-
39
- # A small example of token decoding
40
- payload = token.split('.')[1]
41
- payload = f"{payload}{'=' * ((4 - len(payload) % 4) % 4)}"
42
- try:
43
- decoded = base64.urlsafe_b64decode(payload).decode()
44
- return json.loads(decoded)
45
- except Exception as e:
46
- return {"error": str(e)}
47
-
48
- @spaces.GPU(duration=4*60) # Not possible with IP-based quotas on certain Spaces
49
- def greet_wrapper(request: gr.Request, n):
 
 
 
 
50
  """
51
- Simple wrapper function that passes through inputs to greet function
 
 
 
 
 
 
 
 
 
 
 
 
52
  """
53
- return greet(request, n)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # Build a simple Gradio Blocks interface that also shows a static HTML iframe
57
- with gr.Blocks() as demo:
58
- gr.Markdown("## Testing Static File Serving Without uvicorn")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Show the static HTML file inside an iframe
61
- gr.HTML(
62
- value='<iframe src="/static/test.html" width="100%" height="300px"></iframe>',
63
- label="Static HTML Demo"
 
 
64
  )
65
 
66
- # Add the original demonstration interface
67
- # (just a numeric input feeding into the greet() function)
68
- greet_interface = gr.Interface(fn=greet_wrapper, inputs=gr.Number(), outputs=gr.JSON())
69
- greet_interface.render()
70
 
 
 
71
 
72
- # Mount the Gradio app
73
- app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=False)
74
- app.zerogpu = True
75
 
76
- __all__ = ['app']
77
 
78
- # # We do NOT manually run uvicorn here; HF Spaces will serve the FastAPI app automatically.
79
- # if __name__ == "__main__":
80
- # # This pass ensures that if you run it locally (e.g., python app.py),
81
- # # nothing breaks, but on Spaces it's auto-served via the 'app' object.
82
- # pass
 
1
+ import spaces # necessary to run on Zero.
2
+
3
+ import time
4
+ print(f"Starting up: {time.strftime('%Y-%m-%d %H:%M:%S')}")
5
+
6
+ # Standard library imports
7
+ import os
8
+ from pathlib import Path
9
+ from datetime import datetime
10
+ from itertools import chain
11
+
12
+ # Third-party imports
13
+ import numpy as np
14
+ import pandas as pd
15
  import torch
16
+ import gradio as gr
17
+
18
+ print(f"Gradio version: {gr.__version__}")
19
+
20
  from fastapi import FastAPI
21
  from fastapi.staticfiles import StaticFiles
22
+ import uvicorn
23
+ import matplotlib.pyplot as plt
24
+ import tqdm
25
+ import colormaps
26
+ import matplotlib.colors as mcolors
27
+ from matplotlib.colors import Normalize
28
+
29
+
30
+
31
+ import opinionated # for fonts
32
+ plt.style.use("opinionated_rc")
33
+
34
+ from sklearn.neighbors import NearestNeighbors
35
+
36
+
37
+ def is_running_in_hf_space():
38
+ return "SPACE_ID" in os.environ
39
+
40
+ #if is_running_in_hf_space():
41
+ import spaces # necessary to run on Zero.
42
+ #print(f"Spaces version: {spaces.__version__}")
43
+
44
+ import datamapplot
45
+ import pyalex
46
+
47
+ # Local imports
48
+ from openalex_utils import (
49
+ openalex_url_to_pyalex_query,
50
+ get_field,
51
+ process_records_to_df,
52
+ openalex_url_to_filename
53
+ )
54
+ from styles import DATAMAP_CUSTOM_CSS
55
+ from data_setup import (
56
+ download_required_files,
57
+ setup_basemap_data,
58
+ setup_mapper,
59
+ setup_embedding_model,
60
+
61
+ )
62
+
63
+ from network_utils import create_citation_graph, draw_citation_graph
64
+
65
+
66
+
67
+
68
+ # Configure OpenAlex
69
+ pyalex.config.email = "[email protected]"
70
+
71
+ print(f"Imports completed: {time.strftime('%Y-%m-%d %H:%M:%S')}")
72
 
73
  # FastAPI setup
74
  app = FastAPI()
 
75
  static_dir = Path('./static')
76
  static_dir.mkdir(parents=True, exist_ok=True)
77
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
78
 
79
+ # Gradio configuration
80
+ gr.set_static_paths(paths=["static/"])
 
81
 
82
+ # Resource configuration
83
+ REQUIRED_FILES = {
84
+ "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl":
85
+ "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/100k_filtered_OA_sample_cluster_and_positions_supervised.pkl",
86
+ "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl":
87
+ "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
88
+ }
89
+ BASEMAP_PATH = "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl"
90
+ MAPPER_PARAMS_PATH = "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
91
+ MODEL_NAME = "m7n/discipline-tuned_specter_2_024"
92
 
93
+ # Initialize models and data
94
+ start_time = time.time()
95
+ print("Initializing resources...")
96
 
97
+ download_required_files(REQUIRED_FILES)
98
+ basedata_df = setup_basemap_data(BASEMAP_PATH)
99
+ mapper = setup_mapper(MAPPER_PARAMS_PATH)
100
+ model = setup_embedding_model(MODEL_NAME)
101
 
102
+ print(f"Resources initialized in {time.time() - start_time:.2f} seconds")
103
 
104
+
105
+
106
+ # Setting up decorators for embedding on HF-Zero:
107
+ def no_op_decorator(func):
108
+ """A no-op (no operation) decorator that simply returns the function."""
109
+ def wrapper(*args, **kwargs):
110
+ # Do nothing special
111
+ return func(*args, **kwargs)
112
+ return wrapper
113
+
114
+ # # Decide which decorator to use based on environment
115
+ # decorator_to_use = spaces.GPU() if is_running_in_hf_space() else no_op_decorator
116
+ # #duration=120
117
+
118
+ # @decorator_to_use
119
+ @spaces.GPU
120
+ def create_embeddings(texts_to_embedd):
121
+ """Create embeddings for the input texts using the loaded model."""
122
+ return model.encode(texts_to_embedd, show_progress_bar=True, batch_size=192)
123
+
124
+
125
+ @spaces.GPU
126
+ def predict(text_input, sample_size_slider, reduce_sample_checkbox, sample_reduction_method,
127
+ plot_time_checkbox, locally_approximate_publication_date_checkbox,
128
+ download_csv_checkbox, download_png_checkbox,citation_graph_checkbox, progress=gr.Progress()):
129
  """
130
+ Main prediction pipeline that processes OpenAlex queries and creates visualizations.
131
+
132
+ Args:
133
+ text_input (str): OpenAlex query URL
134
+ sample_size_slider (int): Maximum number of samples to process
135
+ reduce_sample_checkbox (bool): Whether to reduce sample size
136
+ sample_reduction_method (str): Method for sample reduction ("Random" or "Order of Results")
137
+ plot_time_checkbox (bool): Whether to color points by publication date
138
+ locally_approximate_publication_date_checkbox (bool): Whether to approximate publication date locally before plotting.
139
+ progress (gr.Progress): Gradio progress tracker
140
+
141
+ Returns:
142
+ tuple: (link to visualization, iframe HTML)
143
  """
144
+ # Check if input is empty or whitespace
145
+ print(f"Input: {text_input}")
146
+ if not text_input or text_input.isspace():
147
+ error_message = "Error: Please enter a valid OpenAlex URL in the 'OpenAlex-search URL'-field"
148
+ return [
149
+ error_message, # iframe HTML
150
+ gr.DownloadButton(label="Download Interactive Visualization", value='html_file_path', visible=False), # html download
151
+ gr.DownloadButton(label="Download CSV Data", value='csv_file_path', visible=False), # csv download
152
+ gr.DownloadButton(label="Download Static Plot", value='png_file_path', visible=False), # png download
153
+ gr.Button(visible=False) # cancel button state
154
+ ]
155
+
156
+
157
+ # Check if the input is a valid OpenAlex URL
158
+
159
+
160
+
161
+ start_time = time.time()
162
+ print('Starting data projection pipeline')
163
+ progress(0.1, desc="Starting...")
164
+
165
+ # Split input into multiple URLs if present
166
+ urls = [url.strip() for url in text_input.split(';')]
167
+ records = []
168
+ total_query_length = 0
169
+
170
+ # Use first URL for filename
171
+ first_query, first_params = openalex_url_to_pyalex_query(urls[0])
172
+ filename = openalex_url_to_filename(urls[0])
173
+ print(f"Filename: {filename}")
174
+
175
+ # Process each URL
176
+ for i, url in enumerate(urls):
177
+ query, params = openalex_url_to_pyalex_query(url)
178
+ query_length = query.count()
179
+ total_query_length += query_length
180
+ print(f'Requesting {query_length} entries from query {i+1}/{len(urls)}...')
181
+
182
+ target_size = sample_size_slider if reduce_sample_checkbox and sample_reduction_method == "First n samples" else query_length
183
+ records_per_query = 0
184
+
185
+ should_break = False
186
+ for page in query.paginate(per_page=200, n_max=None):
187
+ for record in page:
188
+ records.append(record)
189
+ records_per_query += 1
190
+ progress(0.1 + (0.2 * len(records) / (total_query_length)),
191
+ desc=f"Getting data from query {i+1}/{len(urls)}...")
192
+
193
+ if reduce_sample_checkbox and sample_reduction_method == "First n samples" and records_per_query >= target_size:
194
+ should_break = True
195
+ break
196
+ if should_break:
197
+ break
198
+ if should_break:
199
+ break
200
+ print(f"Query completed in {time.time() - start_time:.2f} seconds")
201
+
202
+ # Process records
203
+ processing_start = time.time()
204
+ records_df = process_records_to_df(records)
205
+
206
+ if reduce_sample_checkbox and sample_reduction_method != "All":
207
+ sample_size = min(sample_size_slider, len(records_df))
208
+ if sample_reduction_method == "n random samples":
209
+ records_df = records_df.sample(sample_size)
210
+ elif sample_reduction_method == "First n samples":
211
+ records_df = records_df.iloc[:sample_size]
212
+ print(f"Records processed in {time.time() - processing_start:.2f} seconds")
213
+
214
+ # Create embeddings
215
+ embedding_start = time.time()
216
+ progress(0.3, desc="Embedding Data...")
217
+ texts_to_embedd = [f"{title} {abstract}" for title, abstract
218
+ in zip(records_df['title'], records_df['abstract'])]
219
+ embeddings = create_embeddings(texts_to_embedd)
220
+ print(f"Embeddings created in {time.time() - embedding_start:.2f} seconds")
221
+
222
+ # Project embeddings
223
+ projection_start = time.time()
224
+ progress(0.5, desc="Project into UMAP-embedding...")
225
+ umap_embeddings = mapper.transform(embeddings)
226
+ records_df[['x','y']] = umap_embeddings
227
+ print(f"Projection completed in {time.time() - projection_start:.2f} seconds")
228
 
229
+ # Prepare visualization data
230
+ viz_prep_start = time.time()
231
+ progress(0.6, desc="Preparing visualization data...")
232
+
233
+ basedata_df['color'] = '#ced4d211'
234
+
235
+ if not plot_time_checkbox:
236
+ records_df['color'] = '#5e2784'
237
+ else:
238
+ cmap = colormaps.haline
239
+ if not locally_approximate_publication_date_checkbox:
240
+ # Create color mapping based on publication years
241
+ years = pd.to_numeric(records_df['publication_year'])
242
+ norm = mcolors.Normalize(vmin=years.min(), vmax=years.max())
243
+ records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in years]
244
+
245
+ else:
246
+ n_neighbors = 10 # Adjust this value to control smoothing
247
+ nn = NearestNeighbors(n_neighbors=n_neighbors)
248
+ nn.fit(umap_embeddings)
249
+ distances, indices = nn.kneighbors(umap_embeddings)
250
 
251
+ # Calculate local average publication year for each point
252
+ local_years = np.array([
253
+ np.mean(records_df['publication_year'].iloc[idx])
254
+ for idx in indices
255
+ ])
256
+ norm = mcolors.Normalize(vmin=local_years.min(), vmax=local_years.max())
257
+ records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in local_years]
258
+
259
+
260
+
261
+ stacked_df = pd.concat([basedata_df, records_df], axis=0, ignore_index=True)
262
+ stacked_df = stacked_df.fillna("Unlabelled")
263
+ stacked_df['parsed_field'] = [get_field(row) for ix, row in stacked_df.iterrows()]
264
+ extra_data = pd.DataFrame(stacked_df['doi'])
265
+ print(f"Visualization data prepared in {time.time() - viz_prep_start:.2f} seconds")
266
+ if citation_graph_checkbox:
267
+ citation_graph_start = time.time()
268
+ citation_graph = create_citation_graph(records_df)
269
+ graph_file_name = f"{filename}_citation_graph.jpg"
270
+ graph_file_path = static_dir / graph_file_name
271
+ draw_citation_graph(citation_graph,path=graph_file_path,bundle_edges=True,
272
+ min_max_coordinates=[np.min(stacked_df['x']),np.max(stacked_df['x']),np.min(stacked_df['y']),np.max(stacked_df['y'])])
273
+ print(f"Citation graph created and saved in {time.time() - citation_graph_start:.2f} seconds")
274
+
275
+
276
+
277
+
278
+ # Create and save plot
279
+ plot_start = time.time()
280
+ progress(0.7, desc="Creating interactive plot...")
281
+ # Create a solid black colormap
282
+ black_cmap = mcolors.LinearSegmentedColormap.from_list('black', ['#000000', '#000000'])
283
+
284
+
285
+ plot = datamapplot.create_interactive_plot(
286
+ stacked_df[['x','y']].values,
287
+ np.array(stacked_df['cluster_2_labels']),
288
+ np.array(['Unlabelled' if pd.isna(x) else x for x in stacked_df['parsed_field']]),
289
+
290
+ hover_text=[str(row['title']) for ix, row in stacked_df.iterrows()],
291
+ marker_color_array=stacked_df['color'],
292
+ use_medoids=False, # Switch back once efficient mediod caclulation comes out!
293
+ width=1000,
294
+ height=1000,
295
+ point_radius_min_pixels=1,
296
+ text_outline_width=5,
297
+ point_hover_color='#5e2784',
298
+ point_radius_max_pixels=7,
299
+ cmap=black_cmap,
300
+ background_image=graph_file_name if citation_graph_checkbox else None,
301
+ #color_label_text=False,
302
+ font_family="Roboto Condensed",
303
+ font_weight=600,
304
+ tooltip_font_weight=600,
305
+ tooltip_font_family="Roboto Condensed",
306
+ extra_point_data=extra_data,
307
+ on_click="window.open(`{doi}`)",
308
+ custom_css=DATAMAP_CUSTOM_CSS,
309
+ initial_zoom_fraction=.8,
310
+ enable_search=False,
311
+ offline_mode=False
312
+ )
313
+
314
+ # Save plot
315
+ html_file_name = f"{filename}.html"
316
+ html_file_path = static_dir / html_file_name
317
+ plot.save(html_file_path)
318
+ print(f"Plot created and saved in {time.time() - plot_start:.2f} seconds")
319
+
320
+
321
+
322
+ # Save additional files if requested
323
+ csv_file_path = static_dir / f"{filename}.csv"
324
+ png_file_path = static_dir / f"{filename}.png"
325
+
326
+ if download_csv_checkbox:
327
+ # Export relevant column
328
+ export_df = records_df[['title', 'abstract', 'doi', 'publication_year', 'x', 'y','id','primary_topic']]
329
+ export_df['parsed_field'] = [get_field(row) for ix, row in export_df.iterrows()]
330
+ export_df['referenced_works'] = [', '.join(x) for x in records_df['referenced_works']]
331
+ export_df.to_csv(csv_file_path, index=False)
332
+
333
+ if download_png_checkbox:
334
+ png_start_time = time.time()
335
+ print("Starting PNG generation...")
336
+
337
+ # Sample and prepare data
338
+ sample_prep_start = time.time()
339
+ sample_to_plot = basedata_df#.sample(20000)
340
+ labels1 = np.array(sample_to_plot['cluster_2_labels'])
341
+ labels2 = np.array(['Unlabelled' if pd.isna(x) else x for x in sample_to_plot['parsed_field']])
342
+
343
+ ratio = 0.6
344
+ mask = np.random.random(size=len(labels1)) < ratio
345
+ combined_labels = np.where(mask, labels1, labels2)
346
+
347
+ # Get the 30 most common labels
348
+ unique_labels, counts = np.unique(combined_labels, return_counts=True)
349
+ top_30_labels = set(unique_labels[np.argsort(counts)[-50:]])
350
+
351
+ # Replace less common labels with 'Unlabelled'
352
+ combined_labels = np.array(['Unlabelled' if label not in top_30_labels else label for label in combined_labels])
353
+ #combined_labels = np.array(['Unlabelled' for label in combined_labels])
354
+ #if label not in top_30_labels else label
355
+ colors_base = ['#536878' for _ in range(len(labels1))]
356
+ print(f"Sample preparation completed in {time.time() - sample_prep_start:.2f} seconds")
357
+
358
+ # Create main plot
359
+ print(labels1)
360
+ print(labels2)
361
+ print(sample_to_plot[['x','y']].values)
362
+ print(combined_labels)
363
+
364
+ main_plot_start = time.time()
365
+ fig, ax = datamapplot.create_plot(
366
+ sample_to_plot[['x','y']].values,
367
+ combined_labels,
368
+ label_wrap_width=12,
369
+ label_over_points=True,
370
+ dynamic_label_size=True,
371
+ use_medoids=False, # Switch back once efficient mediod caclulation comes out!
372
+ point_size=2,
373
+ marker_color_array=colors_base,
374
+ force_matplotlib=True,
375
+ max_font_size=12,
376
+ min_font_size=4,
377
+ min_font_weight=100,
378
+ max_font_weight=300,
379
+ font_family="Roboto Condensed",
380
+ color_label_text=False, add_glow=False,
381
+ highlight_labels=list(np.unique(labels1)),
382
+ label_font_size=8,
383
+ highlight_label_keywords={"fontsize": 12, "fontweight": "bold", "bbox":{"boxstyle":"circle", "pad":0.75,'alpha':0.}},
384
+ )
385
+ print(f"Main plot creation completed in {time.time() - main_plot_start:.2f} seconds")
386
+
387
+
388
+ if citation_graph_checkbox:
389
+
390
+ # Read and add the graph image
391
+ graph_img = plt.imread(graph_file_path)
392
+ ax.imshow(graph_img, extent=[np.min(stacked_df['x']),np.max(stacked_df['x']),np.min(stacked_df['y']),np.max(stacked_df['y'])],
393
+ alpha=0.9, aspect='auto')
394
+
395
+
396
+
397
+ # Time-based visualization
398
+ scatter_start = time.time()
399
+ if plot_time_checkbox:
400
+ if locally_approximate_publication_date_checkbox:
401
+ scatter = plt.scatter(
402
+ umap_embeddings[:,0],
403
+ umap_embeddings[:,1],
404
+ c=local_years,
405
+ cmap=colormaps.haline,
406
+ alpha=0.8,
407
+ s=5
408
+ )
409
+ else:
410
+ years = pd.to_numeric(records_df['publication_year'])
411
+ scatter = plt.scatter(
412
+ umap_embeddings[:,0],
413
+ umap_embeddings[:,1],
414
+ c=years,
415
+ cmap=colormaps.haline,
416
+ alpha=0.8,
417
+ s=5
418
+ )
419
+ plt.colorbar(scatter, shrink=0.5, format='%d')
420
+ else:
421
+ scatter = plt.scatter(
422
+ umap_embeddings[:,0],
423
+ umap_embeddings[:,1],
424
+ c=records_df['color'],
425
+ alpha=0.8,
426
+ s=5
427
+ )
428
+ print(f"Scatter plot creation completed in {time.time() - scatter_start:.2f} seconds")
429
+
430
+ # Save plot
431
+ save_start = time.time()
432
+ plt.axis('off')
433
+ png_file_path = static_dir / f"{filename}.png"
434
+ plt.savefig(png_file_path, dpi=300, bbox_inches='tight')
435
+ plt.close()
436
+ print(f"Plot saving completed in {time.time() - save_start:.2f} seconds")
437
+
438
+ print(f"Total PNG generation completed in {time.time() - png_start_time:.2f} seconds")
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+ progress(1.0, desc="Done!")
447
+ print(f"Total pipeline completed in {time.time() - start_time:.2f} seconds")
448
+
449
+ iframe = f"""<iframe src="/static/{html_file_name}" width="100%" height="1000px"></iframe>"""
450
+
451
+ # Return iframe and download buttons with appropriate visibility
452
+ return [
453
+ iframe,
454
+ gr.DownloadButton(label="Download Interactive Visualization", value=html_file_path, visible=True, variant='secondary'),
455
+ gr.DownloadButton(label="Download CSV Data", value=csv_file_path, visible=download_csv_checkbox, variant='secondary'),
456
+ gr.DownloadButton(label="Download Static Plot", value=png_file_path, visible=download_png_checkbox, variant='secondary'),
457
+ gr.Button(visible=False) # Return hidden state for cancel button
458
+ ]
459
+
460
+ predict.zerogpu = True
461
+
462
+
463
+
464
+ theme = gr.themes.Monochrome(
465
+ font=[gr.themes.GoogleFont("Roboto Condensed"), "ui-sans-serif", "system-ui", "sans-serif"],
466
+ text_size="lg",
467
+ ).set(
468
+ button_secondary_background_fill="white",
469
+ button_secondary_background_fill_hover="#f3f4f6",
470
+ button_secondary_border_color="black",
471
+ button_secondary_text_color="black",
472
+ button_border_width="2px",
473
+ )
474
+
475
+
476
+ # Gradio interface setup
477
+ with gr.Blocks(theme=theme, css="""
478
+ .gradio-container a {
479
+ color: black !important;
480
+ text-decoration: none !important; /* Force remove default underline */
481
+ font-weight: bold;
482
+ transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out;
483
+ display: inline-block; /* Enable proper spacing for descenders */
484
+ line-height: 1.1; /* Adjust line height */
485
+ padding-bottom: 2px; /* Add space for descenders */
486
+ }
487
+ .gradio-container a:hover {
488
+ color: #b23310 !important;
489
+ border-bottom: 3px solid #b23310; /* Wider underline, only on hover */
490
+ }
491
+ """) as demo:
492
+ gr.Markdown("""
493
+ <div style="max-width: 100%; margin: 0 auto;">
494
+ <br>
495
+
496
+ # OpenAlex Mapper
497
+
498
+ OpenAlex Mapper is a way of projecting search queries from the amazing OpenAlex database on a background map of randomly sampled papers from OpenAlex, which allows you to easily investigate interdisciplinary connections. OpenAlex Mapper was developed by [Maximilian Noichl](https://maxnoichl.eu) and [Andrea Loettgers](https://unige.academia.edu/AndreaLoettgers) at the [Possible Life project](http://www.possiblelife.eu/).
499
+
500
+ To use OpenAlex Mapper, first head over to [OpenAlex](https://openalex.org/) and search for something that interests you. For example, you could search for all the papers that make use of the [Kuramoto model](https://openalex.org/works?page=1&filter=default.search%3A%22Kuramoto%20Model%22), for all the papers that were published by researchers at [Utrecht University in 2019](https://openalex.org/works?page=1&filter=authorships.institutions.lineage%3Ai193662353,publication_year%3A2019), or for all the papers that cite Wittgenstein's [Philosophical Investigations](https://openalex.org/works?page=1&filter=cites%3Aw4251395411). Then you copy the URL to that search query into the OpenAlex search URL box below and click "Run Query." It will download all of these records from OpenAlex and embed them on our interactive map. As the embedding step is a little expensive, computationally, it's often a good idea to play around with smaller samples, before running a larger analysis. After a little time, that map will appear and be available for you to interact with and download. You can find more explanations in the FAQs below.
501
+ </div>
502
+ """)
503
+
504
+
505
+ with gr.Row():
506
+ with gr.Column(scale=1):
507
+ with gr.Row():
508
+ run_btn = gr.Button("Run Query", variant='primary')
509
+ cancel_btn = gr.Button("Cancel", visible=False, variant='secondary')
510
+
511
+ # Create separate download buttons
512
+ html_download = gr.DownloadButton("Download Interactive Visualization", visible=False, variant='secondary')
513
+ csv_download = gr.DownloadButton("Download CSV Data", visible=False, variant='secondary')
514
+ png_download = gr.DownloadButton("Download Static Plot", visible=False, variant='secondary')
515
+
516
+ text_input = gr.Textbox(label="OpenAlex-search URL",
517
+ info="Enter the URL to an OpenAlex-search.")
518
+
519
+ gr.Markdown("### Sample Settings")
520
+ reduce_sample_checkbox = gr.Checkbox(
521
+ label="Reduce Sample Size",
522
+ value=True,
523
+ info="Reduce sample size."
524
+ )
525
+ sample_reduction_method = gr.Dropdown(
526
+ ["All", "First n samples", "n random samples"],
527
+ label="Sample Selection Method",
528
+ value="First n samples",
529
+ info="How to choose the samples to keep."
530
+ )
531
+ sample_size_slider = gr.Slider(
532
+ label="Sample Size",
533
+ minimum=500,
534
+ maximum=20000,
535
+ step=10,
536
+ value=1000,
537
+ info="How many samples to keep.",
538
+ visible=True
539
+ )
540
+
541
+ gr.Markdown("### Plot Settings")
542
+ plot_time_checkbox = gr.Checkbox(
543
+ label="Plot Time",
544
+ value=True,
545
+ info="Colour points by their publication date."
546
+ )
547
+ locally_approximate_publication_date_checkbox = gr.Checkbox(
548
+ label="Locally Approximate Publication Date",
549
+ value=True,
550
+ info="Colour points by the average publication date in their area."
551
+ )
552
+
553
+ gr.Markdown("### Download Options")
554
+ download_csv_checkbox = gr.Checkbox(
555
+ label="Generate CSV Export",
556
+ value=False,
557
+ info="Export the data as CSV file"
558
+ )
559
+ download_png_checkbox = gr.Checkbox(
560
+ label="Generate Static PNG Plot",
561
+ value=False,
562
+ info="Export a static PNG visualization. This will make things slower!"
563
+ )
564
+
565
+ gr.Markdown("### Citation graph")
566
+ citation_graph_checkbox = gr.Checkbox(
567
+ label="Add Citation Graph",
568
+ value=False,
569
+ info="Adds a citation graph of the sample to the plot."
570
+ )
571
+
572
+
573
+
574
+ with gr.Column(scale=2):
575
+ html = gr.HTML(
576
+ value='<div style="width: 100%; height: 1000px; display: flex; justify-content: center; align-items: center; border: 1px solid #ccc; background-color: #f8f9fa;"><p style="font-size: 1.2em; color: #666;">The visualization map will appear here after running a query</p></div>',
577
+ label="",
578
+ show_label=False
579
+ )
580
+ gr.Markdown("""
581
+ <div style="max-width: 100%; margin: 0 auto;">
582
+
583
+ # FAQs
584
+
585
+ ## Who made this?
586
+
587
+ This project was developed by [Maximilian Noichl](https://maxnoichl.eu) (Utrecht University), in cooperation with Andrea Loettger and Tarja Knuuttila at the [Possible Life project](http://www.possiblelife.eu/), at the University of Vienna. If this project is useful in any way for your research, we would appreciate citation of **...**
588
+
589
+ This project received funding from the European Research Council under the European Union's Horizon 2020 research and innovation programme (LIFEMODE project, grant agreement No. 818772).
590
+
591
+ ## How does it work?
592
+
593
+ The base map for this project is developed by randomly downloading 250,000 articles from OpenAlex, then embedding their abstracts using our [fine-tuned](https://huggingface.co/m7n/discipline-tuned_specter_2_024) version of the [specter-2](https://huggingface.co/allenai/specter2_aug2023refresh_base) language model, running these embeddings through [UMAP](https://umap-learn.readthedocs.io/en/latest/) to give us a two-dimensional representation, and displaying that in an interactive window using [datamapplot](https://datamapplot.readthedocs.io/en/latest/index.html). After the data for your query is downloaded from OpenAlex, it then undergoes the exact same process, but the pre-trained UMAP model from earlier is used to project your new data points onto this original map, showing where they would show up if they were included in the original sample. For more details, you can take a look at the method section of this paper: **...**
594
+
595
+ ## I want to add multiple queries at once!
596
+
597
+ That can be a good idea, e. g. if your interested in a specific paper, as well as all the papers that cite it. Just add the queries to the query box and separate them with a ";" without any spaces in between!
598
+
599
+ ## I think I found a mistake in the map.
600
+
601
+ There are various considerations to take into account when working with this map:
602
+
603
+ 1. The language model we use is fine-tuned to separate disciplines from each other, but of course, disciplines are weird, partially subjective social categories, so what the model has learned might not always correspond perfectly to what you would expect to see.
604
+
605
+ 2. When pressing down a really high-dimensional space into a low-dimensional one, there will be trade-offs. For example, we see this big ring structure of the sciences on the map, but in the middle of the map there is a overly stretchedstring of bioinformaticsthat stretches from computer science at the bottom up to the life sciences clusters at the top. This is one of the areas where the UMAP algorithm had trouble pressing our high-dimensional dataset into a low-dimensional space. For more information on how to read a UMAP plot, I recommend looking into ["Understanding UMAP"](https://pair-code.github.io/understanding-umap/) by Andy Coenen & Adam Pearce.
606
+
607
+ 3. Finally, the labels we're using for the regions of this plot are created from OpenAlex's own labels of sub-disciplines. They give a rough indication of the papers that could be expected in this broad area of the map, but they are not necessarily the perfect label for the articles that are precisely below them. They are just located at the median point of a usually much larger, much broader, and fuzzier category, so they should always be taken with quite a big grain of salt.
608
+
609
+ </div>
610
+ """)
611
+
612
+ def update_slider_visibility(method):
613
+ return gr.Slider(visible=(method != "All"))
614
+
615
+ sample_reduction_method.change(
616
+ fn=update_slider_visibility,
617
+ inputs=[sample_reduction_method],
618
+ outputs=[sample_size_slider]
619
+ )
620
+
621
+ def show_cancel_button():
622
+ return gr.Button(visible=True)
623
+
624
+ def hide_cancel_button():
625
+ return gr.Button(visible=False)
626
+
627
+ show_cancel_button.zerogpu = True
628
+ hide_cancel_button.zerogpu = True
629
+ predict.zerogpu = True
630
+
631
+ # Update the run button click event
632
+ run_event = run_btn.click(
633
+ fn=show_cancel_button,
634
+ outputs=cancel_btn,
635
+ queue=False
636
+ ).then(
637
+ fn=predict,
638
+ inputs=[text_input, sample_size_slider, reduce_sample_checkbox,
639
+ sample_reduction_method, plot_time_checkbox,
640
+ locally_approximate_publication_date_checkbox,
641
+ download_csv_checkbox, download_png_checkbox,citation_graph_checkbox],
642
+ outputs=[html, html_download, csv_download, png_download, cancel_btn]
643
+ )
644
 
645
+ # Add cancel button click event
646
+ cancel_btn.click(
647
+ fn=hide_cancel_button,
648
+ outputs=cancel_btn,
649
+ cancels=[run_event],
650
+ queue=False # Important to make the button hide immediately
651
  )
652
 
 
 
 
 
653
 
654
+ # Mount and run app
655
+ app = gr.mount_gradio_app(app, demo, path="/",ssr_mode=False)
656
 
657
+ app.zerogpu = True # Add this line
 
 
658
 
 
659
 
660
+ if __name__ == "__main__":
661
+ uvicorn.run(app, host="0.0.0.0", port=7860)