import json from dataclasses import asdict from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth app = FastAPI() HTML_ROOT = """ FastAPI x OAuth """ HTML_AFTER=""" """ LOGIN_BUTTON = """
Sign in with Hugging Face
""" LOGOUT_BUTTON = """
Sign Out
{oauth_info}
""" @app.get("/", response_class=HTMLResponse) def main_page(request: Request): oauth_info = parse_huggingface_oauth(request) if oauth_info is None: return HTML_ROOT + LOGIN_BUTTON + HTML_AFTER if len(oauth_info.access_token) > 70: oauth_info.access_token = oauth_info.access_token[:50] + "..." oauth_info.access_token_expires_at = str(oauth_info.access_token_expires_at) # JSON complains about datetimes return HTML_ROOT + LOGOUT_BUTTON.format(oauth_info=json.dumps(asdict(oauth_info), indent=2)) + HTML_AFTER attach_huggingface_oauth(app) if __name__ == "__main__": import uvicorn uvicorn.run(app)