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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import os
4
+ from together import Together
5
+ import argparse
6
+ from datetime import datetime
7
+ import re
8
+ import textwrap
9
+
10
+ # Global variables
11
+ client = None
12
+ current_metadata = None
13
+
14
+ # Import functions after client is defined
15
+ from minimal import (
16
+ extract_metadata,
17
+ save_metadata,
18
+ request_additional_variable,
19
+ remove_variable,
20
+ prompt_llm,
21
+ extract_json_from_response
22
+ )
23
+
24
+ def initialize_client(api_key):
25
+ """Initialize the Together client with the provided API key."""
26
+ global client
27
+ try:
28
+ client = Together(api_key=api_key)
29
+ # Update the client in the minimal module
30
+ import minimal
31
+ minimal.client = client
32
+ return "API key set successfully!"
33
+ except Exception as e:
34
+ return f"Error setting API key: {str(e)}"
35
+
36
+ def process_paper(paper_content):
37
+ """Process the paper content and extract metadata."""
38
+ global client, current_metadata
39
+
40
+ try:
41
+ # Extract metadata directly from content
42
+ current_metadata = extract_metadata(paper_content)
43
+ return json.dumps(current_metadata, indent=4)
44
+ except Exception as e:
45
+ return f"Error processing paper: {str(e)}"
46
+
47
+ def query_metadata(query):
48
+ """Query the current metadata."""
49
+ global current_metadata
50
+
51
+ if not current_metadata:
52
+ return "No metadata available. Please process a paper first."
53
+
54
+ try:
55
+ if not query:
56
+ return json.dumps(current_metadata, indent=4)
57
+
58
+ # Split the query into parts
59
+ parts = query.split('.')
60
+
61
+ # Navigate through the metadata
62
+ result = current_metadata
63
+ for part in parts:
64
+ if part not in result:
65
+ return f"Path '{query}' not found in metadata"
66
+ result = result[part]
67
+
68
+ return json.dumps(result, indent=4)
69
+ except Exception as e:
70
+ return f"Error querying metadata: {str(e)}"
71
+
72
+ def add_variable(variable_name):
73
+ """Request additional information about a variable."""
74
+ global current_metadata, client
75
+
76
+ if not current_metadata:
77
+ return "No metadata available. Please process a paper first."
78
+
79
+ if not client:
80
+ return "Client not initialized. Please process a paper first."
81
+
82
+ try:
83
+ return request_additional_variable(current_metadata, variable_name)
84
+ except Exception as e:
85
+ return f"Error adding variable: {str(e)}"
86
+
87
+ def request_additional_variable(metadata, variable_name):
88
+ """
89
+ Request additional information about a specific variable from the LLM.
90
+
91
+ Args:
92
+ metadata (dict): The current metadata dictionary
93
+ variable_name (str): The name of the variable to get more information about
94
+ """
95
+ global client
96
+
97
+ prompt = f"""Please analyze the research paper and provide detailed information about the following variable: {variable_name}
98
+
99
+ Please provide the information in JSON format with the following structure:
100
+ {{
101
+ "definition": "Clear definition of the variable",
102
+ "measurement_method": "How it was measured/collected",
103
+ "units": "Units of measurement if applicable",
104
+ "importance": "Why this variable is important in the study"
105
+ }}
106
+
107
+ Return ONLY the JSON object, no additional text."""
108
+
109
+ response = prompt_llm(prompt)
110
+ additional_info = extract_json_from_response(response)
111
+
112
+ if additional_info:
113
+ # Add the new information to the metadata
114
+ if 'additional_variables' not in metadata:
115
+ metadata['additional_variables'] = {}
116
+ metadata['additional_variables'][variable_name] = additional_info
117
+ return json.dumps(additional_info, indent=4)
118
+ else:
119
+ return f"Could not extract additional information about {variable_name}"
120
+
121
+ def find_variable_in_metadata(metadata, target_var):
122
+ """Helper function to find a variable in the metadata structure."""
123
+ if isinstance(metadata, dict):
124
+ for key, value in metadata.items():
125
+ if key == target_var:
126
+ return metadata, key
127
+ result = find_variable_in_metadata(value, target_var)
128
+ if result:
129
+ return result
130
+ return None
131
+
132
+ def remove_variable_from_metadata(variable_path):
133
+ """Remove a variable from the metadata."""
134
+ global current_metadata
135
+
136
+ if not current_metadata:
137
+ return "No metadata available. Please process a paper first."
138
+
139
+ try:
140
+ # If the path contains dots, treat it as a full path
141
+ if '.' in variable_path:
142
+ parts = variable_path.split('.')
143
+ current = current_metadata
144
+ for part in parts[:-1]:
145
+ if part not in current:
146
+ return f"Path '{variable_path}' not found in metadata"
147
+ current = current[part]
148
+
149
+ variable_to_remove = parts[-1]
150
+ if variable_to_remove not in current:
151
+ return f"Variable '{variable_to_remove}' not found at path '{variable_path}'"
152
+
153
+ removed_value = current.pop(variable_to_remove)
154
+ return f"Removed variable '{variable_path}' with value: {removed_value}"
155
+ else:
156
+ # Search for the variable in the entire metadata structure
157
+ result = find_variable_in_metadata(current_metadata, variable_path)
158
+ if result:
159
+ parent_dict, var_name = result
160
+ removed_value = parent_dict.pop(var_name)
161
+ return f"Removed variable '{variable_path}' with value: {removed_value}"
162
+ else:
163
+ return f"Variable '{variable_path}' not found in metadata"
164
+ except Exception as e:
165
+ return f"Error removing variable: {str(e)}"
166
+
167
+ def save_current_metadata():
168
+ """Save the current metadata to a file."""
169
+ global current_metadata
170
+
171
+ if not current_metadata:
172
+ return "No metadata available to save."
173
+
174
+ try:
175
+ output_file = save_metadata(current_metadata)
176
+ return f"Metadata saved to: {output_file}"
177
+ except Exception as e:
178
+ return f"Error saving metadata: {str(e)}"
179
+
180
+ def extract_json_from_response(response):
181
+ """
182
+ Extract JSON from the LLM's response.
183
+
184
+ Args:
185
+ response (str): The LLM's response containing JSON
186
+
187
+ Returns:
188
+ dict: The parsed JSON data
189
+ """
190
+ try:
191
+ # Try to parse the response directly as JSON
192
+ return json.loads(response)
193
+ except json.JSONDecodeError:
194
+ # If that fails, try to find JSON in code blocks
195
+ json_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', response, re.DOTALL)
196
+ if json_match:
197
+ try:
198
+ return json.loads(json_match.group(1))
199
+ except json.JSONDecodeError:
200
+ pass
201
+
202
+ # If all parsing attempts fail, return None
203
+ return None
204
+
205
+ def split_paper_into_sections(content):
206
+ """
207
+ Split the paper into logical sections for processing.
208
+
209
+ Args:
210
+ content (str): The full paper content
211
+
212
+ Returns:
213
+ dict: Dictionary containing different sections of the paper
214
+ """
215
+ sections = {
216
+ 'title_abstract': '',
217
+ 'methods': '',
218
+ 'results': '',
219
+ 'discussion': ''
220
+ }
221
+
222
+ # Extract title and abstract
223
+ title_abstract_match = re.search(r'^(.*?)(?=Introduction)', content, re.DOTALL)
224
+ if title_abstract_match:
225
+ sections['title_abstract'] = title_abstract_match.group(1).strip()
226
+
227
+ # Extract methods
228
+ methods_match = re.search(r'Methods\n(.*?)(?=Results|Discussion)', content, re.DOTALL)
229
+ if methods_match:
230
+ sections['methods'] = methods_match.group(1).strip()
231
+
232
+ # Extract results
233
+ results_match = re.search(r'Results\n(.*?)(?=Discussion|Conclusion)', content, re.DOTALL)
234
+ if results_match:
235
+ sections['results'] = results_match.group(1).strip()
236
+
237
+ # Extract discussion
238
+ discussion_match = re.search(r'Discussion\n(.*?)(?=References|$)', content, re.DOTALL)
239
+ if discussion_match:
240
+ sections['discussion'] = discussion_match.group(1).strip()
241
+
242
+ return sections
243
+
244
+ def extract_metadata(content):
245
+ """
246
+ Extract metadata from research paper content using LLM.
247
+
248
+ Args:
249
+ content (str): The research paper content
250
+
251
+ Returns:
252
+ dict: Dictionary containing the extracted metadata
253
+ """
254
+ # Split paper into sections
255
+ sections = split_paper_into_sections(content)
256
+
257
+ # Extract basic information from title and abstract
258
+ basic_info_prompt = f"""Please analyze this section of a research paper and extract the following information in JSON format:
259
+ 1. Basic Information:
260
+ - Title
261
+ - Authors
262
+ - Publication dates (received, accepted, published)
263
+ - DOI
264
+ - Keywords
265
+
266
+ Here is the paper section:
267
+ {sections['title_abstract']}
268
+
269
+ Please provide the information in a structured JSON format. Return ONLY the JSON object, no additional text."""
270
+
271
+ # Extract data information from methods and results
272
+ data_info_prompt = f"""Please analyze these sections of a research paper and extract the following information in JSON format:
273
+ 2. Data Information:
274
+ - Variables measured/collected
275
+ - Spatial extent of the study
276
+ - Temporal extent of the study
277
+ - Sampling resolution (spatial and temporal)
278
+ - Sample size
279
+ - Data collection methods
280
+ - Data sources
281
+ - Any data limitations or constraints
282
+
283
+ Here are the relevant paper sections:
284
+
285
+ Methods:
286
+ {sections['methods']}
287
+
288
+ Results:
289
+ {sections['results']}
290
+
291
+ Please provide the information in a structured JSON format. Return ONLY the JSON object, no additional text."""
292
+
293
+ # Get LLM responses
294
+ basic_info_response = prompt_llm(basic_info_prompt)
295
+ data_info_response = prompt_llm(data_info_prompt)
296
+
297
+ # Extract JSON from responses
298
+ basic_info = extract_json_from_response(basic_info_response)
299
+ data_info = extract_json_from_response(data_info_response)
300
+
301
+ # Process basic info
302
+ if basic_info:
303
+ # Handle publication dates if they're in a nested structure
304
+ if 'publication_dates' in basic_info:
305
+ basic_info['dates'] = basic_info.pop('publication_dates')
306
+
307
+ # Process data info
308
+ if data_info and 'dataInformation' in data_info:
309
+ # Flatten the nested structure
310
+ data_info = data_info['dataInformation']
311
+ # Convert camelCase keys to snake_case
312
+ data_info = {
313
+ 'variables': data_info.get('variablesMeasuredCollected'),
314
+ 'spatial_extent': data_info.get('spatialExtent'),
315
+ 'temporal_extent': data_info.get('temporalExtent'),
316
+ 'sampling_resolution': {
317
+ 'spatial': data_info.get('SamplingResolution', {}).get('spatial'),
318
+ 'temporal': data_info.get('SamplingResolution', {}).get('temporal')
319
+ },
320
+ 'sample_size': data_info.get('sampleSize'),
321
+ 'collection_methods': data_info.get('dataCollectionMethods'),
322
+ 'data_sources': data_info.get('dataSources'),
323
+ 'limitations': data_info.get('dataLimitations')
324
+ }
325
+
326
+ # Create metadata structure
327
+ metadata = {
328
+ 'basic_info': basic_info or {
329
+ 'title': None,
330
+ 'authors': None,
331
+ 'dates': {
332
+ 'received': None,
333
+ 'accepted': None,
334
+ 'published': None
335
+ },
336
+ 'doi': None,
337
+ 'keywords': None
338
+ },
339
+ 'data_info': data_info or {
340
+ 'variables': None,
341
+ 'spatial_extent': None,
342
+ 'temporal_extent': None,
343
+ 'sampling_resolution': {
344
+ 'spatial': None,
345
+ 'temporal': None
346
+ },
347
+ 'sample_size': None,
348
+ 'collection_methods': None,
349
+ 'data_sources': None,
350
+ 'limitations': None
351
+ },
352
+ 'extraction_timestamp': datetime.now().isoformat()
353
+ }
354
+
355
+ return metadata
356
+
357
+ def prompt_llm(prompt, with_linebreak=False):
358
+ """
359
+ Prompt the LLM to extract metadata from research paper content.
360
+
361
+ Args:
362
+ prompt (str): The prompt containing the paper content and instructions
363
+ with_linebreak (bool): Whether to wrap the output with line breaks
364
+
365
+ Returns:
366
+ str: The LLM's response
367
+ """
368
+ global client
369
+
370
+ # model
371
+ model = "meta-llama/Meta-Llama-3-8B-Instruct-Lite"
372
+
373
+ # Make the API call
374
+ response = client.chat.completions.create(
375
+ model=model,
376
+ messages=[{"role": "user", "content": prompt}],
377
+ )
378
+ output = response.choices[0].message.content
379
+
380
+ if with_linebreak:
381
+ # Wrap the output
382
+ wrapped_output = textwrap.fill(output, width=50)
383
+ return wrapped_output
384
+ else:
385
+ return output
386
+
387
+ # Create the Gradio interface
388
+ with gr.Blocks(title="Research Paper Metadata Extractor") as demo:
389
+ gr.Markdown("# Research Paper Metadata Extractor")
390
+
391
+ with gr.Tab("Process Paper"):
392
+ with gr.Row():
393
+ with gr.Column():
394
+ paper_content = gr.Textbox(
395
+ label="Paper Content",
396
+ placeholder="Paste your research paper content here...",
397
+ lines=20,
398
+ value="""Fisheries Research 272 (2024) 106932
399
+ Available online 14 January 2024
400
+ 0165-7836/© 2024 The Authors. Published by Elsevier B.V. This is an open access article under the CC BY-NC-ND license (http://creativecommons.org/licenses/by-
401
+ nc-nd/4.0/).Estimating angler effort and catch from a winter recreational fishery using a
402
+ novel Bayesian methodology to integrate multiple sources of creel
403
+ survey data
404
+ Caroline M. Tucker a,*, Simone Collier a, Geoffrey Legault b, George E. Morgan a, Derrick K. de
405
+ Kerckhove a
406
+ a Ontario Ministry of Natural Resources and Forestry, Aquatic Research and Monitoring Section, 2140 East Bank Drive, Peterborough, ON K9L 1Z8, Canada
407
+ b Unaffiliated, Toronto, ON, Canada
408
+ A R T I C L E I N F O
409
+ Handled by: Russell B Millar
410
+ Keywords:
411
+ Survey design
412
+ Fisheries management
413
+ Catch rates
414
+ Fishing effort
415
+ Bayesian statistics
416
+ A B S T R A C T
417
+ The range of survey methodologies for measuring daily activity, catch and harvest (i.e. creel surveys) of recre-
418
+ ational anglers, is increasing with the advent of new technologies and improvements in remote sensing. Indi-
419
+ vidual creel survey types frequently give different insights into a fishery due to their unique sources of
420
+ methodological bias and coverage, which creates a problem for resource managers since markedly different
421
+ estimates of important fishery metrics can result. We demonstrate a joint estimation approach using a Bayesian
422
+ statistical framework that can bring together multiple survey types to derive a single estimate for important
423
+ metrics. This framework is applied to data collected from a relatively large winter fishery and integrates three
424
+ traditional creel methodologies (i.e. roving, access and aerial counts), each with very different sources of bias, to
425
+ derive a common estimate of angler effort. Models integrating two survey types are found to be have lower
426
+ uncertainty in their estimates. Further, reductions in effort for any one survey type is found to be buffered by the
427
+ joint estimation approach, such that resource managers will likely find benefits in using more than one survey
428
+ methodology in an integrated fashion to monitor a fishery."""
429
+ )
430
+ process_btn = gr.Button("Process Paper")
431
+
432
+ with gr.Column():
433
+ metadata_output = gr.Textbox(
434
+ label="Extracted Metadata",
435
+ lines=20,
436
+ interactive=False
437
+ )
438
+
439
+ with gr.Tab("Query Metadata"):
440
+ with gr.Row():
441
+ with gr.Column():
442
+ query_input = gr.Textbox(
443
+ label="Query",
444
+ placeholder="Enter query (e.g., 'basic_info.title', 'data_info.variables')"
445
+ )
446
+ query_btn = gr.Button("Query")
447
+
448
+ add_var_input = gr.Textbox(
449
+ label="Add Variable",
450
+ placeholder="Enter variable name to get more information"
451
+ )
452
+ add_var_btn = gr.Button("Add Variable")
453
+
454
+ remove_var_input = gr.Textbox(
455
+ label="Remove Variable",
456
+ placeholder="Enter variable path to remove (e.g., 'data_info.variables')"
457
+ )
458
+ remove_var_btn = gr.Button("Remove Variable")
459
+
460
+ save_btn = gr.Button("Save Metadata")
461
+
462
+ with gr.Column():
463
+ query_output = gr.Textbox(
464
+ label="Query Result",
465
+ lines=20,
466
+ interactive=False
467
+ )
468
+
469
+ # Set up event handlers
470
+ process_btn.click(
471
+ process_paper,
472
+ inputs=[paper_content],
473
+ outputs=metadata_output
474
+ )
475
+
476
+ query_btn.click(
477
+ query_metadata,
478
+ inputs=query_input,
479
+ outputs=query_output
480
+ )
481
+
482
+ add_var_btn.click(
483
+ add_variable,
484
+ inputs=add_var_input,
485
+ outputs=query_output
486
+ )
487
+
488
+ remove_var_btn.click(
489
+ remove_variable_from_metadata,
490
+ inputs=remove_var_input,
491
+ outputs=query_output
492
+ )
493
+
494
+ save_btn.click(
495
+ save_current_metadata,
496
+ outputs=query_output
497
+ )
498
+
499
+ if __name__ == "__main__":
500
+ # Parse command line arguments
501
+ parser = argparse.ArgumentParser(description="Extract metadata from research papers using LLM")
502
+ parser.add_argument("-k",
503
+ "--api_key",
504
+ type=str,
505
+ default="407980b3daee11d57187bc919693b335417b40bb15d2ebe504ea8d7a4edb972b",
506
+ help="Together API key for LLM access")
507
+ args = parser.parse_args()
508
+
509
+ # Initialize the Together client
510
+ client = Together(api_key=args.api_key)
511
+
512
+ # Launch the Gradio interface
513
+ demo.launch()