From 03636ac9848a3b7c83143eafc94e40841e8f0c21 Mon Sep 17 00:00:00 2001 From: abhijitgorde5-crypto Date: Tue, 8 Sep 2026 22:55:59 +0530 Subject: [PATCH] Replace print() with logger calls in llm_utils, random_image_for_visual_search, and rewards_tasks --- src/constants.py | 1 - src/llm_utils.py | 4 +- src/random_image_for_visual_search.py | 106 +++++++++----------------- src/rewards_tasks.py | 10 +-- 4 files changed, 41 insertions(+), 80 deletions(-) diff --git a/src/constants.py b/src/constants.py index a552bcc..2bf35c7 100644 --- a/src/constants.py +++ b/src/constants.py @@ -6,4 +6,3 @@ USER_DATA_DIR = abspath("./data-dir") PROFILE_NAME = "Default" - diff --git a/src/llm_utils.py b/src/llm_utils.py index 38d598c..4cb44bd 100644 --- a/src/llm_utils.py +++ b/src/llm_utils.py @@ -89,7 +89,7 @@ def get_search_query_from_task_description(task_description: str) -> str: response = get_nonempty_ollama_response(messages) return response.lower() except Exception as exc: - print(f"[WARNING] Ollama is offline or unavailable ({exc}). Using fallback search query generator.") + logger.warning("Ollama is offline or unavailable (%s). Using fallback search query generator.", exc) words = [w for w in re.sub(r"[^\w\s]", "", task_description).split() if len(w) > 3 and w.lower() not in {"search", "bing", "find", "about", "with", "from", "that", "this"}] fallback_query = " ".join(words[:4]) if words else f"{get_random_noun()} search" return fallback_query.lower() @@ -126,7 +126,7 @@ def get_related_search_queries(seed_word: str, num_queries: int=20) -> Generator }) continue except Exception as exc: - print(f"[WARNING] Ollama is offline or unavailable ({exc}). Using built-in generator for remaining queries.") + logger.warning("Ollama is offline or unavailable (%s). Using built-in generator for remaining queries.", exc) use_fallback = True noun1 = get_random_noun() diff --git a/src/random_image_for_visual_search.py b/src/random_image_for_visual_search.py index f5dd5c8..00b45ed 100644 --- a/src/random_image_for_visual_search.py +++ b/src/random_image_for_visual_search.py @@ -1,5 +1,6 @@ import io import json +import logging import time from pathlib import Path from urllib.parse import urlsplit, urlunsplit @@ -7,6 +8,8 @@ from urllib.parse import urlsplit, urlunsplit import requests from PIL import Image +logger = logging.getLogger(__name__) + # ============================================================ # CONFIG @@ -93,10 +96,7 @@ def wait_after_429(response, attempt): wait_time = max(5, wait_time) - print( - f"Rate limited. Waiting " - f"{wait_time} seconds..." - ) + logger.warning("Rate limited. Waiting %d seconds...", wait_time) time.sleep(wait_time) @@ -118,7 +118,7 @@ def download_image(url): ) except (requests.RequestException, ConnectionResetError, OSError) as e: - print(f"Download failed: {e}") + logger.warning("Download failed: %s", e) return None if response.status_code == 429: @@ -126,13 +126,13 @@ def download_image(url): return None if response.status_code == 403: - print("Wikimedia returned 403 Forbidden.") + logger.warning("Wikimedia returned 403 Forbidden.") return None try: response.raise_for_status() except requests.RequestException as e: - print(f"HTTP error: {e}") + logger.warning("HTTP error: %s", e) return None content_type = response.headers.get( @@ -141,13 +141,11 @@ def download_image(url): ).lower() if not content_type.startswith("image/"): - print( - f"Not an image: {content_type}" - ) + logger.warning("Not an image: %s", content_type) return None if not response.content: - print("Downloaded image is empty.") + logger.warning("Downloaded image is empty.") return None return response.content @@ -188,15 +186,13 @@ def convert_to_jpeg(image_data): return output.getvalue() except Exception as e: - print( - f"JPEG conversion failed: {e}" - ) + logger.warning("JPEG conversion failed: %s", e) return None def generate_fallback_image(): """Generate a synthetic local JPEG image using PIL as a fallback.""" - print("[INFO] Generating synthetic local fallback image for visual search...") + logger.info("Generating synthetic local fallback image for visual search...") from PIL import ImageDraw import random @@ -215,7 +211,7 @@ def generate_fallback_image(): jpeg_data = output.getvalue() OUTPUT_FILE.write_bytes(jpeg_data) - print(f"Saved fallback image to {OUTPUT_FILE.absolute()}") + logger.info("Saved fallback image to %s", OUTPUT_FILE.absolute()) return {"title": "Fallback Synthetic Image", "width": 800, "height": 600} @@ -233,10 +229,7 @@ def get_random_image(): if attempt > 1: time.sleep(REQUEST_DELAY) - print( - f"\nAttempt " - f"{attempt}/{MAX_ATTEMPTS}" - ) + logger.debug("Attempt %d/%d", attempt, MAX_ATTEMPTS) params = { "action": "query", @@ -263,7 +256,7 @@ def get_random_image(): ) except (requests.RequestException, ConnectionResetError, OSError) as e: - print(f"API request failed: {e}") + logger.warning("API request failed: %s", e) continue if response.status_code == 429: @@ -281,7 +274,7 @@ def get_random_image(): requests.RequestException, ValueError, ) as e: - print(f"API error: {e}") + logger.warning("API error: %s", e) continue pages = ( @@ -291,7 +284,7 @@ def get_random_image(): ) if not pages: - print("No page returned.") + logger.debug("No page returned.") continue page = next( @@ -308,9 +301,7 @@ def get_random_image(): ) if not imageinfo: - print( - "No image information." - ) + logger.debug("No image information.") continue info = imageinfo[0] @@ -348,55 +339,39 @@ def get_random_image(): "image/png", "image/webp", }: - print( - f"Skipping unsupported type: " - f"{mime}" - ) + logger.debug("Skipping unsupported type: %s", mime) continue if width < MIN_WIDTH or height < MIN_HEIGHT: - print( - f"Skipping small image: " - f"{width}x{height}" - ) + logger.debug("Skipping small image: %dx%d", width, height) continue if size > MAX_FILE_SIZE: - print( - f"Skipping large image: " - f"{size / 1024 / 1024:.1f} MB" - ) + logger.debug("Skipping large image: %.1f MB", size / 1024 / 1024) continue if not thumbnail_url: - print("No thumbnail URL.") + logger.debug("No thumbnail URL.") continue - print(f"Found: {title}") - print( - f"Size: {width}x{height}" - ) + logger.debug("Found: %s (%dx%d)", title, width, height) image_data = download_image( thumbnail_url ) if image_data is None and original_url: - print( - "Trying original..." - ) + logger.debug("Thumbnail download failed, trying original URL...") image_data = download_image( original_url ) if image_data is None: - print( - "Couldn't download image." - ) + logger.debug("Couldn't download image.") continue - print("Converting to JPEG...") + logger.debug("Converting to JPEG...") jpeg_data = convert_to_jpeg( image_data @@ -411,9 +386,7 @@ def get_random_image(): ) except OSError as e: - print( - f"Couldn't save image: {e}" - ) + logger.warning("Couldn't save image: %s", e) continue metadata = { @@ -456,30 +429,19 @@ def get_random_image(): ) except OSError as e: - print( - f"Warning: couldn't save " - f"metadata: {e}" - ) + logger.warning("Couldn't save metadata: %s", e) - print() - print("=" * 50) - print("SUCCESS") - print("=" * 50) - print( - f"Image: " - f"{OUTPUT_FILE.absolute()}" - ) - print( - f"Size: " - f"{len(jpeg_data) / 1024:.1f} KB" - ) - print( - f"Source: {title}" + logger.info( + "Visual search image saved: %s (%s, %.1f KB, source: %s)", + OUTPUT_FILE.absolute(), + f"{width}x{height}", + len(jpeg_data) / 1024, + title, ) return metadata - print("[WARNING] Could not download image from Wikimedia Commons. Generating local fallback image.") + logger.warning("Could not download image from Wikimedia Commons. Generating local fallback image.") return generate_fallback_image() diff --git a/src/rewards_tasks.py b/src/rewards_tasks.py index 3e265e2..0c327b4 100644 --- a/src/rewards_tasks.py +++ b/src/rewards_tasks.py @@ -91,8 +91,8 @@ class RewardsTaskUtils: time.sleep(2) url = self.driver.current_url.lower() if "login.live.com" in url or "account.microsoft.com" in url or "signup" in url: - print("\n[WARNING] Microsoft Rewards is NOT signed in on rewards.bing.com for this profile!") - print("[WARNING] Please sign in once on rewards.bing.com in this Edge profile window.\n") + logger.warning("Microsoft Rewards is NOT signed in on rewards.bing.com for this profile!") + logger.warning("Please sign in once on rewards.bing.com in this Edge profile window.") except Exception: pass @@ -203,7 +203,7 @@ class RewardsTaskUtils: try: self.move_to_and_click(get_activity_elem) except Exception as exc: - print(f"[WARNING] Failed to click daily set activity {index + 1}: {exc}") + logger.warning("Failed to click daily set activity %d: %s", index + 1, exc) continue time.sleep(random.uniform(2, 3)) @@ -254,7 +254,7 @@ class RewardsTaskUtils: self.switch_to_earn_page() if not os.path.exists(VISUAL_SEARCH_IMAGE_PATH): - print("[INFO] visual_search.jpg not found. Generating visual search image...") + logger.info("visual_search.jpg not found. Generating visual search image...") import random_image_for_visual_search random_image_for_visual_search.get_random_image() @@ -295,7 +295,7 @@ class RewardsTaskUtils: time.sleep(random.uniform(1, 2)) self.tab_utils.close_all_other_tabs(exceptions=[main_tab]) except Exception as exc: - print(f"[WARNING] Misc Card [{index}] interaction failed: {exc}") + logger.warning("Misc Card [%d] interaction failed: %s", index, exc) continue for card in self.elements.get_all_misc_cards():