import os import html import re import time import requests import dotenv import mistune from gradio_client import Client from image import fetch_image dotenv.load_dotenv() access_key = os.getenv('ACCESS_KEY') client_id = os.getenv('CLIENT_ID') client_secret = os.getenv('CLIENT_SECRET') refresh_token = os.getenv('REFRESH_TOKEN') blog_id = os.getenv('BLOG_ID') imgbb_api_key = os.getenv('IMGBB_API_KEY') def generate_post_html(doi, title, category, summary, mindmap, citation): doi = doi.split("https://")[-1] print(f"Generating post for {doi}") title = title.replace("{", r'{').replace("}", r'}') title = re.sub(r"\\(?![a-zA-Z])", r"", title) summary = summary.replace("{", r'{').replace("}", r'}') mindmap = mindmap.replace("{", r'{').replace("}", r'}') citation = citation.replace("{", r'{').replace("}", r'}') citation = mistune.html(citation.replace("&", "&").strip()) image = fetch_image(title, summary, imgbb_api_key) html_summary = mistune.html(summary) post = f"""
{title.strip()}
{{getToc}} $title={{Table of Contents}}
{html_summary.replace("&", "&").strip()}

Mindmap

If MindMap doesn't load, go to the Homepage and visit blog again or Switch to Android App (Under Development).


Citation

{mistune.html(citation.replace("&", "&").strip())}
""" return post, image def create_post(doi, title, category, summary, mindmap, citation): post_title = title post_category = f"{category}" try: post_body, post_image = generate_post_html(doi, title, category, summary, mindmap, citation) # with open('post.html', 'w') as f: # f.write(post_body) # exit(code=0) except Exception as e: print(f"Error generating post: {e}") return None, None, None, None return post_title, post_category, post_body, post_image def post_post(title, category, body, image): title = re.sub(r"\\(?![a-zA-Z])", r"", title) response = None try: data = requests.post( url='https://oauth2.googleapis.com/token', data={ 'grant_type': 'refresh_token', 'client_secret': client_secret, 'refresh_token': refresh_token, 'client_id': client_id, }, ).json() url = f"https://blogger.googleapis.com/v3/blogs/{blog_id}/posts" headers = { 'Authorization': f"Bearer {data['access_token']}", "content-type": "application/json" } post_data = { "kind": "blogger#post", "blog": { "id": blog_id }, "images": [{ "url": image }], "title": title, "content": body, "labels": [category, "ZZZZZZZZZ"] } response = requests.post(url, headers=headers, json=post_data).json() if response['status'] != 'LIVE': print(response) if response['status'] == 'LIVE': print(f"The post '{title}' is {response['status']}") return True else: print(response) print(f"Error posting {title}: {response}") return False except Exception as e: print(response) print(f"Error posting {title}: {e}") return False def post_blog(doi, title, category, summary, mindmap, citation, uaccess_key, wait_time=5): if uaccess_key != access_key: return False else: status = True post_title, post_category, post_body, post_image = create_post(doi, title, category, summary, mindmap, citation) if not all([post_title, post_category, post_body, post_image]): print(f'Failed to create post {post_title}') return False post_title = post_title.replace("&", "&") if "&" in post_title: return False status = post_post(post_title, post_category, post_body, post_image) print(f"Waiting for {wait_time*60} seconds...") time.sleep(wait_time*60) if status: print('Post created successfully') return True else: print('Failed to create post') return False def test(uaccess_key): data = { "status": "success", "Astrophysics": { "2412.16344": { "id": "2412.20276", "doi": "https://doi.org/10.48550/arXiv.2412.20276", "title": "From Painlev\xe9 equations to ${\cal N}=2$ susy gauge theories: prolegomena TDI-$\\infty$", "category": "Astrophysics", "citation": "Nair, D. G., Nagar, N. M., Ramakrishnan, V., Wielgus, M., Arratia, V., Krichbaum, T. P., Zhang, X. A., Ricarte, A., S., S., Hernández-Yévenes, J., Ford, N. M., Bandyopadhyay, B., Gurwell, M., Burridge, R., Pesce, D. W., Doeleman, S. S., Kim, J.-Y., Kim, D., Janssen, M., … Zensus, J. A. (2024). Demographics of black holes at $<$100 R$_{\\rm g}$ scales: accretion flows, jets, and shadows (Version 1). arXiv. https://doi.org/10.48550/ARXIV.2412.20276", "summary": "## Summary\nThe Event Horizon Telescope (EHT) has imaged supermassive black holes (SMBHs) in M87 and Sgr A*, testing General Relativity and constraining black hole mass. The EHT has also imaged inner jets of several SMBHs, but at coarser resolutions than 100 Rg. The \"Event Horizon and Environs\" (ETHER) sample is a comprehensive database of SMBH mass estimates, radio to hard X-ray flux densities, and spectral energy distribution information.\n\n## Highlights\n- The EHT has imaged SMBH shadows in M87 and Sgr A*, testing General Relativity and constraining black hole mass.\n- The EHT has imaged the inner jets of several SMBHs, but at coarser resolutions than 100 Rg.\n- The ETHER sample is a comprehensive database of SMBH mass estimates, radio to hard X-ray flux densities, and spectral energy distribution information.\n- The ETHER database includes predictions for the 230 GHz and 345 GHz flux densities in the EHT field of view for approximately 40,000 SMBHs.\n- The 43 GHz VLBA is the highest frequency sensitive phase-referenced VLBI network, providing valuable constraints for SED modeling.\n- The ngEHT is expected to measure approximately 50 SMBH masses, 30 SMBH spins, and 7 SMBH shadows.\n- The ngEHT will enable demographic studies of SMBHs, testing General Relativity and constraining black hole mass.\n\n## Key Insights\n- The EHT's ability to image SMBH shadows and inner jets has opened a new window into understanding these enigmatic objects, allowing for tests of General Relativity and constraints on black hole mass.\n- The ETHER sample provides a comprehensive database for identifying and optimizing target selection for the EHT and its upgrades, enabling the identification of a \"Gold Sample\" of nearby low-luminosity Active Galactic Nuclei (AGNs) optimal for studying jet bases and potentially imaging black hole shadows.\n- The ngEHT will enable the measurement of approximately 50 SMBH masses, 30 SMBH spins, and 7 SMBH shadows, providing a significant increase in the number of SMBHs that can be studied in detail.\n- The 43 GHz VLBA provides valuable constraints for SED modeling, allowing for the prediction of EHT flux densities and the identification of optimal targets for EHT observations.\n- The ETHER database includes predictions for the 230 GHz and 345 GHz flux densities in the EHT field of view for approximately 40,000 SMBHs, enabling the identification of potential targets for EHT observations.\n- The ngEHT will enable demographic studies of SMBHs, testing General Relativity and constraining black hole mass, and providing insights into the properties of these enigmatic objects.\n- The EHT's ability to image SMBH shadows and inner jets has significant implications for our understanding of these objects and the role they play in the universe, and will continue to be an important area of research in the coming years.", "mindmap": "## Introduction\n- Event Horizon Telescope (EHT) project introduced\n- Studies black holes with high angular resolution\n- Provides insights into black hole physics\n\n## Black Hole Demographics\n- ETHER database for black hole demographics\n- Contains 3.15 million SMBH mass estimates\n- 20,000 VLBI radio flux densities included\n\n## EHT and ngEHT Capabilities\n- EHT resolves SMBH shadows at 10 Rg scale\n- ngEHT expected to improve imaging capabilities\n- Will study SMBHs with higher angular resolution\n\n## Observational Programs\n- 43 GHz VLBA imaging of ETHER targets\n- 230 GHz EHT+ALMA observations planned\n- GMVA+ALMA observations for deep imaging\n\n## Scientific Goals\n- Study jet launching and accretion flows\n- Investigate black hole physics and GR\n- Measure SMBH masses and spins\n\n## Future Prospects\n- ngEHT will improve imaging capabilities\n- Will enable study of more SMBHs\n- Provide insights into black hole physics\n\n## Collaboration and Funding\n- EHT collaboration for research and development\n- Funding agencies supporting the project\n- International collaboration for astronomy research\n\n## Research and Development\n- Developing new imaging techniques\n- Improving telescope sensitivity and resolution\n- Enhancing data analysis and modeling capabilities\n\n## Challenges and Limitations\n- Overcoming technical challenges and limitations\n- Addressing observational and theoretical uncertainties\n- Improving data quality and interpretation\n\n## Conclusion\n- EHT and ngEHT for black hole research\n- Studying SMBH demographics and physics\n- Advancing our understanding of the universe" } } } if data['status'] != 'success': print('Failed to fetch data') else: for category, catdata in data.items(): if category != 'status': for paper_id, paperdata in catdata.items(): title = paperdata['title'] category = paperdata['category'] summary = paperdata.get('summary', '') mindmap = paperdata.get('mindmap', '') citation = paperdata.get('citation', '') uaccess_key = access_key try: escaped_title = repr(title.encode('latin1').decode('unicode-escape')).strip() except: escaped_title = repr(title).strip() title = html.escape(str(escaped_title).strip()[1:-1]) try: encoded_bytes = citation.encode('latin1').decode('utf-8', errors='replace') except: encoded_bytes = repr(citation) citation = html.unescape(encoded_bytes) status = post_blog("2412.20276", title, category, summary, mindmap, citation, uaccess_key, 0) print(status) return status if __name__ == '__main__': test(access_key)