Replace print() with logger calls in llm_utils, random_image_for_visual_search, and rewards_tasks

This commit is contained in:
abhijitgorde5-crypto
2026-09-08 23:02:34 +05:30
parent 049a119e36
commit 03636ac984
4 changed files with 41 additions and 80 deletions
-1
View File
@@ -6,4 +6,3 @@ USER_DATA_DIR = abspath("./data-dir")
PROFILE_NAME = "Default" PROFILE_NAME = "Default"
+2 -2
View File
@@ -89,7 +89,7 @@ def get_search_query_from_task_description(task_description: str) -> str:
response = get_nonempty_ollama_response(messages) response = get_nonempty_ollama_response(messages)
return response.lower() return response.lower()
except Exception as exc: 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"}] 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" fallback_query = " ".join(words[:4]) if words else f"{get_random_noun()} search"
return fallback_query.lower() return fallback_query.lower()
@@ -126,7 +126,7 @@ def get_related_search_queries(seed_word: str, num_queries: int=20) -> Generator
}) })
continue continue
except Exception as exc: 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 use_fallback = True
noun1 = get_random_noun() noun1 = get_random_noun()
+34 -72
View File
@@ -1,5 +1,6 @@
import io import io
import json import json
import logging
import time import time
from pathlib import Path from pathlib import Path
from urllib.parse import urlsplit, urlunsplit from urllib.parse import urlsplit, urlunsplit
@@ -7,6 +8,8 @@ from urllib.parse import urlsplit, urlunsplit
import requests import requests
from PIL import Image from PIL import Image
logger = logging.getLogger(__name__)
# ============================================================ # ============================================================
# CONFIG # CONFIG
@@ -93,10 +96,7 @@ def wait_after_429(response, attempt):
wait_time = max(5, wait_time) wait_time = max(5, wait_time)
print( logger.warning("Rate limited. Waiting %d seconds...", wait_time)
f"Rate limited. Waiting "
f"{wait_time} seconds..."
)
time.sleep(wait_time) time.sleep(wait_time)
@@ -118,7 +118,7 @@ def download_image(url):
) )
except (requests.RequestException, ConnectionResetError, OSError) as e: except (requests.RequestException, ConnectionResetError, OSError) as e:
print(f"Download failed: {e}") logger.warning("Download failed: %s", e)
return None return None
if response.status_code == 429: if response.status_code == 429:
@@ -126,13 +126,13 @@ def download_image(url):
return None return None
if response.status_code == 403: if response.status_code == 403:
print("Wikimedia returned 403 Forbidden.") logger.warning("Wikimedia returned 403 Forbidden.")
return None return None
try: try:
response.raise_for_status() response.raise_for_status()
except requests.RequestException as e: except requests.RequestException as e:
print(f"HTTP error: {e}") logger.warning("HTTP error: %s", e)
return None return None
content_type = response.headers.get( content_type = response.headers.get(
@@ -141,13 +141,11 @@ def download_image(url):
).lower() ).lower()
if not content_type.startswith("image/"): if not content_type.startswith("image/"):
print( logger.warning("Not an image: %s", content_type)
f"Not an image: {content_type}"
)
return None return None
if not response.content: if not response.content:
print("Downloaded image is empty.") logger.warning("Downloaded image is empty.")
return None return None
return response.content return response.content
@@ -188,15 +186,13 @@ def convert_to_jpeg(image_data):
return output.getvalue() return output.getvalue()
except Exception as e: except Exception as e:
print( logger.warning("JPEG conversion failed: %s", e)
f"JPEG conversion failed: {e}"
)
return None return None
def generate_fallback_image(): def generate_fallback_image():
"""Generate a synthetic local JPEG image using PIL as a fallback.""" """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 from PIL import ImageDraw
import random import random
@@ -215,7 +211,7 @@ def generate_fallback_image():
jpeg_data = output.getvalue() jpeg_data = output.getvalue()
OUTPUT_FILE.write_bytes(jpeg_data) 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} return {"title": "Fallback Synthetic Image", "width": 800, "height": 600}
@@ -233,10 +229,7 @@ def get_random_image():
if attempt > 1: if attempt > 1:
time.sleep(REQUEST_DELAY) time.sleep(REQUEST_DELAY)
print( logger.debug("Attempt %d/%d", attempt, MAX_ATTEMPTS)
f"\nAttempt "
f"{attempt}/{MAX_ATTEMPTS}"
)
params = { params = {
"action": "query", "action": "query",
@@ -263,7 +256,7 @@ def get_random_image():
) )
except (requests.RequestException, ConnectionResetError, OSError) as e: except (requests.RequestException, ConnectionResetError, OSError) as e:
print(f"API request failed: {e}") logger.warning("API request failed: %s", e)
continue continue
if response.status_code == 429: if response.status_code == 429:
@@ -281,7 +274,7 @@ def get_random_image():
requests.RequestException, requests.RequestException,
ValueError, ValueError,
) as e: ) as e:
print(f"API error: {e}") logger.warning("API error: %s", e)
continue continue
pages = ( pages = (
@@ -291,7 +284,7 @@ def get_random_image():
) )
if not pages: if not pages:
print("No page returned.") logger.debug("No page returned.")
continue continue
page = next( page = next(
@@ -308,9 +301,7 @@ def get_random_image():
) )
if not imageinfo: if not imageinfo:
print( logger.debug("No image information.")
"No image information."
)
continue continue
info = imageinfo[0] info = imageinfo[0]
@@ -348,55 +339,39 @@ def get_random_image():
"image/png", "image/png",
"image/webp", "image/webp",
}: }:
print( logger.debug("Skipping unsupported type: %s", mime)
f"Skipping unsupported type: "
f"{mime}"
)
continue continue
if width < MIN_WIDTH or height < MIN_HEIGHT: if width < MIN_WIDTH or height < MIN_HEIGHT:
print( logger.debug("Skipping small image: %dx%d", width, height)
f"Skipping small image: "
f"{width}x{height}"
)
continue continue
if size > MAX_FILE_SIZE: if size > MAX_FILE_SIZE:
print( logger.debug("Skipping large image: %.1f MB", size / 1024 / 1024)
f"Skipping large image: "
f"{size / 1024 / 1024:.1f} MB"
)
continue continue
if not thumbnail_url: if not thumbnail_url:
print("No thumbnail URL.") logger.debug("No thumbnail URL.")
continue continue
print(f"Found: {title}") logger.debug("Found: %s (%dx%d)", title, width, height)
print(
f"Size: {width}x{height}"
)
image_data = download_image( image_data = download_image(
thumbnail_url thumbnail_url
) )
if image_data is None and original_url: if image_data is None and original_url:
print( logger.debug("Thumbnail download failed, trying original URL...")
"Trying original..."
)
image_data = download_image( image_data = download_image(
original_url original_url
) )
if image_data is None: if image_data is None:
print( logger.debug("Couldn't download image.")
"Couldn't download image."
)
continue continue
print("Converting to JPEG...") logger.debug("Converting to JPEG...")
jpeg_data = convert_to_jpeg( jpeg_data = convert_to_jpeg(
image_data image_data
@@ -411,9 +386,7 @@ def get_random_image():
) )
except OSError as e: except OSError as e:
print( logger.warning("Couldn't save image: %s", e)
f"Couldn't save image: {e}"
)
continue continue
metadata = { metadata = {
@@ -456,30 +429,19 @@ def get_random_image():
) )
except OSError as e: except OSError as e:
print( logger.warning("Couldn't save metadata: %s", e)
f"Warning: couldn't save "
f"metadata: {e}"
)
print() logger.info(
print("=" * 50) "Visual search image saved: %s (%s, %.1f KB, source: %s)",
print("SUCCESS") OUTPUT_FILE.absolute(),
print("=" * 50) f"{width}x{height}",
print( len(jpeg_data) / 1024,
f"Image: " title,
f"{OUTPUT_FILE.absolute()}"
)
print(
f"Size: "
f"{len(jpeg_data) / 1024:.1f} KB"
)
print(
f"Source: {title}"
) )
return metadata 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() return generate_fallback_image()
+5 -5
View File
@@ -91,8 +91,8 @@ class RewardsTaskUtils:
time.sleep(2) time.sleep(2)
url = self.driver.current_url.lower() url = self.driver.current_url.lower()
if "login.live.com" in url or "account.microsoft.com" in url or "signup" in url: 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!") logger.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("Please sign in once on rewards.bing.com in this Edge profile window.")
except Exception: except Exception:
pass pass
@@ -203,7 +203,7 @@ class RewardsTaskUtils:
try: try:
self.move_to_and_click(get_activity_elem) self.move_to_and_click(get_activity_elem)
except Exception as exc: 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 continue
time.sleep(random.uniform(2, 3)) time.sleep(random.uniform(2, 3))
@@ -254,7 +254,7 @@ class RewardsTaskUtils:
self.switch_to_earn_page() self.switch_to_earn_page()
if not os.path.exists(VISUAL_SEARCH_IMAGE_PATH): 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 import random_image_for_visual_search
random_image_for_visual_search.get_random_image() random_image_for_visual_search.get_random_image()
@@ -295,7 +295,7 @@ class RewardsTaskUtils:
time.sleep(random.uniform(1, 2)) time.sleep(random.uniform(1, 2))
self.tab_utils.close_all_other_tabs(exceptions=[main_tab]) self.tab_utils.close_all_other_tabs(exceptions=[main_tab])
except Exception as exc: except Exception as exc:
print(f"[WARNING] Misc Card [{index}] interaction failed: {exc}") logger.warning("Misc Card [%d] interaction failed: %s", index, exc)
continue continue
for card in self.elements.get_all_misc_cards(): for card in self.elements.get_all_misc_cards():