| import gradio as gr |
| import urllib.request |
| from bs4 import BeautifulSoup |
| import re |
|
|
| def get_citation(bibcode): |
| """Fetch citation from ADS bibcode""" |
| bibtex_url = f'https://ui.adsabs.harvard.edu/abs/{bibcode}/exportcitation' |
| with urllib.request.urlopen(bibtex_url) as response: |
| bibtex = response.read().decode('utf-8') |
| soup = BeautifulSoup(bibtex, 'html.parser') |
| citation_text = soup.textarea.text |
| return citation_text |
|
|
| def process_bibcodes(bibcode_input): |
| """Process single or multiple bibcodes and generate .bib file""" |
| |
| bibcodes = re.split(r'[,\n\s]+', bibcode_input.strip()) |
| bibcodes = [b.strip() for b in bibcodes if b.strip()] |
| |
| if not bibcodes: |
| return "Error: No bibcodes provided", None |
| |
| all_citations = [] |
| errors = [] |
| |
| for bibcode in bibcodes: |
| try: |
| citation = get_citation(bibcode) |
| all_citations.append(citation) |
| except Exception as e: |
| errors.append(f"Error fetching {bibcode}: {str(e)}") |
| |
| if not all_citations: |
| return "Error: Could not fetch any citations\n" + "\n".join(errors), None |
| |
| |
| combined_bib = "\n\n".join(all_citations) |
| |
| |
| status = f"Successfully fetched {len(all_citations)} citation(s)" |
| if errors: |
| status += "\n\nErrors:\n" + "\n".join(errors) |
| |
| |
| output_filename = "citations.bib" |
| with open(output_filename, 'w', encoding='utf-8') as f: |
| f.write(combined_bib) |
| |
| return status, output_filename |
|
|
| |
| with gr.Blocks(title="ADS BibTeX Citation Generator") as demo: |
| gr.Markdown("# ADS BibTeX Citation Generator") |
| gr.Markdown("Enter one or multiple ADS bibcodes to generate a .bib file. Separate multiple bibcodes with commas, spaces, or newlines.") |
| |
| with gr.Row(): |
| with gr.Column(): |
| bibcode_input = gr.Textbox( |
| label="Bibcode(s)", |
| placeholder="e.g., 2021Natur.592..534C\nor multiple:\n2021Natur.592..534C, 1999AJ....118.2751M", |
| lines=5 |
| ) |
| submit_btn = gr.Button("Generate .bib File", variant="primary") |
| |
| with gr.Column(): |
| status_output = gr.Textbox(label="Status", lines=5) |
| file_output = gr.File(label="Download .bib File") |
| |
| |
| gr.Examples( |
| examples=[ |
| ["2021Natur.592..534C"], |
| ["2021Natur.592..534C\n1999AJ....118.2751M"], |
| ["2021Natur.592..534C, 1999AJ....118.2751M, 2019ApJ...887..235P"] |
| ], |
| inputs=bibcode_input |
| ) |
| |
| submit_btn.click( |
| fn=process_bibcodes, |
| inputs=bibcode_input, |
| outputs=[status_output, file_output] |
| ) |
|
|
| |
| if __name__ == "__main__": |
| demo.launch() |