from fastapi import FastAPI, HTTPException import urllib.request from urllib.error import HTTPError from habanero import Crossref from fastapi.responses import HTMLResponse app = FastAPI() BASE_URL = 'https://doi.org/' @app.get("/", response_class=HTMLResponse) def read_root(): html_content = """
As Citation Helper, I specialize in generating citations for academic papers. You can provide me with the DOI (Digital Object Identifier) or the title of an academic paper, and I will create a citation for it.
Here's how you can use my service:
Feel free to start by giving me a DOI or a paper title!
""" return HTMLResponse(content=html_content) @app.get("/title2ref/") async def title2doi(title: str): cr = Crossref() result = cr.works(query=title) # Check if the result has items and the title matches if result['message']['items']: for item in result['message']['items']: if 'title' in item and item['title'][0] == title: doi = item['DOI'] url = BASE_URL + doi req = urllib.request.Request(url) req.add_header('Accept', 'application/x-bibtex') try: with urllib.request.urlopen(req) as f: bibtex = f.read().decode() return {"bibtex": bibtex} except HTTPError as e: if e.code == 404: raise HTTPException(status_code=404, detail="DOI not found") else: raise HTTPException(status_code=503, detail="Service unavailable") # If no matching title found raise HTTPException(status_code=404, detail="Title not found, please enter DOI") @app.get("/doi2ref/") async def doi2ref(doi: str): url = BASE_URL + doi req = urllib.request.Request(url) req.add_header('Accept', 'application/x-bibtex') try: with urllib.request.urlopen(req) as f: bibtex = f.read().decode() return {"bibtex": bibtex} except HTTPError as e: if e.code == 404: raise HTTPException(status_code=404, detail="DOI not found") else: raise HTTPException(status_code=503, detail="Service unavailable") if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=7860)