-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
53 lines (43 loc) · 1.67 KB
/
main.py
File metadata and controls
53 lines (43 loc) · 1.67 KB
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
# main.py
import argparse
import json
import sys
from typing import Any
from analyzer import analyze_sentiment, batch_analyze, load_csv, save_results
def build_parser() -> argparse.ArgumentParser:
"""Return the configured argument parser."""
parser = argparse.ArgumentParser(
description="Classify text sentiment using the Anthropic API."
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--text", type=str, help="Single text string to analyze.")
group.add_argument("--file", type=str, help="Path to input CSV file for batch analysis.")
parser.add_argument(
"--output",
type=str,
help="Output CSV path (required when using --file).",
)
return parser
def _print_result(result: dict[str, Any]) -> None:
print(json.dumps(result, indent=2))
def main(argv: list[str] | None = None) -> None:
"""Entry point for the sentiment analyzer CLI."""
parser = build_parser()
args = parser.parse_args(argv)
try:
if args.text is not None:
result = analyze_sentiment(args.text)
_print_result(result)
elif args.file is not None:
if not args.output:
# parser.error raises SystemExit (BaseException), not caught below
parser.error("--output is required when using --file")
texts = load_csv(args.file)
results = batch_analyze(texts)
save_results(results, args.output)
print(f"Saved {len(results)} results to {args.output}")
except Exception as exc: # noqa: BLE001
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()