Spaces:
Running
Running
File size: 36,002 Bytes
057a205 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 | import csv
import http.client
import http.server
import io
import json
import os
import re
import shutil
import socketserver
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
PORT = 8000
DATA_DIR = "spherex_data"
MOSAIC_DIR = "spherex_mosaics"
IRSA_HOST = "irsa.ipac.caltech.edu"
SIA_URL = f"https://{IRSA_HOST}/SIA"
ALLOWED_COLLECTIONS = {"spherex_qr2", "spherex_qr2_deep"}
SIA_COLUMNS = [
"obs_id", "s_ra", "s_dec", "s_region", "em_min", "em_max",
"energy_bandpassname", "t_min", "access_url", "access_estsize",
]
USER_AGENT = "spherex-data-explorer/1.0"
HIPS_CACHE = "hips_cache"
MOC_HOSTS = [
"https://alaskybis.cds.unistra.fr/MocServer/query",
"https://alasky.cds.unistra.fr/MocServer/query",
]
SKY_SURVEYS = {
"dss2-color": ("DSS2 color", "CDS/P/DSS2/color"),
"dss2-red": ("DSS2 red", "CDS/P/DSS2/red"),
"2mass-color": ("2MASS color", "CDS/P/2MASS/color"),
"allwise-color": ("AllWISE color", "CDS/P/allWISE/color"),
"mellinger": ("Mellinger color", "CDS/P/Mellinger/color"),
"panstarrs": ("Pan-STARRS DR1 color", "CDS/P/PanSTARRS/DR1/color-z-zg-g"),
"sdss9": ("SDSS9 color", "CDS/P/SDSS9/color"),
"desi": ("DESI Legacy DR10 color", "CDS/P/DESI-Legacy-Surveys/DR10/color"),
"galex": ("GALEX GR6 AIS color", "CDS/P/GALEXGR6/AIS/color"),
"spitzer": ("Spitzer color", "CDS/P/SPITZER/color"),
}
FALLBACK_BASES = {
"CDS/P/DSS2/color": [
"https://alaskybis.cds.unistra.fr/DSS/DSSColor",
"https://irsa.ipac.caltech.edu/data/hips/CDS/DSS2/color",
"https://casda.csiro.au/hips/DSS2/color",
"https://stpubdata.s3.us-east-1.amazonaws.com/mast/skybackgrounds/DSSColor",
"http://skies.esac.esa.int/DSSColor",
"https://alasky.cds.unistra.fr/DSS/DSSColor",
],
"CDS/P/DSS2/red": [
"https://alaskybis.cds.unistra.fr/DSS/DSS2Merged",
"https://irsa.ipac.caltech.edu/data/hips/CDS/DSS2/red",
"https://alasky.cds.unistra.fr/DSS/DSS2Merged",
],
"CDS/P/2MASS/color": [
"https://alaskybis.cds.unistra.fr/2MASS/Color",
"https://irsa.ipac.caltech.edu/data/hips/CDS/2MASS/Color",
"https://alasky.cds.unistra.fr/2MASS/Color",
],
"CDS/P/allWISE/color": [
"https://alaskybis.cds.unistra.fr/AllWISE/RGB-W4-W2-W1",
"https://irsa.ipac.caltech.edu/data/hips/CDS/AllWISE/RGB-W4-W2-W1",
"https://hips.china-vo.org/m/CDS_P_allWISE_color",
"http://skies.esac.esa.int/AllWISEColor",
"https://alasky.cds.unistra.fr/AllWISE/RGB-W4-W2-W1",
],
"CDS/P/Mellinger/color": [
"https://alaskybis.cds.unistra.fr/MellingerRGB",
"https://alasky.cds.unistra.fr/MellingerRGB",
],
"CDS/P/PanSTARRS/DR1/color-z-zg-g": [
"https://alaskybis.cds.unistra.fr/Pan-STARRS/DR1/color-z-zg-g",
"https://alasky.cds.unistra.fr/Pan-STARRS/DR1/color-z-zg-g",
],
"CDS/P/SDSS9/color": [
"https://alaskybis.cds.unistra.fr/SDSS/DR9/color",
"https://irsa.ipac.caltech.edu/data/hips/CDS/SDSS/DR9/color",
"http://skies.esac.esa.int/SDSS9Color",
"https://alasky.cds.unistra.fr/SDSS/DR9/color",
],
"CDS/P/DESI-Legacy-Surveys/DR10/color": [
"https://alaskybis.cds.unistra.fr/DESI-legacy-surveys/DR10/CDS_P_DESI-Legacy-Surveys_DR10_color",
"https://alasky.cds.unistra.fr/DESI-legacy-surveys/DR10/CDS_P_DESI-Legacy-Surveys_DR10_color",
],
"CDS/P/GALEXGR6/AIS/color": [
"https://alaskybis.cds.unistra.fr/GALEX/GR6-03-2014/AIS-Color",
"https://irsa.ipac.caltech.edu/data/hips/CDS/GALEX/GR6-03-2014/AIS-Color",
"https://hips.china-vo.org/m/CDS_P_GALEXGR6_AIS_color",
"https://alasky.cds.unistra.fr/GALEX/GR6-03-2014/AIS-Color",
],
"CDS/P/SPITZER/color": [
"https://alaskybis.cds.unistra.fr/Spitzer/SpitzerI1I2I4color",
"https://casda.csiro.au/hips/SpitzerI1I2I4color",
"https://alasky.cds.unistra.fr/Spitzer/SpitzerI1I2I4color",
],
}
_resolved = {}
_resolved_lock = threading.Lock()
_mirror_fail = {}
_CLIENT_GONE = (BrokenPipeError, ConnectionResetError, ConnectionAbortedError)
_tls = threading.local()
_stats_lock = threading.Lock()
_stats = {"cache_hits": 0, "cache_bad": 0, "upstream_ok": 0,
"upstream_404": 0, "upstream_fail": 0}
_mirror_stats = {}
_fail_logged = 0
_STALE = (
http.client.RemoteDisconnected, http.client.CannotSendRequest,
http.client.ResponseNotReady, ConnectionResetError, BrokenPipeError,
)
def _http_get(url, timeout, _redirects=3):
"""GET with a per-thread keep-alive connection, so a burst of sky tiles does not
pay a new TCP and TLS handshake every time (that was the slow part).
Reads are chunked with an overall deadline: the socket timeout only bounds
each individual recv, so a mirror that drips a few KB at a time could
otherwise keep a "6 second" fetch alive for minutes."""
u = urllib.parse.urlsplit(url)
conns = getattr(_tls, "conns", None)
if conns is None:
conns = _tls.conns = {}
key = (u.scheme, u.netloc, timeout)
target = (u.path or "/") + ("?" + u.query if u.query else "")
deadline = time.monotonic() + max(30.0, timeout * 4)
for attempt in (0, 1):
conn = conns.get(key)
if conn is None:
cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection
conn = conns[key] = cls(u.netloc, timeout=timeout)
try:
conn.request("GET", target, headers={"User-Agent": USER_AGENT, "Accept-Encoding": "identity"})
resp = conn.getresponse()
body = b""
while True:
chunk = resp.read(65536)
if not chunk:
break
body += chunk
if time.monotonic() > deadline:
raise TimeoutError("mirror too slow, overall deadline hit")
break
except _STALE:
conn.close()
conns.pop(key, None)
if attempt == 1:
raise
except Exception:
conn.close()
conns.pop(key, None)
raise
if resp.status in (301, 302, 303, 307, 308) and _redirects > 0 and resp.getheader("Location"):
return _http_get(urllib.parse.urljoin(url, resp.getheader("Location")), timeout, _redirects - 1)
if resp.status != 200:
raise urllib.error.HTTPError(url, resp.status, resp.reason, resp.msg, None)
return body
def _count(name):
with _stats_lock:
_stats[name] += 1
def _mirror_note(base, ok, ms=0.0):
with _stats_lock:
st = _mirror_stats.setdefault(base, {"ok": 0, "fail": 0, "ms": 0.0})
if ok:
st["ok"] += 1
st["ms"] += ms
else:
st["fail"] += 1
def _note_fail(base):
t, c = _mirror_fail.get(base, (0.0, 0))
_mirror_fail[base] = (time.time(), c + 1)
def _note_ok(base):
_mirror_fail.pop(base, None)
def content_plausible(rel, data):
"""Magic-byte check so garbage never enters (or stays in) the cache.
An error page, a truncated download or an empty file cached by an older
version of this server would otherwise be served forever as a 'tile'."""
if not data:
return False
name = rel.rsplit("/", 1)[-1].lower()
if name == "properties":
head = data[:65536].decode("utf-8", "replace").lower()
return "hips_" in head and "<html" not in head
if name.endswith((".jpg", ".jpeg")):
return data[:3] == b"\xff\xd8\xff"
if name.endswith(".png"):
return data[:8] == b"\x89PNG\r\n\x1a\n"
if name.endswith(".fits"):
return data[:6] == b"SIMPLE"
return True
def _load_resolved():
"""Read hips_cache/_resolved.json, but only trust entries that really look
like {'hips id': ['https://...', ...]}. Anything else (an older format,
a string instead of a list, a truncated file) is dropped instead of being
used, because a corrupted entry pins every request to broken mirrors."""
try:
with open(os.path.join(HIPS_CACHE, "_resolved.json"), "r", encoding="utf-8") as f:
data = json.load(f)
except (OSError, ValueError):
data = None
if isinstance(data, dict):
for hips_id, mirrors in data.items():
if isinstance(mirrors, str):
mirrors = [mirrors]
if (isinstance(hips_id, str) and isinstance(mirrors, list)
and mirrors and all(isinstance(u, str) and u.startswith("http")
for u in mirrors)):
_resolved[hips_id] = [u.rstrip("/") for u in mirrors]
for hips_id, bases in FALLBACK_BASES.items():
merged = list(_resolved.get(hips_id, []))
for u in bases:
if u not in merged:
merged.append(u)
_resolved[hips_id] = merged
def _save_resolved():
try:
os.makedirs(HIPS_CACHE, exist_ok=True)
with open(os.path.join(HIPS_CACHE, "_resolved.json"), "w", encoding="utf-8") as f:
json.dump(_resolved, f, indent=2)
except OSError:
pass
def resolve_bases(hips_id):
"""Mirror base URLs for a HiPS id: the verified list first, then anything
extra the CDS registry reports. Cached in _resolved.json."""
with _resolved_lock:
if _resolved.get(hips_id):
return list(_resolved[hips_id])
registry = []
for host in MOC_HOSTS:
try:
url = host + "?" + urllib.parse.urlencode({"id": hips_id, "get": "record", "fmt": "ascii"})
text = _http_get(url, 8).decode("utf-8", "replace")
for m in re.finditer(r"^\s*hips_service_url(?:_\d+)?\s*=\s*(\S+)\s*$", text, re.M):
u = m.group(1).rstrip("/")
if u not in registry:
registry.append(u)
if registry:
break
except Exception:
continue
bases = list(FALLBACK_BASES.get(hips_id, []))
for u in registry:
if u not in bases:
bases.append(u)
if bases:
with _resolved_lock:
_resolved[hips_id] = bases
_save_resolved()
return bases
def _ordered(bases):
"""Mirrors that have actually delivered a file recently go first (fastest
first); a mirror that failed moments ago, or failed 3+ times in a row,
goes last. Dead primaries cost one timeout once, not one per tile."""
now = time.time()
def score(b):
t, c = _mirror_fail.get(b, (0.0, 0))
since = now - t
shaky = since < 120 or (c >= 3 and since < 1800)
st = _mirror_stats.get(b)
avg = (st["ms"] / st["ok"]) if st and st["ok"] else float("inf")
return (shaky, avg, bases.index(b))
return sorted(bases, key=score)
def fetch_upstream(hips_id, rel, timeout=8, rounds=2):
global _fail_logged
bases = resolve_bases(hips_id)
if not bases:
raise IOError("no mirrors known for " + hips_id)
saw_404 = False
t_start = time.monotonic()
budget = max(30.0, timeout * 4)
for _ in range(rounds):
saw_error = False
for base in _ordered(bases):
if time.monotonic() - t_start > budget:
break
t0 = time.time()
try:
data = _http_get(f"{base}/{rel}", timeout)
if not content_plausible(rel, data):
raise IOError("implausible content from mirror")
_mirror_note(base, True, (time.time() - t0) * 1000)
_note_ok(base)
_count("upstream_ok")
return data
except urllib.error.HTTPError as e:
if e.code == 404:
saw_404 = True
else:
saw_error = True
_note_fail(base)
_mirror_note(base, False)
except Exception:
saw_error = True
_note_fail(base)
_mirror_note(base, False)
if not saw_error:
break
if saw_404:
_count("upstream_404")
raise FileNotFoundError(rel)
_count("upstream_fail")
with _resolved_lock:
if _resolved.pop(hips_id, None) is not None:
_save_resolved()
_fail_logged += 1
if _fail_logged <= 20 or _fail_logged % 50 == 0:
print(f"[sky] no mirror delivered {hips_id} {rel} (failure #{_fail_logged}). See /api/sky/stats")
raise IOError("all mirrors failed for " + rel)
_SAFE_REL = re.compile(r"^[A-Za-z0-9_\-./]+$")
def get_hips_file(key, rel, **kw):
"""Bytes of one HiPS file: from the local cache, else fetched and cached.
Files already in the cache are content-checked, so junk cached by an
earlier run is thrown out instead of being served forever."""
if key not in SKY_SURVEYS or not _SAFE_REL.match(rel) or ".." in rel:
raise FileNotFoundError(rel)
path = os.path.join(HIPS_CACHE, key, rel)
if os.path.isfile(path):
with open(path, "rb") as f:
data = f.read()
if content_plausible(rel, data):
_count("cache_hits")
return data
_count("cache_bad")
try:
os.remove(path)
except OSError:
pass
data = fetch_upstream(SKY_SURVEYS[key][1], rel, **kw)
os.makedirs(os.path.dirname(path), exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path))
with os.fdopen(fd, "wb") as f:
f.write(data)
os.replace(tmp, path)
return data
def check_survey(key):
"""Can this survey actually deliver tiles from here? Warms the cache too."""
try:
props = get_hips_file(key, "properties", timeout=6, rounds=2).decode("utf-8", "replace")
m = re.search(r"^hips_tile_format\s*=\s*(.+)$", props, re.M)
fmts = m.group(1).lower().split() if m else ["jpeg"]
ext = "jpg" if "jpeg" in fmts else "png" if "png" in fmts else "fits"
probes = [f"Norder0/Dir0/Npix{i}.{ext}" for i in range(12)] + [f"Norder3/Allsky.{ext}"]
hard_failures = 0
for rel in probes:
try:
get_hips_file(key, rel, timeout=6, rounds=2)
return {"ok": True, "format": ext}
except FileNotFoundError:
continue
except IOError as e:
hard_failures += 1
if hard_failures >= 2:
return {"ok": False, "error": f"mirrors unreachable: {e}"}
continue
return {"ok": False, "error": "no base tiles found"}
except FileNotFoundError:
return {"ok": False, "error": "not found"}
except Exception as e:
return {"ok": False, "error": str(e)}
def purge_cache(key=None):
"""Delete cached sky tiles - one survey, or everything including the
remembered mirror list. Returns (files, bytes) removed."""
n = b = 0
targets = [os.path.join(HIPS_CACHE, key)] if key else [HIPS_CACHE]
for t in targets:
if not os.path.isdir(t):
continue
for root, _dirs, files in os.walk(t):
for f in files:
try:
b += os.path.getsize(os.path.join(root, f))
n += 1
except OSError:
pass
for t in targets:
shutil.rmtree(t, ignore_errors=True)
with _resolved_lock:
if key is None:
_resolved.clear()
elif key in SKY_SURVEYS:
_resolved.pop(SKY_SURVEYS[key][1], None)
_save_resolved()
_mirror_fail.clear()
with _stats_lock:
_mirror_stats.clear()
os.makedirs(HIPS_CACHE, exist_ok=True)
return n, b
def hips_content_type(rel):
if rel.endswith((".jpg", ".jpeg")):
return "image/jpeg"
if rel.endswith(".png"):
return "image/png"
if rel == "properties":
return "text/plain; charset=utf-8"
return "application/octet-stream"
def local_properties(raw):
"""Drop mirror hints so Aladin keeps asking this server for every tile
(and never tries to fetch the MOC straight from a remote host)."""
lines = raw.decode("utf-8", "replace").splitlines()
kept = [ln for ln in lines if not re.match(r"^\s*#?\s*(hips_service_url|moc_access_url)", ln)]
return ("\n".join(kept) + "\n").encode("utf-8")
_load_resolved()
def list_bands():
bands = {}
if not os.path.isdir(DATA_DIR):
return bands
for band_name in sorted(os.listdir(DATA_DIR)):
band_path = os.path.join(DATA_DIR, band_name)
if not os.path.isdir(band_path):
continue
files = sorted(f for f in os.listdir(band_path) if f.endswith(".fits"))
if files:
bands[band_name] = files
return bands
_FOOTPRINTS_SIA_CACHE = {"data": None, "mtime": 0.0}
_FOOTPRINTS_SIA_LOCK = threading.Lock()
def search_local_sia(ra: float, dec: float, radius: float, maxrec: int = 500):
"""Cone search against local footprints.json returning standardized SIA2 rows."""
fp_path = os.path.join(BASE_DIR, "footprints.json")
if not os.path.isfile(fp_path):
return []
try:
mtime = os.path.getmtime(fp_path)
except OSError:
mtime = 0.0
with _FOOTPRINTS_SIA_LOCK:
if _FOOTPRINTS_SIA_CACHE["data"] is not None and _FOOTPRINTS_SIA_CACHE["mtime"] == mtime:
data = _FOOTPRINTS_SIA_CACHE["data"]
else:
try:
with open(fp_path, "r", encoding="utf-8") as f:
data = json.load(f)
_FOOTPRINTS_SIA_CACHE["data"] = data
_FOOTPRINTS_SIA_CACHE["mtime"] = mtime
except Exception as e:
print(f"[sia] Error loading footprints.json: {e}")
return []
band_wave = {
"SPHEREx-D1": (0.75e-6, 1.11e-6),
"SPHEREx-D2": (1.11e-6, 1.64e-6),
"SPHEREx-D3": (1.64e-6, 2.42e-6),
"SPHEREx-D4": (2.42e-6, 3.42e-6),
"SPHEREx-D5": (3.42e-6, 4.42e-6),
"SPHEREx-D6": (4.42e-6, 5.00e-6),
}
results = []
threshold = float(radius) + 2.5
r_ra = math.radians(ra)
r_dec = math.radians(dec)
sin_dec = math.sin(r_dec)
cos_dec = math.cos(r_dec)
for band_name, items in data.items():
w_min, w_max = band_wave.get(band_name, (0.75e-6, 5.00e-6))
for item in items:
f_ra = item.get("ra")
f_dec = item.get("dec")
if f_ra is None or f_dec is None:
continue
f_r_ra = math.radians(float(f_ra))
f_r_dec = math.radians(float(f_dec))
dr = f_r_ra - r_ra
cos_d = sin_dec * math.sin(f_r_dec) + cos_dec * math.cos(f_r_dec) * math.cos(dr)
dist_deg = math.degrees(math.acos(max(-1.0, min(1.0, cos_d))))
if dist_deg <= threshold:
fname = item.get("file") or os.path.basename(item.get("path", ""))
polygon = item.get("polygon") or []
if polygon:
s_region = "POLYGON ICRS " + " ".join(f"{pt[0]} {pt[1]}" for pt in polygon)
else:
s_region = f"CIRCLE ICRS {f_ra} {f_dec} 1.5"
access_url = f"/files/{band_name}/{fname}"
results.append((dist_deg, {
"obs_id": fname,
"s_ra": str(round(float(f_ra), 6)),
"s_dec": str(round(float(f_dec), 6)),
"s_region": s_region,
"em_min": str(w_min),
"em_max": str(w_max),
"energy_bandpassname": band_name,
"t_min": "2025-05-01",
"access_url": access_url,
"access_estsize": "16657920",
}))
results.sort(key=lambda x: x[0])
return [row for _, row in results[:maxrec]]
def query_sia(collection, ra, dec, radius, maxrec=500):
"""Query local SPHEREx dataset and remote IRSA SIA.
Returns (rows, irsa_error).
If remote IRSA fails or is unavailable, local rows are returned with an error note.
"""
local_rows = search_local_sia(ra, dec, radius, maxrec)
irsa_err = None
remote_rows = []
try:
params = {
"COLLECTION": collection or "spherex_qr2",
"POS": f"CIRCLE {ra} {dec} {radius}",
"RESPONSEFORMAT": "CSV",
"MAXREC": str(maxrec),
}
url = SIA_URL + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "text/csv,text/plain,*/*",
}
)
with urllib.request.urlopen(req, timeout=5.0) as resp:
text = resp.read().decode("utf-8", errors="replace")
reader = csv.DictReader(io.StringIO(text))
if reader.fieldnames and "access_url" in reader.fieldnames:
for row in reader:
if not row.get("access_url"):
continue
filtered = {col: row.get(col, "") for col in SIA_COLUMNS if col in row}
remote_rows.append(filtered)
except urllib.error.HTTPError as e:
irsa_err = f"IRSA HTTP {e.code} ({e.reason})"
print(f"[sia] IRSA SIA returned HTTP {e.code}: {e.reason}")
except urllib.error.URLError as e:
irsa_err = f"IRSA connection failed ({e.reason})"
print(f"[sia] IRSA connection failed: {e.reason}")
except Exception as e:
irsa_err = f"IRSA query error ({e})"
print(f"[sia] IRSA query error: {e}")
combined = list(local_rows)
seen_urls = {r.get("access_url") for r in combined}
seen_ids = {r.get("obs_id") for r in combined if r.get("obs_id")}
for r in remote_rows:
u = r.get("access_url")
oid = r.get("obs_id")
if u not in seen_urls and (not oid or oid not in seen_ids):
combined.append(r)
seen_urls.add(u)
if oid:
seen_ids.add(oid)
return combined[:maxrec], irsa_err
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
timeout = 60
wbufsize = 64 * 1024
disable_nagle_algorithm = True
def log_message(self, fmt, *args):
if getattr(self, "path", "").startswith("/hips/") or fmt.startswith("Request timed out"):
return
print(f"[{self.address_string()}] {fmt % args}")
def send_json(self, obj, status=200):
body = json.dumps(obj).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
if path == "/" or path == "/index.html":
self.serve_file("index.html", "text/html")
return
if path == "/api/bands":
self.send_json(list_bands())
return
if path == "/api/sia":
q = urllib.parse.parse_qs(parsed.query)
try:
coll_param = q.get("collection", ["spherex_qr2"])[0].strip()
collection = coll_param if (coll_param in ALLOWED_COLLECTIONS) else "spherex_qr2"
ra = float(q["ra"][0])
dec = float(q["dec"][0])
radius = float(q.get("radius", ["0.01"])[0])
except (KeyError, ValueError):
self.send_json({"error": "ra, dec and radius must be numbers"}, 400)
return
if not (0 < radius <= 5):
self.send_json({"error": "radius must be between 0 and 5 degrees"}, 400)
return
rows, irsa_err = query_sia(collection, ra, dec, radius)
resp_payload = {
"count": len(rows),
"rows": rows,
"irsa_available": (irsa_err is None),
}
if irsa_err:
resp_payload["irsa_notice"] = f"Remote IRSA archive is currently unavailable ({irsa_err}). Showing matching observations from local SPHEREx dataset."
self.send_json(resp_payload)
return
if path == "/api/remote":
q = urllib.parse.parse_qs(parsed.query)
target = q.get("url", [""])[0].strip()
if not target:
self.send_error(400, "Missing url parameter")
return
clean_target = target.split("?")[0]
if clean_target.startswith("/files/") or clean_target.startswith("files/") or (not clean_target.startswith("http://") and not clean_target.startswith("https://")):
rel = clean_target.lstrip("/")
if rel.startswith("files/"):
rel = rel[len("files/"):]
rel = urllib.parse.unquote(rel)
full_path = os.path.realpath(os.path.join(DATA_DIR, rel))
data_dir_abs = os.path.realpath(DATA_DIR)
if not os.path.isfile(full_path) or os.path.commonpath((data_dir_abs, full_path)) != data_dir_abs:
self.send_error(404, "Local file not found")
return
try:
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(os.path.getsize(full_path)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
with open(full_path, "rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
self.wfile.write(chunk)
except _CLIENT_GONE:
self.close_connection = True
return
u = urllib.parse.urlparse(target)
if u.scheme != "https" or u.hostname != IRSA_HOST:
self.send_error(403, "Only https://" + IRSA_HOST + " URLs are allowed")
return
try:
req = urllib.request.Request(target, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=180) as resp:
data = resp.read()
except urllib.error.HTTPError as e:
self.send_error(502, f"IRSA returned HTTP {e.code}")
return
except Exception as e:
self.send_error(502, f"Fetch failed: {e}")
return
try:
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(data)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(data)
except _CLIENT_GONE:
self.close_connection = True
return
if path == "/api/sky/stats":
with _stats_lock:
mirrors = {
b: {"ok": v["ok"], "fail": v["fail"],
"avg_ms": round(v["ms"] / v["ok"]) if v["ok"] else None}
for b, v in _mirror_stats.items()
}
self.send_json({"totals": dict(_stats), "mirrors": mirrors})
return
if path == "/api/sky":
self.send_json([{"key": k, "label": v[0]} for k, v in SKY_SURVEYS.items()])
return
if path == "/api/sky/check":
key = urllib.parse.parse_qs(parsed.query).get("key", [""])[0]
if key not in SKY_SURVEYS:
self.send_json({"ok": False, "error": "unknown survey"}, 404)
return
self.send_json(check_survey(key))
return
if path == "/api/sky/purge":
q = urllib.parse.parse_qs(parsed.query)
key = q.get("key", [None])[0]
if key is not None and key not in SKY_SURVEYS:
self.send_json({"error": "unknown survey"}, 404)
return
n, b = purge_cache(key)
self.send_json({"purged_files": n, "purged_bytes": b})
return
if path == "/mocserver":
q = urllib.parse.parse_qs(parsed.query)
target = "https://alaskybis.cds.unistra.fr/MocServer/query?" + \
urllib.parse.urlencode(q, doseq=True)
try:
req = urllib.request.Request(target, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=30) as resp:
data = resp.read()
content_type = resp.headers.get("Content-Type", "text/plain; charset=utf-8")
except Exception as e:
self.send_error(502, f"MocServer fetch failed: {e}")
return
try:
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Cache-Control", "public, max-age=300")
self.end_headers()
self.wfile.write(data)
except _CLIENT_GONE:
self.close_connection = True
return
if path.startswith("/hips/"):
key, _, rel = path[len("/hips/"):].partition("/")
try:
data = get_hips_file(key, rel)
except FileNotFoundError:
self.send_error(404, "Not found")
return
except Exception:
self.send_error(502, "Upstream unavailable")
return
if rel == "properties":
data = local_properties(data)
try:
self.send_response(200)
self.send_header("Content-Type", hips_content_type(rel))
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "public, max-age=86400")
self.end_headers()
self.wfile.write(data)
except _CLIENT_GONE:
self.close_connection = True
return
if path == "/api/mosaics":
manifest = os.path.join(MOSAIC_DIR, "manifest.json")
if os.path.isfile(manifest):
with open(manifest, "r", encoding="utf-8") as f:
self.send_json(json.load(f))
else:
self.send_json({"bands": {}})
return
if path.startswith("/mosaic/"):
name = urllib.parse.unquote(path[len("/mosaic/"):])
mosaic_abs = os.path.abspath(MOSAIC_DIR)
full_path = os.path.abspath(os.path.join(MOSAIC_DIR, name))
if not full_path.startswith(mosaic_abs + os.sep) or not os.path.isfile(full_path):
self.send_error(404, "Mosaic not found")
return
with open(full_path, "rb") as f:
body = f.read()
try:
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-cache")
self.end_headers()
self.wfile.write(body)
except _CLIENT_GONE:
self.close_connection = True
return
if path.startswith("/files/"):
rel = urllib.parse.unquote(path[len("/files/"):])
full_path = os.path.join(DATA_DIR, rel)
full_path = os.path.abspath(full_path)
data_dir_abs = os.path.abspath(DATA_DIR)
if not full_path.startswith(data_dir_abs) or not os.path.isfile(full_path):
self.send_error(404, "File not found")
return
try:
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(os.path.getsize(full_path)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
with open(full_path, "rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
self.wfile.write(chunk)
except _CLIENT_GONE:
self.close_connection = True
return
if path.startswith("/api/zip/"):
band_name = urllib.parse.unquote(path[len("/api/zip/"):])
band_path = os.path.join(DATA_DIR, band_name)
if not os.path.isdir(band_path):
self.send_error(404, "Band not found")
return
self.send_response(200)
self.send_header("Content-Type", "application/zip")
self.send_header("Content-Disposition", f'attachment; filename="spherex_{band_name}.zip"')
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Connection", "close")
self.end_headers()
self.close_connection = True
try:
with zipfile.ZipFile(self.wfile, "w", zipfile.ZIP_STORED) as zf:
for fname in sorted(os.listdir(band_path)):
if not fname.endswith(".fits"):
continue
fpath = os.path.join(band_path, fname)
zf.write(fpath, arcname=fname)
except _CLIENT_GONE:
self.close_connection = True
return
self.send_error(404, "Not found")
def serve_file(self, filename, content_type):
if not os.path.exists(filename):
self.send_error(404, f"{filename} not found next to this script")
return
with open(filename, "rb") as f:
body = f.read()
try:
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except _CLIENT_GONE:
self.close_connection = True
class Server(socketserver.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
def handle_error(self, request, client_address):
exc = sys.exc_info()[1]
if isinstance(exc, (BrokenPipeError, ConnectionResetError,
ConnectionAbortedError, TimeoutError)):
return
super().handle_error(request, client_address)
if __name__ == "__main__":
bands = list_bands()
total = sum(len(v) for v in bands.values())
print(f"Found {len(bands)} band folder(s), {total} .fits file(s) total under '{DATA_DIR}/'")
n_cached = 0
if os.path.isdir(HIPS_CACHE):
for _root, _dirs, files in os.walk(HIPS_CACHE):
n_cached += len(files)
print(f"Sky tile cache: {n_cached} file(s) under '{HIPS_CACHE}/' "
f"(clear it any time with the page's 'Reset sky cache' button)")
print(f"Starting server at http://localhost:{PORT}")
print("Open that URL in your browser. Press Ctrl+C to stop.")
try:
with Server(("", PORT), Handler) as httpd:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nStopped.")
|