|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +PopulPy - Command Line Interface |
| 4 | +Use this module to access PopulPy features from the command line |
| 5 | +""" |
1 | 6 | import argparse
|
2 | 7 | import logging
|
3 | 8 | import os
|
4 | 9 | import csv
|
| 10 | +import sys |
| 11 | +from typing import Dict, List, Any, Optional |
| 12 | + |
| 13 | +# Add the project root to the Python path |
| 14 | +sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) |
| 15 | + |
5 | 16 | from dotenv import load_dotenv
|
6 |
| -from pytrends.request import TrendReq |
7 | 17 |
|
8 |
| -from src.services.google_service import ( |
9 |
| - get_top_results_for_related_searches, |
10 |
| - create_wordcloud |
| 18 | +# Configure logging |
| 19 | +logging.basicConfig( |
| 20 | + level=logging.INFO, |
| 21 | + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
11 | 22 | )
|
12 |
| - |
13 | 23 | logger = logging.getLogger(__name__)
|
14 | 24 |
|
| 25 | +try: |
| 26 | + from pytrends.request import TrendReq |
| 27 | + from src.services.google_service import ( |
| 28 | + get_top_results_for_related_searches, |
| 29 | + create_wordcloud, |
| 30 | + get_google_search_trends, |
| 31 | + get_google_related_searches |
| 32 | + ) |
| 33 | +except ImportError as e: |
| 34 | + logger.error(f"Required package not found: {e}") |
| 35 | + logger.error("Please install required packages using: pip install -r requirements.txt") |
| 36 | + sys.exit(1) |
| 37 | + |
15 | 38 | def parse_args():
|
16 |
| - parser = argparse.ArgumentParser() |
17 |
| - parser.add_argument("-q", "--query", help="Query to search on Google", required=True) |
18 |
| - parser.add_argument("-c", "--country", help="Country to search in", default="es") |
19 |
| - parser.add_argument("-w", "--wordcloud", help="Path to save the wordcloud image") |
| 39 | + """Parse command line arguments.""" |
| 40 | + parser = argparse.ArgumentParser( |
| 41 | + description="PopulPy - Analyze search trends across multiple providers" |
| 42 | + ) |
| 43 | + parser.add_argument("-q", "--query", |
| 44 | + help="Query to search on Google", |
| 45 | + required=True) |
| 46 | + parser.add_argument("-c", "--country", |
| 47 | + help="Country code to search in (e.g., ES, US)", |
| 48 | + default="ES") |
| 49 | + parser.add_argument("-t", "--timeframe", |
| 50 | + help="Timeframe for trend analysis (e.g., 'today 5-y')", |
| 51 | + default="today 5-y") |
| 52 | + parser.add_argument("-w", "--wordcloud", |
| 53 | + help="Path to save the wordcloud image", |
| 54 | + default="wordcloud.png") |
| 55 | + parser.add_argument("-o", "--output", |
| 56 | + help="Output file path for related searches data", |
| 57 | + default=None) |
| 58 | + parser.add_argument("--no-wordcloud", |
| 59 | + help="Skip generating wordcloud", |
| 60 | + action="store_true") |
20 | 61 | return parser.parse_args()
|
21 | 62 |
|
22 |
| -def save_related_searches_to_csv(related_searches, filename): |
23 |
| - with open(filename, mode='w', newline='', encoding='utf-8') as csv_file: |
24 |
| - fieldnames = ['Related Search', 'Result 1', 'Result 2', 'Result 3', 'Result 4', 'Result 5'] |
25 |
| - writer = csv.DictWriter(csv_file, fieldnames=fieldnames) |
26 |
| - writer.writeheader() |
27 |
| - for search, results in related_searches.items(): |
28 |
| - row = {'Related Search': search} |
29 |
| - for i, result in enumerate(results, 1): |
30 |
| - row[f"Result {i}"] = result |
31 |
| - writer.writerow(row) |
32 |
| - |
33 |
| -if __name__ == "__main__": |
| 63 | +def save_related_searches_to_csv(related_searches: Dict[str, List[str]], |
| 64 | + filename: str) -> None: |
| 65 | + """ |
| 66 | + Save related searches and their results to a CSV file. |
| 67 | + |
| 68 | + Args: |
| 69 | + related_searches: Dictionary with related searches and their results |
| 70 | + filename: Path to save the CSV file |
| 71 | + """ |
| 72 | + try: |
| 73 | + with open(filename, mode='w', newline='', encoding='utf-8') as csv_file: |
| 74 | + fieldnames = ['Related Search', 'Result 1', 'Result 2', 'Result 3', 'Result 4', 'Result 5'] |
| 75 | + writer = csv.DictWriter(csv_file, fieldnames=fieldnames) |
| 76 | + writer.writeheader() |
| 77 | + |
| 78 | + for search, results in related_searches.items(): |
| 79 | + row = {'Related Search': search} |
| 80 | + for i, result in enumerate(results, 1): |
| 81 | + if i <= 5: # Ensure we don't go beyond our fieldnames |
| 82 | + row[f"Result {i}"] = result |
| 83 | + writer.writerow(row) |
| 84 | + |
| 85 | + logger.info(f"Results saved to {filename}") |
| 86 | + except IOError as e: |
| 87 | + logger.error(f"Error saving results to {filename}: {e}") |
| 88 | + |
| 89 | +def main() -> None: |
| 90 | + """Main entry point for the CLI application.""" |
34 | 91 | args = parse_args()
|
35 | 92 | load_dotenv()
|
36 |
| - pytrends = TrendReq() |
| 93 | + |
| 94 | + # Verify required environment variables |
| 95 | + api_key = os.getenv("GOOGLE_API_KEY") |
| 96 | + cx_id = os.getenv("SEARCH_ENGINE_ID") |
| 97 | + |
| 98 | + if not api_key or not cx_id: |
| 99 | + logger.error("Missing required environment variables. Please set GOOGLE_API_KEY and SEARCH_ENGINE_ID.") |
| 100 | + sys.exit(1) |
37 | 101 |
|
38 | 102 | try:
|
| 103 | + # Initialize PyTrends |
| 104 | + logger.info(f"Initializing PyTrends for query '{args.query}' in {args.country}") |
| 105 | + pytrends = TrendReq(hl=args.country.lower()) |
| 106 | + pytrends.build_payload([args.query], timeframe=args.timeframe, geo=args.country) |
| 107 | + |
| 108 | + # Get related searches |
| 109 | + logger.info("Getting related searches...") |
| 110 | + related_searches = get_google_related_searches(args.query, pytrends) |
| 111 | + |
| 112 | + if not related_searches: |
| 113 | + logger.warning("No related searches found") |
| 114 | + return |
| 115 | + |
| 116 | + # Get search results for related searches |
| 117 | + logger.info("Getting search results for related searches...") |
39 | 118 | related_searches_with_results = get_top_results_for_related_searches(
|
40 |
| - args.query, |
41 |
| - pytrends, |
42 |
| - os.getenv("GOOGLE_API_KEY"), |
43 |
| - os.getenv("SEARCH_ENGINE_ID") |
| 119 | + args.query, pytrends, api_key, cx_id |
44 | 120 | )
|
45 | 121 |
|
46 |
| - save_related_searches_to_csv(related_searches_with_results, f"{args.query}_related_searches.csv") |
| 122 | + # Save results to CSV if requested |
| 123 | + output_file = args.output or f"{args.query.replace(' ', '_')}_related_searches.csv" |
| 124 | + save_related_searches_to_csv(related_searches_with_results, output_file) |
47 | 125 |
|
48 |
| - if args.wordcloud: |
49 |
| - related_searches = list(related_searches_with_results.keys()) |
| 126 | + # Create wordcloud if requested |
| 127 | + if not args.no_wordcloud: |
| 128 | + logger.info(f"Creating wordcloud at {args.wordcloud}...") |
50 | 129 | create_wordcloud(related_searches, args.wordcloud)
|
51 |
| - |
| 130 | + logger.info(f"Wordcloud saved to {args.wordcloud}") |
| 131 | + |
| 132 | + logger.info("Analysis complete!") |
| 133 | + |
| 134 | + except KeyboardInterrupt: |
| 135 | + logger.info("Operation canceled by user.") |
| 136 | + sys.exit(0) |
52 | 137 | except Exception as e:
|
53 |
| - logger.error(f"Error durante la ejecución: {str(e)}") |
| 138 | + logger.error(f"Error during execution: {str(e)}", exc_info=True) |
| 139 | + sys.exit(1) |
| 140 | + |
| 141 | +if __name__ == "__main__": |
| 142 | + main() |
0 commit comments