GlycoShape_1 / src /fetch_torsion.py
Jacky233emm's picture
Duplicate from Jacky233emm/GlycoShape
bf004e2
import requests
import os, time
from typing import Optional
BASE_API = "https://glycoshape.org/api/analysis/torsion/"
BASE_PAGE = "https://glycoshape.org/glycan?glytoucan="
def download_torsion(glycan_id: str, save_dir: str = "../torsion_data") -> Optional[str]:
"""
Download torsion data for a given GlycoShape glycan ID.
Parameters
----------
glycan_id : str
GlycoShape ID (e.g. GS00114)
save_dir : str
Directory where the file will be saved
Returns
-------
Optional[str]
Path to the saved file, or None if the download failed
"""
api_url = f"{BASE_API}{glycan_id}"
file_name = f"{glycan_id}_torsion_data.txt"
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/122.0.0.0 Safari/537.36"
),
"Referer": f"{BASE_PAGE}{glycan_id}",
"Accept": "application/json, text/plain, */*",
"Origin": "https://glycoshape.org",
}
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, file_name)
try:
response = requests.get(api_url, headers=headers, timeout=30)
response.raise_for_status()
with open(save_path, "w", encoding="utf-8") as f:
f.write(response.text)
print(f"Download successful: {glycan_id}")
print(f"Saved to: {save_path}")
print(f"Preview: {response.text[:100]}...")
return save_path
except requests.exceptions.HTTPError as e:
print(f"HTTP error while downloading {glycan_id}: {e}")
except requests.exceptions.ConnectionError:
print("Network connection error")
except Exception as e:
print(f"Unexpected error: {e}")
return None
if __name__ == "__main__":
GS_list=os.listdir('../raw_data/')
print("GS_list",len(GS_list),GS_list)
for GS in GS_list:
download_torsion(GS)
time.sleep(1)