Skip to content

Commit 79a108d

Browse files
committed
fixed nasa_ads api logic alma's bugs and translate scripts
1 parent 516d171 commit 79a108d

20 files changed

Lines changed: 994 additions & 779 deletions

File tree

astroquery_cli/__init__.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,21 @@
11
# astroquery_cli/__init__.py
22
from importlib import metadata
3+
import logging
4+
import sys
5+
6+
# Suppress astroquery log messages globally
7+
logging.getLogger('astroquery').setLevel(logging.CRITICAL)
8+
9+
# Monkey patch logging.Logger._set_defaults to prevent AttributeError from astroquery
10+
# This needs to happen before astroquery is imported.
11+
# We replace _set_defaults with a no-op if it exists.
12+
if hasattr(logging.Logger, '_set_defaults'):
13+
original_set_defaults = logging.Logger._set_defaults
14+
def no_op_set_defaults(self):
15+
pass
16+
logging.Logger._set_defaults = no_op_set_defaults
17+
318
try:
419
__version__ = metadata.version("astroquery-cli")
520
except metadata.PackageNotFoundError:
6-
__version__ = "None"
21+
__version__ = "None"

astroquery_cli/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def load_config():
2929
# Create a default config file for the user
3030
with open(CONFIG_FILE_PATH, 'w') as f:
3131
f.write("[Environment]\n")
32-
f.write("# ADS_DEV_KEY = your_ads_dev_key\n")
32+
f.write("ADS_DEV_KEY = \n") # Add this line
3333
f.write("# AQC_DEBUG = true\n")
3434
f.write("# AQC_VERBOSE = true\n")
3535
f.write("# AQC_LANG = en\n")
1.9 KB
Binary file not shown.
1.37 KB
Binary file not shown.
1015 Bytes
Binary file not shown.

astroquery_cli/main.py

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
from rich.console import Console # Import Console
1212
from rich.text import Text # Import Text
1313
import re # Import re
14+
import logging # Import logging
15+
16+
# Suppress astroquery log messages globally (moved to __init__.py for earlier execution)
17+
# Monkey patch for astroquery.logger._init_log (moved to __init__.py for earlier execution)
1418

1519
from astroquery_cli import config # Import config first
1620
# Load configuration from ~/.aqc/config.ini
@@ -24,7 +28,6 @@
2428
from astroquery_cli.debug import debug_manager
2529

2630

27-
2831
def save_default_lang(lang):
2932
config.set_language(lang.strip())
3033

@@ -41,18 +44,19 @@ def load_default_lang():
4144
context_settings={"help_option_names": ["-h", "--help"]},
4245
)
4346

44-
_captured_stdout_during_import = ""
45-
4647
def setup_subcommands():
47-
global _captured_stdout_during_import # Declare global here
48-
f = StringIO()
49-
with redirect_stdout(f):
50-
from .modules import (
51-
simbad_cli, alma_cli, esasky_cli, gaia_cli, irsa_cli, irsa_dust_cli,
52-
jplhorizons_cli, jplsbdb_cli, mast_cli, nasa_ads_cli, ned_cli,
53-
splatalogue_cli, vizier_cli
54-
)
55-
_captured_stdout_during_import = f.getvalue()
48+
import logging
49+
# Suppress astroquery log messages during import
50+
logging.getLogger('astroquery').setLevel(logging.CRITICAL)
51+
52+
# Import all subcommands
53+
from .modules import (
54+
simbad_cli, alma_cli, esasky_cli, gaia_cli, irsa_cli, irsa_dust_cli,
55+
jplhorizons_cli, jplsbdb_cli, mast_cli, nasa_ads_cli, ned_cli,
56+
splatalogue_cli, vizier_cli
57+
)
58+
# Restore astroquery log level after import
59+
logging.getLogger('astroquery').setLevel(logging.NOTSET)
5660

5761
app.add_typer(simbad_cli.get_app(), name="simbad")
5862
app.add_typer(alma_cli.get_app(), name="alma")
@@ -106,7 +110,6 @@ def main_callback(
106110
help=i18n._("Enable verbose output.")
107111
)
108112
):
109-
global _captured_stdout_during_import
110113
_ = builtins._
111114
ctx.obj = ctx.obj or {}
112115

@@ -157,20 +160,6 @@ def main_callback(
157160
}
158161
debug_manager.print_translation_info(selected_lang, translation_info)
159162

160-
# Process captured stdout messages after translation is initialized
161-
if _captured_stdout_during_import:
162-
lines = _captured_stdout_during_import.splitlines()
163-
for line in lines:
164-
if "Gaia ESA Archive has been rolled back" in line:
165-
translated_message = _(
166-
"Please note that the Gaia ESA Archive has been rolled back to version 3.7. "
167-
"Please find the release notes at https://www.cosmos.esa.int/web/gaia-users/archive/release-notes"
168-
)
169-
print(translated_message)
170-
else:
171-
print(line)
172-
_captured_stdout_during_import = ""
173-
174163
# Try to inject our translations into Click's gettext domain
175164
try:
176165
import gettext
@@ -249,7 +238,6 @@ def custom_gettext(message):
249238
commands_match = re.search(r'╭─ Commands ─.*?(\n(?:│.*?\n)*)╰─.*─╯', full_help_text, re.DOTALL)
250239
if commands_match:
251240
commands_section = commands_match.group(0)
252-
# Remove the "Usage:" line if present in the full help text
253241
# This is a fallback in case Typer's internal help generation includes it
254242
filtered_commands_section = "\n".join([
255243
line for line in commands_section.splitlines() if "Usage:" not in line
@@ -261,11 +249,19 @@ def custom_gettext(message):
261249
raise typer.Exit()
262250

263251
def cli():
252+
from rich.console import Console # Import Console here
264253
try:
254+
# Check for debug flag early to configure debug_manager before module imports
255+
if "--debug" in sys.argv or "-d" in sys.argv:
256+
debug_manager.enable_debug()
257+
# Print a message indicating debug mode is enabled
258+
console = Console()
259+
console.print("[bold green]Debug mode enabled.[/bold green]")
260+
# Removed the "Debug mode disabled" message as per user request.
261+
265262
setup_subcommands()
266263
app()
267264
except KeyboardInterrupt:
268-
from rich.console import Console
269265
_ = i18n.get_translator()
270266
console = Console()
271267
console.print(f"[bold yellow]{_('User interrupted the query. Exiting safely.')}[bold yellow]")

astroquery_cli/modules/alma_cli.py

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from typing import Optional, List
33
from astropy.table import Table as AstropyTable
44
from astroquery.alma import Alma
5+
import logging # Import logging
56
from ..utils import (
67
console,
78
display_table,
@@ -16,6 +17,7 @@
1617
import re # Import re
1718
from io import StringIO # Import StringIO
1819
from contextlib import redirect_stdout # Import redirect_stdout
20+
import sys # Import sys
1921
from astroquery_cli.common_options import setup_debug_context # Import setup_debug_context
2022

2123
def get_app():
@@ -75,6 +77,9 @@ def alma_callback(
7577
console.print(full_help_text)
7678
raise typer.Exit()
7779

80+
# Suppress ALMA log messages during import
81+
logging.getLogger('astroquery.alma').setLevel(logging.WARNING)
82+
7883
Alma.ROW_LIMIT = 50
7984
Alma.TIMEOUT = 60
8085

@@ -94,17 +99,16 @@ def query_object(
9499
output_file: Optional[str] = common_output_options["output_file"],
95100
output_format: Optional[str] = common_output_options["output_format"],
96101
max_rows_display: int = typer.Option(20, help=builtins._("Maximum number of rows to display. Use -1 for all rows.")),
97-
show_all_columns: bool = typer.Option(False, "--show-all-cols", help=builtins._("Show all columns in the output table.")),
98-
test: bool = typer.Option(False, "--test", "-t", help=_("Enable test mode and print elapsed time."))
102+
show_all_columns: bool = typer.Option(False, "--show-all-cols", help=builtins._("Show all columns in the output table."))
99103
):
100-
import time
101-
start = time.perf_counter() if test else None
102-
103104
lang = ctx.obj.get("lang", "en") if ctx.obj else "en"
104105
_ = i18n.get_translator(lang)
105-
console.print(_("[cyan]Querying ALMA for object: '{object_name}'...[/cyan]").format(object_name=object_name))
106106
alma = Alma()
107107
try:
108+
# Debugging information
109+
console.print(f"DEBUG: query_object - object_name: {object_name}")
110+
111+
console.print(f"[cyan]{_('Querying ALMA for object: {object_name}').format(object_name=object_name)}[/cyan]")
108112
query_payload = {'source_name_alma': object_name}
109113
if payload:
110114
for item in payload:
@@ -131,11 +135,6 @@ def query_object(
131135
handle_astroquery_exception(ctx, e, _("ALMA object"))
132136
raise typer.Exit(code=1)
133137

134-
if test:
135-
elapsed = time.perf_counter() - start
136-
print(f"Elapsed: {elapsed:.3f} s")
137-
raise typer.Exit()
138-
139138
@app.command(name="region", help=builtins._("Query ALMA for observations in a sky region."))
140139
@global_keyboard_interrupt_handler
141140
def query_region(
@@ -147,16 +146,15 @@ def query_region(
147146
output_file: Optional[str] = common_output_options["output_file"],
148147
output_format: Optional[str] = common_output_options["output_format"],
149148
max_rows_display: int = typer.Option(20, help=builtins._("Maximum number of rows to display. Use -1 for all rows.")),
150-
show_all_columns: bool = typer.Option(False, "--show-all-cols", help=builtins._("Show all columns in the output table.")),
151-
test: bool = typer.Option(False, "--test", "-t", help=builtins._("Enable test mode and print elapsed time."))
149+
show_all_columns: bool = typer.Option(False, "--show-all-cols", help=builtins._("Show all columns in the output table."))
152150
):
153-
import time
154-
start = time.perf_counter() if test else None
155-
156151
lang = ctx.obj.get("lang", "en") if ctx.obj else "en"
157152
_ = i18n.get_translator(lang)
158-
console.print(_("[cyan]Querying ALMA for region: '{coordinates}' with radius '{radius}'...[/cyan]").format(coordinates=coordinates, radius=radius))
159153
try:
154+
# Debugging information
155+
console.print(f"DEBUG: query_region - coordinates: {coordinates}, radius: {radius}")
156+
157+
console.print(f"[cyan]{_('Querying ALMA for region: {coordinates} with radius {radius}').format(coordinates=coordinates, radius=radius)}[/cyan]")
160158
coord = parse_coordinates(ctx, coordinates)
161159
rad = parse_angle_str_to_quantity(ctx, radius)
162160
alma = Alma()
@@ -178,9 +176,5 @@ def query_region(
178176
handle_astroquery_exception(ctx, e, _("ALMA region"))
179177
raise typer.Exit(code=1)
180178

181-
if test:
182-
elapsed = time.perf_counter() - start
183-
print(f"Elapsed: {elapsed:.3f} s")
184-
raise typer.Exit()
185179

186180
return app

astroquery_cli/modules/gaia_cli.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77

88
console = Console()
99

10+
# Suppress Gaia server messages during import
11+
gaia_conf.show_server_messages = False
12+
1013
from ..utils import display_table, handle_astroquery_exception, parse_coordinates, parse_angle_str_to_quantity, common_output_options, save_table_to_file
1114
from ..utils import global_keyboard_interrupt_handler
1215
from ..i18n import get_translator
@@ -43,6 +46,9 @@ def gaia_callback(
4346
)
4447
):
4548
setup_debug_context(ctx, debug, verbose)
49+
# Re-enable Gaia server messages when the gaia app is actually invoked
50+
gaia_conf.show_server_messages = True
51+
console.print(builtins._("[yellow]Please note that the Gaia ESA Archive has been rolled back to version 3.7. Please find the release notes at https://www.cosmos.esa.int/web/gaia-users/archive/release-notes[/yellow]"))
4652

4753
# Custom help display logic
4854
if ctx.invoked_subcommand is None and \
@@ -72,8 +78,6 @@ def gaia_callback(
7278
console.print(full_help_text)
7379
raise typer.Exit()
7480

75-
gaia_conf.show_server_messages = True
76-
7781
GAIA_TABLES = {
7882
"main_source": "gaiadr3.gaia_source",
7983
"dr2_source": "gaiadr2.gaia_source",

0 commit comments

Comments
 (0)