m7n commited on
Commit
b1b5dc2
·
1 Parent(s): 8f3219d

reintegrated old code

Browse files
Files changed (2) hide show
  1. app.py +666 -41
  2. app_2.py +61 -652
app.py CHANGED
@@ -1,12 +1,77 @@
 
 
 
 
 
 
 
 
1
  from pathlib import Path
2
- import gradio as gr
3
  from datetime import datetime
4
- import os
5
- import spaces # necessary to run on Zero.
6
- from spaces.zero.client import _get_token
 
 
 
 
 
 
 
7
  from fastapi import FastAPI
8
  from fastapi.staticfiles import StaticFiles
9
  import uvicorn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # Create a static directory to store the dynamic HTML files
12
  static_dir = Path("./static")
@@ -16,56 +81,616 @@ static_dir.mkdir(parents=True, exist_ok=True)
16
  os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
17
  print("os.environ['GRADIO_ALLOWED_PATHS'] =", os.environ["GRADIO_ALLOWED_PATHS"])
18
 
 
19
  # Create FastAPI app
20
  app = FastAPI()
21
 
22
  # Mount the static directory
23
  app.mount("/static", StaticFiles(directory="static"), name="static")
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  @spaces.GPU(duration=4*60)
26
- def predict(request: gr.Request, text_input):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  token = _get_token(request)
28
- file_name = f"{datetime.utcnow().strftime('%s')}.html"
29
- file_path = static_dir / file_name
30
- print("File will be written to:", file_path)
31
- with open(file_path, "w") as f:
32
- f.write(f"""<!DOCTYPE html>
33
- <html>
34
- <head>
35
- <script src="https://cdn.tailwindcss.com"></script>
36
- </head>
37
- <body class="bg-gray-200 dark:text-white dark:bg-gray-900">
38
- <h1 class="text-3xl font-bold">
39
- Hello <i>{text_input}</i> From Gradio Iframe
40
- </h1>
41
- <h3>Filename: {file_name}</h3>
42
- </body>
43
- </html>
44
- """)
45
- os.chmod(file_path, 0o644)
46
- # Use the direct static route instead of Gradio's file route
47
- iframe = f'<iframe src="/static/{file_name}" width="100%" height="500px"></iframe>'
48
- link = f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
49
- print("Serving file at URL:", f"/static/{file_name}")
50
- return link, iframe
51
-
52
- with gr.Blocks() as block:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  gr.Markdown("""
54
- ## Gradio + Static Files Demo
55
- This demo generates dynamic HTML files and stores them in a "static" directory. They are then served via Gradio's `/file=` route.
56
- """)
 
 
 
 
 
 
 
 
 
57
  with gr.Row():
58
- with gr.Column():
59
- text_input = gr.Textbox(label="Name")
60
- markdown = gr.Markdown(label="Output Link")
61
- new_btn = gr.Button("New")
62
- with gr.Column():
63
- html = gr.HTML(label="HTML Preview", show_label=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
66
 
 
 
 
67
  # Mount Gradio app to FastAPI
68
- app = gr.mount_gradio_app(app, block, path="/")
69
 
70
  # Run both servers
71
  if __name__ == "__main__":
 
1
+ import spaces # necessary to run on Zero.
2
+ from spaces.zero.client import _get_token
3
+
4
+ import time
5
+ print(f"Starting up: {time.strftime('%Y-%m-%d %H:%M:%S')}")
6
+
7
+ # Standard library imports
8
+ import os
9
  from pathlib import Path
 
10
  from datetime import datetime
11
+ from itertools import chain
12
+
13
+ # Third-party imports
14
+ import numpy as np
15
+ import pandas as pd
16
+ import torch
17
+ import gradio as gr
18
+
19
+ print(f"Gradio version: {gr.__version__}")
20
+
21
  from fastapi import FastAPI
22
  from fastapi.staticfiles import StaticFiles
23
  import uvicorn
24
+ import matplotlib.pyplot as plt
25
+ import tqdm
26
+ import colormaps
27
+ import matplotlib.colors as mcolors
28
+ from matplotlib.colors import Normalize
29
+
30
+
31
+
32
+ import opinionated # for fonts
33
+ plt.style.use("opinionated_rc")
34
+
35
+ from sklearn.neighbors import NearestNeighbors
36
+
37
+
38
+ def is_running_in_hf_space():
39
+ return "SPACE_ID" in os.environ
40
+
41
+ #if is_running_in_hf_space():
42
+ import spaces # necessary to run on Zero.
43
+ #print(f"Spaces version: {spaces.__version__}")
44
+
45
+ import datamapplot
46
+ import pyalex
47
+
48
+ # Local imports
49
+ from openalex_utils import (
50
+ openalex_url_to_pyalex_query,
51
+ get_field,
52
+ process_records_to_df,
53
+ openalex_url_to_filename
54
+ )
55
+ from styles import DATAMAP_CUSTOM_CSS
56
+ from data_setup import (
57
+ download_required_files,
58
+ setup_basemap_data,
59
+ setup_mapper,
60
+ setup_embedding_model,
61
+
62
+ )
63
+
64
+ from network_utils import create_citation_graph, draw_citation_graph
65
+
66
+
67
+
68
+
69
+ # Configure OpenAlex
70
+ pyalex.config.email = "[email protected]"
71
+
72
+ print(f"Imports completed: {time.strftime('%Y-%m-%d %H:%M:%S')}")
73
+
74
+
75
 
76
  # Create a static directory to store the dynamic HTML files
77
  static_dir = Path("./static")
 
81
  os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
82
  print("os.environ['GRADIO_ALLOWED_PATHS'] =", os.environ["GRADIO_ALLOWED_PATHS"])
83
 
84
+
85
  # Create FastAPI app
86
  app = FastAPI()
87
 
88
  # Mount the static directory
89
  app.mount("/static", StaticFiles(directory="static"), name="static")
90
 
91
+
92
+
93
+
94
+
95
+ # Resource configuration
96
+ REQUIRED_FILES = {
97
+ "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl":
98
+ "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/100k_filtered_OA_sample_cluster_and_positions_supervised.pkl",
99
+ "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl":
100
+ "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
101
+ }
102
+ BASEMAP_PATH = "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl"
103
+ MAPPER_PARAMS_PATH = "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
104
+ MODEL_NAME = "m7n/discipline-tuned_specter_2_024"
105
+
106
+ # Initialize models and data
107
+ start_time = time.time()
108
+ print("Initializing resources...")
109
+
110
+ download_required_files(REQUIRED_FILES)
111
+ basedata_df = setup_basemap_data(BASEMAP_PATH)
112
+ mapper = setup_mapper(MAPPER_PARAMS_PATH)
113
+ model = setup_embedding_model(MODEL_NAME)
114
+
115
+ print(f"Resources initialized in {time.time() - start_time:.2f} seconds")
116
+
117
+
118
+
119
+ # Setting up decorators for embedding on HF-Zero:
120
+ def no_op_decorator(func):
121
+ """A no-op (no operation) decorator that simply returns the function."""
122
+ def wrapper(*args, **kwargs):
123
+ # Do nothing special
124
+ return func(*args, **kwargs)
125
+ return wrapper
126
+
127
+ # # Decide which decorator to use based on environment
128
+ # decorator_to_use = spaces.GPU() if is_running_in_hf_space() else no_op_decorator
129
+ # #duration=120
130
+
131
+ # @decorator_to_use
132
  @spaces.GPU(duration=4*60)
133
+ def create_embeddings(texts_to_embedd):
134
+ """Create embeddings for the input texts using the loaded model."""
135
+ return model.encode(texts_to_embedd, show_progress_bar=True, batch_size=192)
136
+
137
+
138
+ def predict(request: gr.Request, text_input, sample_size_slider, reduce_sample_checkbox,
139
+ sample_reduction_method, plot_time_checkbox,
140
+ locally_approximate_publication_date_checkbox,
141
+ download_csv_checkbox, download_png_checkbox, citation_graph_checkbox,
142
+ progress=gr.Progress()):
143
+ """
144
+ Main prediction pipeline that processes OpenAlex queries and creates visualizations.
145
+
146
+ Args:
147
+ request (gr.Request): Gradio request object
148
+ text_input (str): OpenAlex query URL
149
+ sample_size_slider (int): Maximum number of samples to process
150
+ reduce_sample_checkbox (bool): Whether to reduce sample size
151
+ sample_reduction_method (str): Method for sample reduction ("Random" or "Order of Results")
152
+ plot_time_checkbox (bool): Whether to color points by publication date
153
+ locally_approximate_publication_date_checkbox (bool): Whether to approximate publication date locally before plotting.
154
+ progress (gr.Progress): Gradio progress tracker
155
+
156
+ Returns:
157
+ tuple: (link to visualization, iframe HTML)
158
+ """
159
+ # Get the authentication token
160
  token = _get_token(request)
161
+ print(f"Token: {token}")
162
+ print(f"Request: {request}")
163
+ # Check if input is empty or whitespace
164
+ print(f"Input: {text_input}")
165
+ if not text_input or text_input.isspace():
166
+ error_message = "Error: Please enter a valid OpenAlex URL in the 'OpenAlex-search URL'-field"
167
+ return [
168
+ error_message, # iframe HTML
169
+ gr.DownloadButton(label="Download Interactive Visualization", value='html_file_path', visible=False), # html download
170
+ gr.DownloadButton(label="Download CSV Data", value='csv_file_path', visible=False), # csv download
171
+ gr.DownloadButton(label="Download Static Plot", value='png_file_path', visible=False), # png download
172
+ gr.Button(visible=False) # cancel button state
173
+ ]
174
+
175
+
176
+
177
+ # Check if the input is a valid OpenAlex URL
178
+
179
+
180
+
181
+ start_time = time.time()
182
+ print('Starting data projection pipeline')
183
+ progress(0.1, desc="Starting...")
184
+
185
+ # Split input into multiple URLs if present
186
+ urls = [url.strip() for url in text_input.split(';')]
187
+ records = []
188
+ total_query_length = 0
189
+
190
+ # Use first URL for filename
191
+ first_query, first_params = openalex_url_to_pyalex_query(urls[0])
192
+ filename = openalex_url_to_filename(urls[0])
193
+ print(f"Filename: {filename}")
194
+
195
+ # Process each URL
196
+ for i, url in enumerate(urls):
197
+ query, params = openalex_url_to_pyalex_query(url)
198
+ query_length = query.count()
199
+ total_query_length += query_length
200
+ print(f'Requesting {query_length} entries from query {i+1}/{len(urls)}...')
201
+
202
+ target_size = sample_size_slider if reduce_sample_checkbox and sample_reduction_method == "First n samples" else query_length
203
+ records_per_query = 0
204
+
205
+ should_break = False
206
+ for page in query.paginate(per_page=200, n_max=None):
207
+ for record in page:
208
+ records.append(record)
209
+ records_per_query += 1
210
+ progress(0.1 + (0.2 * len(records) / (total_query_length)),
211
+ desc=f"Getting data from query {i+1}/{len(urls)}...")
212
+
213
+ if reduce_sample_checkbox and sample_reduction_method == "First n samples" and records_per_query >= target_size:
214
+ should_break = True
215
+ break
216
+ if should_break:
217
+ break
218
+ if should_break:
219
+ break
220
+ print(f"Query completed in {time.time() - start_time:.2f} seconds")
221
+
222
+ # Process records
223
+ processing_start = time.time()
224
+ records_df = process_records_to_df(records)
225
+
226
+ if reduce_sample_checkbox and sample_reduction_method != "All":
227
+ sample_size = min(sample_size_slider, len(records_df))
228
+ if sample_reduction_method == "n random samples":
229
+ records_df = records_df.sample(sample_size)
230
+ elif sample_reduction_method == "First n samples":
231
+ records_df = records_df.iloc[:sample_size]
232
+ print(f"Records processed in {time.time() - processing_start:.2f} seconds")
233
+
234
+ # Create embeddings
235
+ embedding_start = time.time()
236
+ progress(0.3, desc="Embedding Data...")
237
+ texts_to_embedd = [f"{title} {abstract}" for title, abstract
238
+ in zip(records_df['title'], records_df['abstract'])]
239
+ embeddings = create_embeddings(texts_to_embedd)
240
+ print(f"Embeddings created in {time.time() - embedding_start:.2f} seconds")
241
+
242
+ # Project embeddings
243
+ projection_start = time.time()
244
+ progress(0.5, desc="Project into UMAP-embedding...")
245
+ umap_embeddings = mapper.transform(embeddings)
246
+ records_df[['x','y']] = umap_embeddings
247
+ print(f"Projection completed in {time.time() - projection_start:.2f} seconds")
248
+
249
+ # Prepare visualization data
250
+ viz_prep_start = time.time()
251
+ progress(0.6, desc="Preparing visualization data...")
252
+
253
+ basedata_df['color'] = '#ced4d211'
254
+
255
+ if not plot_time_checkbox:
256
+ records_df['color'] = '#5e2784'
257
+ else:
258
+ cmap = colormaps.haline
259
+ if not locally_approximate_publication_date_checkbox:
260
+ # Create color mapping based on publication years
261
+ years = pd.to_numeric(records_df['publication_year'])
262
+ norm = mcolors.Normalize(vmin=years.min(), vmax=years.max())
263
+ records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in years]
264
+
265
+ else:
266
+ n_neighbors = 10 # Adjust this value to control smoothing
267
+ nn = NearestNeighbors(n_neighbors=n_neighbors)
268
+ nn.fit(umap_embeddings)
269
+ distances, indices = nn.kneighbors(umap_embeddings)
270
+
271
+ # Calculate local average publication year for each point
272
+ local_years = np.array([
273
+ np.mean(records_df['publication_year'].iloc[idx])
274
+ for idx in indices
275
+ ])
276
+ norm = mcolors.Normalize(vmin=local_years.min(), vmax=local_years.max())
277
+ records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in local_years]
278
+
279
+
280
+
281
+ stacked_df = pd.concat([basedata_df, records_df], axis=0, ignore_index=True)
282
+ stacked_df = stacked_df.fillna("Unlabelled")
283
+ stacked_df['parsed_field'] = [get_field(row) for ix, row in stacked_df.iterrows()]
284
+ extra_data = pd.DataFrame(stacked_df['doi'])
285
+ print(f"Visualization data prepared in {time.time() - viz_prep_start:.2f} seconds")
286
+ if citation_graph_checkbox:
287
+ citation_graph_start = time.time()
288
+ citation_graph = create_citation_graph(records_df)
289
+ graph_file_name = f"{filename}_citation_graph.jpg"
290
+ graph_file_path = static_dir / graph_file_name
291
+ draw_citation_graph(citation_graph,path=graph_file_path,bundle_edges=True,
292
+ min_max_coordinates=[np.min(stacked_df['x']),np.max(stacked_df['x']),np.min(stacked_df['y']),np.max(stacked_df['y'])])
293
+ print(f"Citation graph created and saved in {time.time() - citation_graph_start:.2f} seconds")
294
+
295
+
296
+
297
+
298
+ # Create and save plot
299
+ plot_start = time.time()
300
+ progress(0.7, desc="Creating interactive plot...")
301
+ # Create a solid black colormap
302
+ black_cmap = mcolors.LinearSegmentedColormap.from_list('black', ['#000000', '#000000'])
303
+
304
+
305
+ plot = datamapplot.create_interactive_plot(
306
+ stacked_df[['x','y']].values,
307
+ np.array(stacked_df['cluster_2_labels']),
308
+ np.array(['Unlabelled' if pd.isna(x) else x for x in stacked_df['parsed_field']]),
309
+
310
+ hover_text=[str(row['title']) for ix, row in stacked_df.iterrows()],
311
+ marker_color_array=stacked_df['color'],
312
+ use_medoids=False, # Switch back once efficient mediod caclulation comes out!
313
+ width=1000,
314
+ height=1000,
315
+ point_radius_min_pixels=1,
316
+ text_outline_width=5,
317
+ point_hover_color='#5e2784',
318
+ point_radius_max_pixels=7,
319
+ cmap=black_cmap,
320
+ background_image=graph_file_name if citation_graph_checkbox else None,
321
+ #color_label_text=False,
322
+ font_family="Roboto Condensed",
323
+ font_weight=600,
324
+ tooltip_font_weight=600,
325
+ tooltip_font_family="Roboto Condensed",
326
+ extra_point_data=extra_data,
327
+ on_click="window.open(`{doi}`)",
328
+ custom_css=DATAMAP_CUSTOM_CSS,
329
+ initial_zoom_fraction=.8,
330
+ enable_search=False,
331
+ offline_mode=False
332
+ )
333
+
334
+ # Save plot
335
+ html_file_name = f"{filename}.html"
336
+ html_file_path = static_dir / html_file_name
337
+ plot.save(html_file_path)
338
+ print(f"Plot created and saved in {time.time() - plot_start:.2f} seconds")
339
+
340
+
341
+
342
+ # Save additional files if requested
343
+ csv_file_path = static_dir / f"{filename}.csv"
344
+ png_file_path = static_dir / f"{filename}.png"
345
+
346
+ if download_csv_checkbox:
347
+ # Export relevant column
348
+ export_df = records_df[['title', 'abstract', 'doi', 'publication_year', 'x', 'y','id','primary_topic']]
349
+ export_df['parsed_field'] = [get_field(row) for ix, row in export_df.iterrows()]
350
+ export_df['referenced_works'] = [', '.join(x) for x in records_df['referenced_works']]
351
+ export_df.to_csv(csv_file_path, index=False)
352
+
353
+ if download_png_checkbox:
354
+ png_start_time = time.time()
355
+ print("Starting PNG generation...")
356
+
357
+ # Sample and prepare data
358
+ sample_prep_start = time.time()
359
+ sample_to_plot = basedata_df#.sample(20000)
360
+ labels1 = np.array(sample_to_plot['cluster_2_labels'])
361
+ labels2 = np.array(['Unlabelled' if pd.isna(x) else x for x in sample_to_plot['parsed_field']])
362
+
363
+ ratio = 0.6
364
+ mask = np.random.random(size=len(labels1)) < ratio
365
+ combined_labels = np.where(mask, labels1, labels2)
366
+
367
+ # Get the 30 most common labels
368
+ unique_labels, counts = np.unique(combined_labels, return_counts=True)
369
+ top_30_labels = set(unique_labels[np.argsort(counts)[-50:]])
370
+
371
+ # Replace less common labels with 'Unlabelled'
372
+ combined_labels = np.array(['Unlabelled' if label not in top_30_labels else label for label in combined_labels])
373
+ #combined_labels = np.array(['Unlabelled' for label in combined_labels])
374
+ #if label not in top_30_labels else label
375
+ colors_base = ['#536878' for _ in range(len(labels1))]
376
+ print(f"Sample preparation completed in {time.time() - sample_prep_start:.2f} seconds")
377
+
378
+ # Create main plot
379
+ print(labels1)
380
+ print(labels2)
381
+ print(sample_to_plot[['x','y']].values)
382
+ print(combined_labels)
383
+
384
+ main_plot_start = time.time()
385
+ fig, ax = datamapplot.create_plot(
386
+ sample_to_plot[['x','y']].values,
387
+ combined_labels,
388
+ label_wrap_width=12,
389
+ label_over_points=True,
390
+ dynamic_label_size=True,
391
+ use_medoids=False, # Switch back once efficient mediod caclulation comes out!
392
+ point_size=2,
393
+ marker_color_array=colors_base,
394
+ force_matplotlib=True,
395
+ max_font_size=12,
396
+ min_font_size=4,
397
+ min_font_weight=100,
398
+ max_font_weight=300,
399
+ font_family="Roboto Condensed",
400
+ color_label_text=False, add_glow=False,
401
+ highlight_labels=list(np.unique(labels1)),
402
+ label_font_size=8,
403
+ highlight_label_keywords={"fontsize": 12, "fontweight": "bold", "bbox":{"boxstyle":"circle", "pad":0.75,'alpha':0.}},
404
+ )
405
+ print(f"Main plot creation completed in {time.time() - main_plot_start:.2f} seconds")
406
+
407
+
408
+ if citation_graph_checkbox:
409
+
410
+ # Read and add the graph image
411
+ graph_img = plt.imread(graph_file_path)
412
+ 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'])],
413
+ alpha=0.9, aspect='auto')
414
+
415
+
416
+
417
+ # Time-based visualization
418
+ scatter_start = time.time()
419
+ if plot_time_checkbox:
420
+ if locally_approximate_publication_date_checkbox:
421
+ scatter = plt.scatter(
422
+ umap_embeddings[:,0],
423
+ umap_embeddings[:,1],
424
+ c=local_years,
425
+ cmap=colormaps.haline,
426
+ alpha=0.8,
427
+ s=5
428
+ )
429
+ else:
430
+ years = pd.to_numeric(records_df['publication_year'])
431
+ scatter = plt.scatter(
432
+ umap_embeddings[:,0],
433
+ umap_embeddings[:,1],
434
+ c=years,
435
+ cmap=colormaps.haline,
436
+ alpha=0.8,
437
+ s=5
438
+ )
439
+ plt.colorbar(scatter, shrink=0.5, format='%d')
440
+ else:
441
+ scatter = plt.scatter(
442
+ umap_embeddings[:,0],
443
+ umap_embeddings[:,1],
444
+ c=records_df['color'],
445
+ alpha=0.8,
446
+ s=5
447
+ )
448
+ print(f"Scatter plot creation completed in {time.time() - scatter_start:.2f} seconds")
449
+
450
+ # Save plot
451
+ save_start = time.time()
452
+ plt.axis('off')
453
+ png_file_path = static_dir / f"{filename}.png"
454
+ plt.savefig(png_file_path, dpi=300, bbox_inches='tight')
455
+ plt.close()
456
+ print(f"Plot saving completed in {time.time() - save_start:.2f} seconds")
457
+
458
+ print(f"Total PNG generation completed in {time.time() - png_start_time:.2f} seconds")
459
+
460
+
461
+
462
+
463
+
464
+ progress(1.0, desc="Done!")
465
+ print(f"Total pipeline completed in {time.time() - start_time:.2f} seconds")
466
+ iframe = f"""<iframe src="{html_file_path}" width="100%" height="1000px"></iframe>"""
467
+
468
+ # Return iframe and download buttons with appropriate visibility
469
+ return [
470
+ iframe,
471
+ gr.DownloadButton(label="Download Interactive Visualization", value=html_file_path, visible=True, variant='secondary'),
472
+ gr.DownloadButton(label="Download CSV Data", value=csv_file_path, visible=download_csv_checkbox, variant='secondary'),
473
+ gr.DownloadButton(label="Download Static Plot", value=png_file_path, visible=download_png_checkbox, variant='secondary'),
474
+ gr.Button(visible=False) # Return hidden state for cancel button
475
+ ]
476
+
477
+ predict.zerogpu = True
478
+
479
+
480
+
481
+ theme = gr.themes.Monochrome(
482
+ font=[gr.themes.GoogleFont("Roboto Condensed"), "ui-sans-serif", "system-ui", "sans-serif"],
483
+ text_size="lg",
484
+ ).set(
485
+ button_secondary_background_fill="white",
486
+ button_secondary_background_fill_hover="#f3f4f6",
487
+ button_secondary_border_color="black",
488
+ button_secondary_text_color="black",
489
+ button_border_width="2px",
490
+ )
491
+
492
+
493
+ # Gradio interface setup
494
+ with gr.Blocks(theme=theme, css="""
495
+ .gradio-container a {
496
+ color: black !important;
497
+ text-decoration: none !important; /* Force remove default underline */
498
+ font-weight: bold;
499
+ transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out;
500
+ display: inline-block; /* Enable proper spacing for descenders */
501
+ line-height: 1.1; /* Adjust line height */
502
+ padding-bottom: 2px; /* Add space for descenders */
503
+ }
504
+ .gradio-container a:hover {
505
+ color: #b23310 !important;
506
+ border-bottom: 3px solid #b23310; /* Wider underline, only on hover */
507
+ }
508
+ """) as demo:
509
  gr.Markdown("""
510
+ <div style="max-width: 100%; margin: 0 auto;">
511
+ <br>
512
+
513
+ # OpenAlex Mapper
514
+
515
+ 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/).
516
+
517
+ 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.
518
+ </div>
519
+ """)
520
+
521
+
522
  with gr.Row():
523
+ with gr.Column(scale=1):
524
+ with gr.Row():
525
+ run_btn = gr.Button("Run Query", variant='primary')
526
+ cancel_btn = gr.Button("Cancel", visible=False, variant='secondary')
527
+
528
+ # Create separate download buttons
529
+ html_download = gr.DownloadButton("Download Interactive Visualization", visible=False, variant='secondary')
530
+ csv_download = gr.DownloadButton("Download CSV Data", visible=False, variant='secondary')
531
+ png_download = gr.DownloadButton("Download Static Plot", visible=False, variant='secondary')
532
+
533
+ text_input = gr.Textbox(label="OpenAlex-search URL",
534
+ info="Enter the URL to an OpenAlex-search.")
535
+
536
+ gr.Markdown("### Sample Settings")
537
+ reduce_sample_checkbox = gr.Checkbox(
538
+ label="Reduce Sample Size",
539
+ value=True,
540
+ info="Reduce sample size."
541
+ )
542
+ sample_reduction_method = gr.Dropdown(
543
+ ["All", "First n samples", "n random samples"],
544
+ label="Sample Selection Method",
545
+ value="First n samples",
546
+ info="How to choose the samples to keep."
547
+ )
548
+ sample_size_slider = gr.Slider(
549
+ label="Sample Size",
550
+ minimum=500,
551
+ maximum=20000,
552
+ step=10,
553
+ value=1000,
554
+ info="How many samples to keep.",
555
+ visible=True
556
+ )
557
+
558
+ gr.Markdown("### Plot Settings")
559
+ plot_time_checkbox = gr.Checkbox(
560
+ label="Plot Time",
561
+ value=True,
562
+ info="Colour points by their publication date."
563
+ )
564
+ locally_approximate_publication_date_checkbox = gr.Checkbox(
565
+ label="Locally Approximate Publication Date",
566
+ value=True,
567
+ info="Colour points by the average publication date in their area."
568
+ )
569
+
570
+ gr.Markdown("### Download Options")
571
+ download_csv_checkbox = gr.Checkbox(
572
+ label="Generate CSV Export",
573
+ value=False,
574
+ info="Export the data as CSV file"
575
+ )
576
+ download_png_checkbox = gr.Checkbox(
577
+ label="Generate Static PNG Plot",
578
+ value=False,
579
+ info="Export a static PNG visualization. This will make things slower!"
580
+ )
581
+
582
+ gr.Markdown("### Citation graph")
583
+ citation_graph_checkbox = gr.Checkbox(
584
+ label="Add Citation Graph",
585
+ value=False,
586
+ info="Adds a citation graph of the sample to the plot."
587
+ )
588
+
589
+
590
+
591
+ with gr.Column(scale=2):
592
+ html = gr.HTML(
593
+ 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>',
594
+ label="",
595
+ show_label=False
596
+ )
597
+ gr.Markdown("""
598
+ <div style="max-width: 100%; margin: 0 auto;">
599
+
600
+ # FAQs
601
+
602
+ ## Who made this?
603
+
604
+ 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 **...**
605
+
606
+ 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).
607
+
608
+ ## How does it work?
609
+
610
+ 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: **...**
611
+
612
+ ## I want to add multiple queries at once!
613
+
614
+ 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!
615
+
616
+ ## I think I found a mistake in the map.
617
+
618
+ There are various considerations to take into account when working with this map:
619
+
620
+ 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.
621
+
622
+ 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.
623
+
624
+ 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.
625
+
626
+ </div>
627
+ """)
628
+
629
+ def update_slider_visibility(method):
630
+ return gr.Slider(visible=(method != "All"))
631
+
632
+ sample_reduction_method.change(
633
+ fn=update_slider_visibility,
634
+ inputs=[sample_reduction_method],
635
+ outputs=[sample_size_slider]
636
+ )
637
+
638
+ def show_cancel_button():
639
+ return gr.Button(visible=True)
640
+
641
+ def hide_cancel_button():
642
+ return gr.Button(visible=False)
643
+
644
+ show_cancel_button.zerogpu = True
645
+ hide_cancel_button.zerogpu = True
646
+ predict.zerogpu = True
647
+
648
+ # Update the run button click event
649
+ run_event = run_btn.click(
650
+ fn=show_cancel_button,
651
+ outputs=cancel_btn,
652
+ queue=False
653
+ ).then(
654
+ fn=predict,
655
+ inputs=[
656
+ text_input,
657
+ sample_size_slider,
658
+ reduce_sample_checkbox,
659
+ sample_reduction_method,
660
+ plot_time_checkbox,
661
+ locally_approximate_publication_date_checkbox,
662
+ download_csv_checkbox,
663
+ download_png_checkbox,
664
+ citation_graph_checkbox
665
+ ],
666
+ outputs=[html, html_download, csv_download, png_download, cancel_btn]
667
+ )
668
+
669
+ # Add cancel button click event
670
+ cancel_btn.click(
671
+ fn=hide_cancel_button,
672
+ outputs=cancel_btn,
673
+ cancels=[run_event],
674
+ queue=False # Important to make the button hide immediately
675
+ )
676
+
677
+
678
+ # demo.static_dirs = {
679
+ # "static": str(static_dir)
680
+ # }
681
+
682
+
683
+ # Mount and run app
684
+ # app = gr.mount_gradio_app(app, demo, path="/",ssr_mode=False)
685
+
686
+ # app.zerogpu = True # Add this line
687
 
 
688
 
689
+ # if __name__ == "__main__":
690
+ # demo.launch(server_name="0.0.0.0", server_port=7860, share=True,allowed_paths=["/static"])
691
+
692
  # Mount Gradio app to FastAPI
693
+ app = gr.mount_gradio_app(app, demo, path="/")
694
 
695
  # Run both servers
696
  if __name__ == "__main__":
app_2.py CHANGED
@@ -1,676 +1,85 @@
1
- import spaces # necessary to run on Zero.
2
- from spaces.zero.client import _get_token
3
-
4
- import time
5
- print(f"Starting up: {time.strftime('%Y-%m-%d %H:%M:%S')}")
6
-
7
- # Standard library imports
8
- import os
9
- from pathlib import Path
10
- from datetime import datetime
11
- from itertools import chain
12
-
13
- # Third-party imports
14
- import numpy as np
15
- import pandas as pd
16
- import torch
17
- import gradio as gr
18
-
19
- print(f"Gradio version: {gr.__version__}")
20
-
21
- from fastapi import FastAPI
22
- from fastapi.staticfiles import StaticFiles
23
- import uvicorn
24
- import matplotlib.pyplot as plt
25
- import tqdm
26
- import colormaps
27
- import matplotlib.colors as mcolors
28
- from matplotlib.colors import Normalize
29
-
30
-
31
-
32
- import opinionated # for fonts
33
- plt.style.use("opinionated_rc")
34
 
35
- from sklearn.neighbors import NearestNeighbors
36
-
37
-
38
- def is_running_in_hf_space():
39
- return "SPACE_ID" in os.environ
40
-
41
- #if is_running_in_hf_space():
42
- import spaces # necessary to run on Zero.
43
- #print(f"Spaces version: {spaces.__version__}")
44
-
45
- import datamapplot
46
- import pyalex
47
-
48
- # Local imports
49
- from openalex_utils import (
50
- openalex_url_to_pyalex_query,
51
- get_field,
52
- process_records_to_df,
53
- openalex_url_to_filename
54
- )
55
- from styles import DATAMAP_CUSTOM_CSS
56
- from data_setup import (
57
- download_required_files,
58
- setup_basemap_data,
59
- setup_mapper,
60
- setup_embedding_model,
61
 
62
- )
63
-
64
- from network_utils import create_citation_graph, draw_citation_graph
65
-
66
-
67
-
68
-
69
- # Configure OpenAlex
70
- pyalex.config.email = "[email protected]"
71
-
72
- print(f"Imports completed: {time.strftime('%Y-%m-%d %H:%M:%S')}")
73
-
74
-
75
-
76
- # Instead of FastAPI setup, just use Gradio's file serving
77
- static_dir = Path("./static")
78
- static_dir.mkdir(parents=True, exist_ok=True)
79
- gr.set_static_paths(paths=["static/"])
80
-
81
- # Resource configuration
82
- REQUIRED_FILES = {
83
- "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl":
84
- "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/100k_filtered_OA_sample_cluster_and_positions_supervised.pkl",
85
- "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl":
86
- "https://huggingface.co/datasets/m7n/intermediate_sci_pickle/resolve/main/umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
87
- }
88
- BASEMAP_PATH = "100k_filtered_OA_sample_cluster_and_positions_supervised.pkl"
89
- MAPPER_PARAMS_PATH = "umap_mapper_250k_random_OA_discipline_tuned_specter_2_params.pkl"
90
- MODEL_NAME = "m7n/discipline-tuned_specter_2_024"
91
-
92
- # Initialize models and data
93
- start_time = time.time()
94
- print("Initializing resources...")
95
-
96
- download_required_files(REQUIRED_FILES)
97
- basedata_df = setup_basemap_data(BASEMAP_PATH)
98
- mapper = setup_mapper(MAPPER_PARAMS_PATH)
99
- model = setup_embedding_model(MODEL_NAME)
100
-
101
- print(f"Resources initialized in {time.time() - start_time:.2f} seconds")
102
-
103
-
104
-
105
- # Setting up decorators for embedding on HF-Zero:
106
- def no_op_decorator(func):
107
- """A no-op (no operation) decorator that simply returns the function."""
108
- def wrapper(*args, **kwargs):
109
- # Do nothing special
110
- return func(*args, **kwargs)
111
- return wrapper
112
-
113
- # # Decide which decorator to use based on environment
114
- # decorator_to_use = spaces.GPU() if is_running_in_hf_space() else no_op_decorator
115
- # #duration=120
116
-
117
- # @decorator_to_use
118
- @spaces.GPU(duration=4*60)
119
- def create_embeddings(texts_to_embedd):
120
- """Create embeddings for the input texts using the loaded model."""
121
- return model.encode(texts_to_embedd, show_progress_bar=True, batch_size=192)
122
-
123
-
124
- def predict(request: gr.Request, text_input, sample_size_slider, reduce_sample_checkbox,
125
- sample_reduction_method, plot_time_checkbox,
126
- locally_approximate_publication_date_checkbox,
127
- download_csv_checkbox, download_png_checkbox, citation_graph_checkbox,
128
- progress=gr.Progress()):
129
- """
130
- Main prediction pipeline that processes OpenAlex queries and creates visualizations.
131
 
132
- Args:
133
- request (gr.Request): Gradio request object
134
- text_input (str): OpenAlex query URL
135
- sample_size_slider (int): Maximum number of samples to process
136
- reduce_sample_checkbox (bool): Whether to reduce sample size
137
- sample_reduction_method (str): Method for sample reduction ("Random" or "Order of Results")
138
- plot_time_checkbox (bool): Whether to color points by publication date
139
- locally_approximate_publication_date_checkbox (bool): Whether to approximate publication date locally before plotting.
140
- progress (gr.Progress): Gradio progress tracker
141
 
142
- Returns:
143
- tuple: (link to visualization, iframe HTML)
144
- """
145
- # Get the authentication token
146
- token = _get_token(request)
147
- print(f"Token: {token}")
148
- print(f"Request: {request}")
149
- # Check if input is empty or whitespace
150
- print(f"Input: {text_input}")
151
- if not text_input or text_input.isspace():
152
- error_message = "Error: Please enter a valid OpenAlex URL in the 'OpenAlex-search URL'-field"
153
- return [
154
- error_message, # iframe HTML
155
- gr.DownloadButton(label="Download Interactive Visualization", value='html_file_path', visible=False), # html download
156
- gr.DownloadButton(label="Download CSV Data", value='csv_file_path', visible=False), # csv download
157
- gr.DownloadButton(label="Download Static Plot", value='png_file_path', visible=False), # png download
158
- gr.Button(visible=False) # cancel button state
159
- ]
160
-
161
-
162
-
163
- # Check if the input is a valid OpenAlex URL
164
-
165
-
166
-
167
- start_time = time.time()
168
- print('Starting data projection pipeline')
169
- progress(0.1, desc="Starting...")
170
-
171
- # Split input into multiple URLs if present
172
- urls = [url.strip() for url in text_input.split(';')]
173
- records = []
174
- total_query_length = 0
175
-
176
- # Use first URL for filename
177
- first_query, first_params = openalex_url_to_pyalex_query(urls[0])
178
- filename = openalex_url_to_filename(urls[0])
179
- print(f"Filename: {filename}")
180
-
181
- # Process each URL
182
- for i, url in enumerate(urls):
183
- query, params = openalex_url_to_pyalex_query(url)
184
- query_length = query.count()
185
- total_query_length += query_length
186
- print(f'Requesting {query_length} entries from query {i+1}/{len(urls)}...')
187
-
188
- target_size = sample_size_slider if reduce_sample_checkbox and sample_reduction_method == "First n samples" else query_length
189
- records_per_query = 0
190
-
191
- should_break = False
192
- for page in query.paginate(per_page=200, n_max=None):
193
- for record in page:
194
- records.append(record)
195
- records_per_query += 1
196
- progress(0.1 + (0.2 * len(records) / (total_query_length)),
197
- desc=f"Getting data from query {i+1}/{len(urls)}...")
198
-
199
- if reduce_sample_checkbox and sample_reduction_method == "First n samples" and records_per_query >= target_size:
200
- should_break = True
201
- break
202
- if should_break:
203
- break
204
- if should_break:
205
- break
206
- print(f"Query completed in {time.time() - start_time:.2f} seconds")
207
-
208
- # Process records
209
- processing_start = time.time()
210
- records_df = process_records_to_df(records)
211
 
212
- if reduce_sample_checkbox and sample_reduction_method != "All":
213
- sample_size = min(sample_size_slider, len(records_df))
214
- if sample_reduction_method == "n random samples":
215
- records_df = records_df.sample(sample_size)
216
- elif sample_reduction_method == "First n samples":
217
- records_df = records_df.iloc[:sample_size]
218
- print(f"Records processed in {time.time() - processing_start:.2f} seconds")
219
 
220
- # Create embeddings
221
- embedding_start = time.time()
222
- progress(0.3, desc="Embedding Data...")
223
- texts_to_embedd = [f"{title} {abstract}" for title, abstract
224
- in zip(records_df['title'], records_df['abstract'])]
225
- embeddings = create_embeddings(texts_to_embedd)
226
- print(f"Embeddings created in {time.time() - embedding_start:.2f} seconds")
227
-
228
- # Project embeddings
229
- projection_start = time.time()
230
- progress(0.5, desc="Project into UMAP-embedding...")
231
- umap_embeddings = mapper.transform(embeddings)
232
- records_df[['x','y']] = umap_embeddings
233
- print(f"Projection completed in {time.time() - projection_start:.2f} seconds")
234
-
235
- # Prepare visualization data
236
- viz_prep_start = time.time()
237
- progress(0.6, desc="Preparing visualization data...")
238
-
239
- basedata_df['color'] = '#ced4d211'
240
-
241
- if not plot_time_checkbox:
242
- records_df['color'] = '#5e2784'
243
- else:
244
- cmap = colormaps.haline
245
- if not locally_approximate_publication_date_checkbox:
246
- # Create color mapping based on publication years
247
- years = pd.to_numeric(records_df['publication_year'])
248
- norm = mcolors.Normalize(vmin=years.min(), vmax=years.max())
249
- records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in years]
250
-
251
- else:
252
- n_neighbors = 10 # Adjust this value to control smoothing
253
- nn = NearestNeighbors(n_neighbors=n_neighbors)
254
- nn.fit(umap_embeddings)
255
- distances, indices = nn.kneighbors(umap_embeddings)
256
-
257
- # Calculate local average publication year for each point
258
- local_years = np.array([
259
- np.mean(records_df['publication_year'].iloc[idx])
260
- for idx in indices
261
- ])
262
- norm = mcolors.Normalize(vmin=local_years.min(), vmax=local_years.max())
263
- records_df['color'] = [mcolors.to_hex(cmap(norm(year))) for year in local_years]
264
-
265
-
266
-
267
- stacked_df = pd.concat([basedata_df, records_df], axis=0, ignore_index=True)
268
- stacked_df = stacked_df.fillna("Unlabelled")
269
- stacked_df['parsed_field'] = [get_field(row) for ix, row in stacked_df.iterrows()]
270
- extra_data = pd.DataFrame(stacked_df['doi'])
271
- print(f"Visualization data prepared in {time.time() - viz_prep_start:.2f} seconds")
272
- if citation_graph_checkbox:
273
- citation_graph_start = time.time()
274
- citation_graph = create_citation_graph(records_df)
275
- graph_file_name = f"{filename}_citation_graph.jpg"
276
- graph_file_path = static_dir / graph_file_name
277
- draw_citation_graph(citation_graph,path=graph_file_path,bundle_edges=True,
278
- min_max_coordinates=[np.min(stacked_df['x']),np.max(stacked_df['x']),np.min(stacked_df['y']),np.max(stacked_df['y'])])
279
- print(f"Citation graph created and saved in {time.time() - citation_graph_start:.2f} seconds")
280
-
281
-
282
 
283
 
284
- # Create and save plot
285
- plot_start = time.time()
286
- progress(0.7, desc="Creating interactive plot...")
287
- # Create a solid black colormap
288
- black_cmap = mcolors.LinearSegmentedColormap.from_list('black', ['#000000', '#000000'])
289
 
290
 
291
- plot = datamapplot.create_interactive_plot(
292
- stacked_df[['x','y']].values,
293
- np.array(stacked_df['cluster_2_labels']),
294
- np.array(['Unlabelled' if pd.isna(x) else x for x in stacked_df['parsed_field']]),
295
-
296
- hover_text=[str(row['title']) for ix, row in stacked_df.iterrows()],
297
- marker_color_array=stacked_df['color'],
298
- use_medoids=False, # Switch back once efficient mediod caclulation comes out!
299
- width=1000,
300
- height=1000,
301
- point_radius_min_pixels=1,
302
- text_outline_width=5,
303
- point_hover_color='#5e2784',
304
- point_radius_max_pixels=7,
305
- cmap=black_cmap,
306
- background_image=graph_file_name if citation_graph_checkbox else None,
307
- #color_label_text=False,
308
- font_family="Roboto Condensed",
309
- font_weight=600,
310
- tooltip_font_weight=600,
311
- tooltip_font_family="Roboto Condensed",
312
- extra_point_data=extra_data,
313
- on_click="window.open(`{doi}`)",
314
- custom_css=DATAMAP_CUSTOM_CSS,
315
- initial_zoom_fraction=.8,
316
- enable_search=False,
317
- offline_mode=False
318
- )
319
-
320
- # Save plot
321
- html_file_name = f"{filename}.html"
322
- html_file_path = static_dir / html_file_name
323
- plot.save(html_file_path)
324
- print(f"Plot created and saved in {time.time() - plot_start:.2f} seconds")
325
-
326
 
327
-
328
- # Save additional files if requested
329
- csv_file_path = static_dir / f"{filename}.csv"
330
- png_file_path = static_dir / f"{filename}.png"
331
 
332
- if download_csv_checkbox:
333
- # Export relevant column
334
- export_df = records_df[['title', 'abstract', 'doi', 'publication_year', 'x', 'y','id','primary_topic']]
335
- export_df['parsed_field'] = [get_field(row) for ix, row in export_df.iterrows()]
336
- export_df['referenced_works'] = [', '.join(x) for x in records_df['referenced_works']]
337
- export_df.to_csv(csv_file_path, index=False)
338
-
339
- if download_png_checkbox:
340
- png_start_time = time.time()
341
- print("Starting PNG generation...")
342
-
343
- # Sample and prepare data
344
- sample_prep_start = time.time()
345
- sample_to_plot = basedata_df#.sample(20000)
346
- labels1 = np.array(sample_to_plot['cluster_2_labels'])
347
- labels2 = np.array(['Unlabelled' if pd.isna(x) else x for x in sample_to_plot['parsed_field']])
348
-
349
- ratio = 0.6
350
- mask = np.random.random(size=len(labels1)) < ratio
351
- combined_labels = np.where(mask, labels1, labels2)
352
-
353
- # Get the 30 most common labels
354
- unique_labels, counts = np.unique(combined_labels, return_counts=True)
355
- top_30_labels = set(unique_labels[np.argsort(counts)[-50:]])
356
-
357
- # Replace less common labels with 'Unlabelled'
358
- combined_labels = np.array(['Unlabelled' if label not in top_30_labels else label for label in combined_labels])
359
- #combined_labels = np.array(['Unlabelled' for label in combined_labels])
360
- #if label not in top_30_labels else label
361
- colors_base = ['#536878' for _ in range(len(labels1))]
362
- print(f"Sample preparation completed in {time.time() - sample_prep_start:.2f} seconds")
363
-
364
- # Create main plot
365
- print(labels1)
366
- print(labels2)
367
- print(sample_to_plot[['x','y']].values)
368
- print(combined_labels)
369
-
370
- main_plot_start = time.time()
371
- fig, ax = datamapplot.create_plot(
372
- sample_to_plot[['x','y']].values,
373
- combined_labels,
374
- label_wrap_width=12,
375
- label_over_points=True,
376
- dynamic_label_size=True,
377
- use_medoids=False, # Switch back once efficient mediod caclulation comes out!
378
- point_size=2,
379
- marker_color_array=colors_base,
380
- force_matplotlib=True,
381
- max_font_size=12,
382
- min_font_size=4,
383
- min_font_weight=100,
384
- max_font_weight=300,
385
- font_family="Roboto Condensed",
386
- color_label_text=False, add_glow=False,
387
- highlight_labels=list(np.unique(labels1)),
388
- label_font_size=8,
389
- highlight_label_keywords={"fontsize": 12, "fontweight": "bold", "bbox":{"boxstyle":"circle", "pad":0.75,'alpha':0.}},
390
- )
391
- print(f"Main plot creation completed in {time.time() - main_plot_start:.2f} seconds")
392
-
393
-
394
- if citation_graph_checkbox:
395
-
396
- # Read and add the graph image
397
- graph_img = plt.imread(graph_file_path)
398
- 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'])],
399
- alpha=0.9, aspect='auto')
400
-
401
-
402
-
403
- # Time-based visualization
404
- scatter_start = time.time()
405
- if plot_time_checkbox:
406
- if locally_approximate_publication_date_checkbox:
407
- scatter = plt.scatter(
408
- umap_embeddings[:,0],
409
- umap_embeddings[:,1],
410
- c=local_years,
411
- cmap=colormaps.haline,
412
- alpha=0.8,
413
- s=5
414
- )
415
- else:
416
- years = pd.to_numeric(records_df['publication_year'])
417
- scatter = plt.scatter(
418
- umap_embeddings[:,0],
419
- umap_embeddings[:,1],
420
- c=years,
421
- cmap=colormaps.haline,
422
- alpha=0.8,
423
- s=5
424
- )
425
- plt.colorbar(scatter, shrink=0.5, format='%d')
426
- else:
427
- scatter = plt.scatter(
428
- umap_embeddings[:,0],
429
- umap_embeddings[:,1],
430
- c=records_df['color'],
431
- alpha=0.8,
432
- s=5
433
- )
434
- print(f"Scatter plot creation completed in {time.time() - scatter_start:.2f} seconds")
435
-
436
- # Save plot
437
- save_start = time.time()
438
- plt.axis('off')
439
- png_file_path = static_dir / f"{filename}.png"
440
- plt.savefig(png_file_path, dpi=300, bbox_inches='tight')
441
- plt.close()
442
- print(f"Plot saving completed in {time.time() - save_start:.2f} seconds")
443
-
444
- print(f"Total PNG generation completed in {time.time() - png_start_time:.2f} seconds")
445
-
446
-
447
-
448
-
449
-
450
- progress(1.0, desc="Done!")
451
- print(f"Total pipeline completed in {time.time() - start_time:.2f} seconds")
452
- iframe = f"""<iframe src="{html_file_path}" width="100%" height="1000px"></iframe>"""
453
 
454
- # Return iframe and download buttons with appropriate visibility
455
- return [
456
- iframe,
457
- gr.DownloadButton(label="Download Interactive Visualization", value=html_file_path, visible=True, variant='secondary'),
458
- gr.DownloadButton(label="Download CSV Data", value=csv_file_path, visible=download_csv_checkbox, variant='secondary'),
459
- gr.DownloadButton(label="Download Static Plot", value=png_file_path, visible=download_png_checkbox, variant='secondary'),
460
- gr.Button(visible=False) # Return hidden state for cancel button
461
- ]
462
-
463
- predict.zerogpu = True
464
 
 
 
 
465
 
 
 
 
466
 
467
- theme = gr.themes.Monochrome(
468
- font=[gr.themes.GoogleFont("Roboto Condensed"), "ui-sans-serif", "system-ui", "sans-serif"],
469
- text_size="lg",
470
- ).set(
471
- button_secondary_background_fill="white",
472
- button_secondary_background_fill_hover="#f3f4f6",
473
- button_secondary_border_color="black",
474
- button_secondary_text_color="black",
475
- button_border_width="2px",
476
- )
477
 
 
 
478
 
479
- # Gradio interface setup
480
- with gr.Blocks(theme=theme, css="""
481
- .gradio-container a {
482
- color: black !important;
483
- text-decoration: none !important; /* Force remove default underline */
484
- font-weight: bold;
485
- transition: color 0.2s ease-in-out, border-bottom-color 0.2s ease-in-out;
486
- display: inline-block; /* Enable proper spacing for descenders */
487
- line-height: 1.1; /* Adjust line height */
488
- padding-bottom: 2px; /* Add space for descenders */
489
- }
490
- .gradio-container a:hover {
491
- color: #b23310 !important;
492
- border-bottom: 3px solid #b23310; /* Wider underline, only on hover */
493
- }
494
- """) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
495
  gr.Markdown("""
496
- <div style="max-width: 100%; margin: 0 auto;">
497
- <br>
498
-
499
- # OpenAlex Mapper
500
-
501
- 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/).
502
-
503
- 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.
504
- </div>
505
- """)
506
-
507
-
508
  with gr.Row():
509
- with gr.Column(scale=1):
510
- with gr.Row():
511
- run_btn = gr.Button("Run Query", variant='primary')
512
- cancel_btn = gr.Button("Cancel", visible=False, variant='secondary')
513
-
514
- # Create separate download buttons
515
- html_download = gr.DownloadButton("Download Interactive Visualization", visible=False, variant='secondary')
516
- csv_download = gr.DownloadButton("Download CSV Data", visible=False, variant='secondary')
517
- png_download = gr.DownloadButton("Download Static Plot", visible=False, variant='secondary')
518
-
519
- text_input = gr.Textbox(label="OpenAlex-search URL",
520
- info="Enter the URL to an OpenAlex-search.")
521
-
522
- gr.Markdown("### Sample Settings")
523
- reduce_sample_checkbox = gr.Checkbox(
524
- label="Reduce Sample Size",
525
- value=True,
526
- info="Reduce sample size."
527
- )
528
- sample_reduction_method = gr.Dropdown(
529
- ["All", "First n samples", "n random samples"],
530
- label="Sample Selection Method",
531
- value="First n samples",
532
- info="How to choose the samples to keep."
533
- )
534
- sample_size_slider = gr.Slider(
535
- label="Sample Size",
536
- minimum=500,
537
- maximum=20000,
538
- step=10,
539
- value=1000,
540
- info="How many samples to keep.",
541
- visible=True
542
- )
543
-
544
- gr.Markdown("### Plot Settings")
545
- plot_time_checkbox = gr.Checkbox(
546
- label="Plot Time",
547
- value=True,
548
- info="Colour points by their publication date."
549
- )
550
- locally_approximate_publication_date_checkbox = gr.Checkbox(
551
- label="Locally Approximate Publication Date",
552
- value=True,
553
- info="Colour points by the average publication date in their area."
554
- )
555
-
556
- gr.Markdown("### Download Options")
557
- download_csv_checkbox = gr.Checkbox(
558
- label="Generate CSV Export",
559
- value=False,
560
- info="Export the data as CSV file"
561
- )
562
- download_png_checkbox = gr.Checkbox(
563
- label="Generate Static PNG Plot",
564
- value=False,
565
- info="Export a static PNG visualization. This will make things slower!"
566
- )
567
-
568
- gr.Markdown("### Citation graph")
569
- citation_graph_checkbox = gr.Checkbox(
570
- label="Add Citation Graph",
571
- value=False,
572
- info="Adds a citation graph of the sample to the plot."
573
- )
574
-
575
-
576
-
577
- with gr.Column(scale=2):
578
- html = gr.HTML(
579
- 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>',
580
- label="",
581
- show_label=False
582
- )
583
- gr.Markdown("""
584
- <div style="max-width: 100%; margin: 0 auto;">
585
-
586
- # FAQs
587
-
588
- ## Who made this?
589
-
590
- 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 **...**
591
-
592
- 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).
593
-
594
- ## How does it work?
595
-
596
- 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: **...**
597
-
598
- ## I want to add multiple queries at once!
599
-
600
- 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!
601
-
602
- ## I think I found a mistake in the map.
603
-
604
- There are various considerations to take into account when working with this map:
605
-
606
- 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.
607
-
608
- 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.
609
-
610
- 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.
611
-
612
- </div>
613
- """)
614
-
615
- def update_slider_visibility(method):
616
- return gr.Slider(visible=(method != "All"))
617
-
618
- sample_reduction_method.change(
619
- fn=update_slider_visibility,
620
- inputs=[sample_reduction_method],
621
- outputs=[sample_size_slider]
622
- )
623
-
624
- def show_cancel_button():
625
- return gr.Button(visible=True)
626
-
627
- def hide_cancel_button():
628
- return gr.Button(visible=False)
629
-
630
- show_cancel_button.zerogpu = True
631
- hide_cancel_button.zerogpu = True
632
- predict.zerogpu = True
633
-
634
- # Update the run button click event
635
- run_event = run_btn.click(
636
- fn=show_cancel_button,
637
- outputs=cancel_btn,
638
- queue=False
639
- ).then(
640
- fn=predict,
641
- inputs=[
642
- text_input,
643
- sample_size_slider,
644
- reduce_sample_checkbox,
645
- sample_reduction_method,
646
- plot_time_checkbox,
647
- locally_approximate_publication_date_checkbox,
648
- download_csv_checkbox,
649
- download_png_checkbox,
650
- citation_graph_checkbox
651
- ],
652
- outputs=[html, html_download, csv_download, png_download, cancel_btn]
653
- )
654
-
655
- # Add cancel button click event
656
- cancel_btn.click(
657
- fn=hide_cancel_button,
658
- outputs=cancel_btn,
659
- cancels=[run_event],
660
- queue=False # Important to make the button hide immediately
661
- )
662
-
663
-
664
- # demo.static_dirs = {
665
- # "static": str(static_dir)
666
- # }
667
-
668
-
669
- # Mount and run app
670
- # app = gr.mount_gradio_app(app, demo, path="/",ssr_mode=False)
671
 
672
- # app.zerogpu = True # Add this line
673
 
 
 
674
 
 
675
  if __name__ == "__main__":
676
- demo.launch(server_name="0.0.0.0", server_port=7860, share=True,allowed_paths=["/static"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
 
 
 
 
 
 
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
 
 
 
 
 
 
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
 
 
 
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ from pathlib import Path
15
+ import gradio as gr
16
+ from datetime import datetime
17
+ import os
18
+ import spaces # necessary to run on Zero.
19
+ from spaces.zero.client import _get_token
20
+ from fastapi import FastAPI
21
+ from fastapi.staticfiles import StaticFiles
22
+ import uvicorn
 
23
 
24
+ # Create a static directory to store the dynamic HTML files
25
+ static_dir = Path("./static")
26
+ static_dir.mkdir(parents=True, exist_ok=True)
27
 
28
+ # Tell Gradio which absolute paths are allowed to be served
29
+ os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
30
+ print("os.environ['GRADIO_ALLOWED_PATHS'] =", os.environ["GRADIO_ALLOWED_PATHS"])
31
 
32
+ # Create FastAPI app
33
+ app = FastAPI()
 
 
 
 
 
 
 
 
34
 
35
+ # Mount the static directory
36
+ app.mount("/static", StaticFiles(directory="static"), name="static")
37
 
38
+ @spaces.GPU(duration=4*60)
39
+ def predict(request: gr.Request, text_input):
40
+ token = _get_token(request)
41
+ file_name = f"{datetime.utcnow().strftime('%s')}.html"
42
+ file_path = static_dir / file_name
43
+ print("File will be written to:", file_path)
44
+ with open(file_path, "w") as f:
45
+ f.write(f"""<!DOCTYPE html>
46
+ <html>
47
+ <head>
48
+ <script src="https://cdn.tailwindcss.com"></script>
49
+ </head>
50
+ <body class="bg-gray-200 dark:text-white dark:bg-gray-900">
51
+ <h1 class="text-3xl font-bold">
52
+ Hello <i>{text_input}</i> From Gradio Iframe
53
+ </h1>
54
+ <h3>Filename: {file_name}</h3>
55
+ </body>
56
+ </html>
57
+ """)
58
+ os.chmod(file_path, 0o644)
59
+ # Use the direct static route instead of Gradio's file route
60
+ iframe = f'<iframe src="/static/{file_name}" width="100%" height="500px"></iframe>'
61
+ link = f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
62
+ print("Serving file at URL:", f"/static/{file_name}")
63
+ return link, iframe
64
+
65
+ with gr.Blocks() as block:
66
  gr.Markdown("""
67
+ ## Gradio + Static Files Demo
68
+ This demo generates dynamic HTML files and stores them in a "static" directory. They are then served via Gradio's `/file=` route.
69
+ """)
 
 
 
 
 
 
 
 
 
70
  with gr.Row():
71
+ with gr.Column():
72
+ text_input = gr.Textbox(label="Name")
73
+ markdown = gr.Markdown(label="Output Link")
74
+ new_btn = gr.Button("New")
75
+ with gr.Column():
76
+ html = gr.HTML(label="HTML Preview", show_label=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
79
 
80
+ # Mount Gradio app to FastAPI
81
+ app = gr.mount_gradio_app(app, block, path="/")
82
 
83
+ # Run both servers
84
  if __name__ == "__main__":
85
+ uvicorn.run(app, host="0.0.0.0", port=7860)