m7n commited on
Commit
2f63946
·
1 Parent(s): a2d4ba5

testing solution attempt

Browse files
Files changed (2) hide show
  1. app.py +35 -665
  2. app_2.py +36 -29
app.py CHANGED
@@ -1,676 +1,46 @@
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
  from pathlib import Path
 
 
 
 
 
 
 
2
  import gradio as gr
3
+ from datetime import datetime
4
+ import sys
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
 
7
+ # create a static directory to store the static files
8
+ static_dir = Path('./static')
9
  static_dir.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
11
 
12
+ def predict(text_input):
13
+ file_name = f"{datetime.utcnow().strftime('%s')}.html"
14
+ file_path = static_dir / file_name
15
+ print(file_path)
16
+ with open(file_path, "w") as f:
17
+ f.write(f"""
18
+ <script src="https://cdn.tailwindcss.com"></script>
19
+ <body class="bg-gray-200 dark:text-white dark:bg-gray-900">
20
+ <h1 class="text-3xl font-bold">
21
+ Hello <i>{text_input}</i> From Gradio Iframe
22
+ </h1>
23
+ <h3>Filename: {file_name}</h3>
24
+ """)
25
+ iframe = f"""<iframe src="file={file_path}" width="100%" height="500px"></iframe>"""
26
+ link = f'<a href="file={file_path}" target="_blank">{file_name}</a>'
27
+ return link, iframe
28
+
29
+
30
+ with gr.Blocks() as block:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  gr.Markdown("""
32
+ ## Gradio + FastAPI + Static Server
33
+ This is a demo of how to use Gradio with FastAPI and a static server.
34
+ The Gradio app generates dynamic HTML files and stores them in a static directory. FastAPI serves the static files.
35
+ """)
 
 
 
 
 
 
 
 
36
  with gr.Row():
37
+ with gr.Column():
38
+ text_input = gr.Textbox(label="Name")
39
+ markdown = gr.Markdown(label="Output Box")
40
+ new_btn = gr.Button("New")
41
+ with gr.Column():
42
+ html = gr.HTML(label="HTML preview", show_label=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
45
 
46
+ block.launch(debug=True, share=True)
 
app_2.py CHANGED
@@ -1,4 +1,5 @@
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')}")
@@ -70,13 +71,11 @@ 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
@@ -116,20 +115,22 @@ def no_op_decorator(func):
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
@@ -141,6 +142,10 @@ def predict(text_input, sample_size_slider, reduce_sample_checkbox, sample_reduc
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():
@@ -153,6 +158,7 @@ def predict(text_input, sample_size_slider, reduce_sample_checkbox, sample_reduc
153
  gr.Button(visible=False) # cancel button state
154
  ]
155
 
 
156
 
157
  # Check if the input is a valid OpenAlex URL
158
 
@@ -441,12 +447,9 @@ def predict(text_input, sample_size_slider, reduce_sample_checkbox, sample_reduc
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 [
@@ -635,10 +638,17 @@ with gr.Blocks(theme=theme, css="""
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
 
@@ -650,20 +660,17 @@ with gr.Blocks(theme=theme, css="""
650
  queue=False # Important to make the button hide immediately
651
  )
652
 
653
- show_cancel_button.zerogpu = True
654
- hide_cancel_button.zerogpu = True
655
- predict.zerogpu = True
656
 
657
- # Mount and run app
658
- app = gr.mount_gradio_app(app, demo, path="/",ssr_mode=False)
 
659
 
660
- app.zerogpu = True # Add this line
661
 
 
 
662
 
663
- def start_server(app):
664
- uvicorn.run(app, host="0.0.0.0", port=7860)
665
 
666
- start_server.zerogpu = True
667
 
668
  if __name__ == "__main__":
669
- start_server(app)
 
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')}")
 
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
 
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
 
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():
 
158
  gr.Button(visible=False) # cancel button state
159
  ]
160
 
161
+
162
 
163
  # Check if the input is a valid OpenAlex URL
164
 
 
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 [
 
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
 
 
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"])