import os
import time
import json
import logging
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import pytesseract
import re
import pandas as pd
from collections import OrderedDict
class AviatorOCRScraper:
def init(self):
self.SCREENSHOT_DIR = "screenshots"
self.DATA_DIR = "data"
self.EXCEL_DIR = r"C:\Users\levig\downloads"
self.INTERVAL = 10 # Screenshot interval in seconds
self.TOTAL_TIME = 60 # Total run time in seconds (5 minutes)
code
Assistant
# Windows-specific Tesseract path
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Create necessary directories
for directory in [self.SCREENSHOT_DIR, self.DATA_DIR]:
if not os.path.exists(directory):
os.makedirs(directory)
self.setup_logging()
self.multipliers_data = OrderedDict()
def setup_logging(self):
logging.basicConfig(
filename='aviator_ocr.log',
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s'
)
self.logger = logging.getLogger(__name__)
def setup_driver(self):
options = Options()
# options.add_argument('--headless') # Uncomment to run headless
options.add_argument('--start-maximized')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
self.logger.info("WebDriver initialized.")
def login(self):
try:
self.driver.get("https://betika.com/en-ke/login")
self.logger.info("Opened Betika login page.")
time.sleep(5) # Wait for page to load
# Login sequence
self.driver.find_element("css selector", "div.session__form__input.session__form__phone input.input").send_keys("0703972766")
self.driver.find_element("css selector", "div.session__form__input.session__form__password input.input").send_keys("ComplexPass123!")
self.driver.find_element("css selector", "button.session__form__button.login.button.button__secondary").click()
self.logger.info("Login sequence completed.")
time.sleep(5) # Wait for login to complete
except Exception as e:
self.logger.error(f"Login error: {e}")
raise
def navigate_to_aviator(self):
self.driver.get("https://betika.com/en-ke/aviator")
self.logger.info("Navigated to Aviator page.")
time.sleep(10) # Wait for game to load
def capture_and_process(self):
start_time = time.time()
iteration = 0
while time.time() - start_time < self.TOTAL_TIME:
try:
iteration += 1
timestamp = datetime.now().isoformat()
screenshot_path = os.path.join(self.SCREENSHOT_DIR, f"aviator_{iteration}.png")
# Take screenshot
self.driver.save_screenshot(screenshot_path)
self.logger.info(f"Screenshot saved: {screenshot_path}")
# Process screenshot with OCR
image = Image.open(screenshot_path)
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.x'
text = pytesseract.image_to_string(image, config=custom_config)
# Extract multipliers
multipliers = re.findall(r'\d+\.\d+x', text)
if multipliers:
for mult in multipliers:
# Filter out unwanted values
if not re.match(r'0\.00x|00\d\.', mult):
mult_value = float(mult.rstrip('x'))
if mult_value not in self.multipliers_data:
self.multipliers_data[mult_value] = {
'multiplier': mult,
'timestamp': timestamp,
'iteration': iteration
}
self.logger.info(f"Found new valid multiplier: {mult}")
time.sleep(self.INTERVAL)
except Exception as e:
self.logger.error(f"Error in iteration {iteration}: {e}")
time.sleep(self.INTERVAL) # Still wait before next iteration
def save_data(self):
if not self.multipliers_data:
self.logger.warning("No data to save.")
return None
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'aviator_data_{timestamp}.json'
filepath = os.path.join(self.DATA_DIR, filename)
with open(filepath, 'w') as f:
json.dump(list(self.multipliers_data.values()), f, indent=2)
self.logger.info(f"Data saved to {filepath}")
return filepath
def process_data_to_excel(self):
if not self.multipliers_data:
self.logger.warning("No data to process.")
return None
df = pd.DataFrame(self.multipliers_data.values())
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['time_of_day'] = df['timestamp'].dt.time
df['month'] = df['timestamp'].dt.strftime('%B') # Full month name
df['multiplier'] = df['multiplier'].str.rstrip('x').astype(float)
# Rename columns
df = df.rename(columns={'multiplier': 'outcome'})
# Select and order columns
df = df[['outcome', 'time_of_day', 'month']]
# Generate Excel filename
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
excel_filename = f'aviator_data_{timestamp}.xlsx'
excel_filepath = os.path.join(self.EXCEL_DIR, excel_filename)
# Save to Excel
df.to_excel(excel_filepath, index=False)
self.logger.info(f"Excel file created: {excel_filepath}")
return excel_filepath
def run(self):
try:
self.setup_driver()
self.login()
self.navigate_to_aviator()
self.logger.info(f"Starting capture process. Will run for {self.TOTAL_TIME} seconds.")
self.capture_and_process()
json_filepath = self.save_data()
if self.multipliers_data:
print(f"Captured {len(self.multipliers_data)} unique multipliers")
print(f"JSON data saved to {json_filepath}")
excel_filepath = self.process_data_to_excel()
print(f"Excel data saved to {excel_filepath}")
else:
print("No multipliers captured")
except Exception as e:
self.logger.error(f"An error occurred: {e}")
finally:
if hasattr(self, 'driver'):
self.driver.quit()
self.logger.info("WebDriver closed")
You need to have a more sophisticated way of dealing with duplicates for this reason: Screenshots taken 10 seconds after have a some information from the previous screenshots plus new some new information. Try to avoid using timestaps to deal with the duplicates since it may be misleading.
Consider the following aviator ocr logs:
2024-10-05 21:24:51,719:INFO:====== WebDriver manager ======
2024-10-05 21:24:52,359:INFO:Get LATEST chromedriver version for google-chrome
2024-10-05 21:24:52,681:INFO:Get LATEST chromedriver version for google-chrome
2024-10-05 21:24:52,929:INFO:Driver [C:\Users\levig.wdm\drivers\chromedriver\win64\129.0.6668.89\chromedriver-win32/chromedriver.exe] found in cache
2024-10-05 21:24:53,981:INFO:WebDriver initialized.
2024-10-05 21:25:00,511:INFO:Opened Betika login page.
2024-10-05 21:25:05,731:INFO:Login sequence completed.
2024-10-05 21:25:15,957:INFO:Navigated to Aviator page.
2024-10-05 21:25:25,972:INFO:Starting capture process. Will run for 60 seconds.
2024-10-05 21:25:26,140:INFO:Screenshot saved: screenshots\aviator_1.png
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 9.08x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 1.55x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 6.53x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 1.20x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 1.38x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 1.22x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 2.55x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 2.42x
2024-10-05 21:25:26,806:INFO:Found new valid multiplier: 8.23x
2024-10-05 21:25:26,807:INFO:Found new valid multiplier: 4.47x
2024-10-05 21:25:26,807:INFO:Found new valid multiplier: 3.29x
2024-10-05 21:25:36,967:INFO:Screenshot saved: screenshots\aviator_2.png
2024-10-05 21:25:37,942:INFO:Found new valid multiplier: 1.34x
2024-10-05 21:25:37,942:INFO:Found new valid multiplier: 1.33x
2024-10-05 21:25:48,095:INFO:Screenshot saved: screenshots\aviator_3.png
2024-10-05 21:25:48,874:INFO:Found new valid multiplier: 1.83x
2024-10-05 21:25:48,874:INFO:Found new valid multiplier: 1.86x
2024-10-05 21:25:59,024:INFO:Screenshot saved: screenshots\aviator_4.png
2024-10-05 21:25:59,844:INFO:Found new valid multiplier: 4.34x
2024-10-05 21:26:09,985:INFO:Screenshot saved: screenshots\aviator_5.png
2024-10-05 21:26:10,655:INFO:Found new valid multiplier: 8.00x
2024-10-05 21:26:20,789:INFO:Screenshot saved: screenshots\aviator_6.png
2024-10-05 21:26:31,440:INFO:Data saved to data\aviator_data_20241005_212631.json
2024-10-05 21:26:31,472:INFO:Excel file created: C:\Users\levig\downloads\aviator_data_20241005_212631.xlsx
2024-10-05 21:26:33,652:INFO:WebDriver closed
The excel file:
outcome time_of_day month
9.08 21:25:25.972046 October
1.55 21:25:25.972046 October
6.53 21:25:25.972046 October
1.2 21:25:25.972046 October
1.38 21:25:25.972046 October
1.22 21:25:25.972046 October
2.55 21:25:25.972046 October
2.42 21:25:25.972046 October
8.23 21:25:25.972046 October
4.47 21:25:25.972046 October
3.29 21:25:25.972046 October
1.34 21:25:36.810150 October
1.33 21:25:36.810150 October
1.83 21:25:47.953326 October
1.86 21:25:47.953326 October
4.34 21:25:58.879623 October
8 21:26:09.846405 October
To enhance the deduplication mechanism in your AviatorOCRScraper, it's essential to implement a more sophisticated strategy that accurately distinguishes new multipliers from previously detected ones, especially considering the overlapping information in consecutive screenshots. Relying solely on timestamps can indeed be misleading, as multipliers may persist across multiple screenshots.
Proposed Solution
1. Implement State Tracking for Multipliers
Instead of storing multipliers in an OrderedDict keyed by their value, maintain a dynamic set that keeps track of currently active multipliers. By comparing the multipliers detected in the latest screenshot with those from the previous one, you can identify genuinely new multipliers.
2. Avoid Storing Unique Multipliers Globally
Allow the same multiplier value to be recorded multiple times if it appears in different game rounds or after it has disappeared and reappeared. This approach ensures that you capture all relevant occurrences without treating recurring values as duplicates.
3. Utilize a Sliding Window or Active Multiplier Set
Maintain a set of active multipliers from the previous screenshot. In each iteration:
Detect Current Multipliers: Extract multipliers from the current screenshot.
Identify New Multipliers: Determine which multipliers are present in the current set but not in the previous set.
Record New Multipliers: Only log and store these newly identified multipliers.
Update Active Set: Replace the previous set with the current set for the next iteration.
This method effectively filters out multipliers that persist across screenshots, ensuring that only genuinely new multipliers are recorded.
Revised Code Implementation
Below is the modified version of your AviatorOCRScraper class incorporating the improved deduplication strategy:
python
import os
import time
import json
import logging
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import pytesseract
import re
import pandas as pd
from collections import OrderedDict
class AviatorOCRScraper:
def __init__(self):
self.SCREENSHOT_DIR = "screenshots"
self.DATA_DIR = "data"
self.EXCEL_DIR = r"C:\Users\levig\downloads"
self.INTERVAL = 10 # Screenshot interval in seconds
self.TOTAL_TIME = 60 # Total run time in seconds (1 minute for testing)
# Windows-specific Tesseract path
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Create necessary directories
for directory in [self.SCREENSHOT_DIR, self.DATA_DIR]:
if not os.path.exists(directory):
os.makedirs(directory)
self.setup_logging()
self.multipliers_data = []
self.previous_multipliers = set()
def setup_logging(self):
logging.basicConfig(
filename='aviator_ocr.log',
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s'
)
self.logger = logging.getLogger(__name__)
def setup_driver(self):
options = Options()
# options.add_argument('--headless') # Uncomment to run headless
options.add_argument('--start-maximized')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
self.logger.info("WebDriver initialized.")
def login(self):
try:
self.driver.get("https://betika.com/en-ke/login")
self.logger.info("Opened Betika login page.")
time.sleep(5) # Wait for page to load
# Login sequence
self.driver.find_element("css selector", "div.session__form__input.session__form__phone input.input").send_keys("0703972766")
self.driver.find_element("css selector", "div.session__form__input.session__form__password input.input").send_keys("ComplexPass123!")
self.driver.find_element("css selector", "button.session__form__button.login.button.button__secondary").click()
self.logger.info("Login sequence completed.")
time.sleep(5) # Wait for login to complete
except Exception as e:
self.logger.error(f"Login error: {e}")
raise
def navigate_to_aviator(self):
self.driver.get("https://betika.com/en-ke/aviator")
self.logger.info("Navigated to Aviator page.")
time.sleep(10) # Wait for game to load
def capture_and_process(self):
start_time = time.time()
iteration = 0
while time.time() - start_time < self.TOTAL_TIME:
try:
iteration += 1
timestamp = datetime.now().isoformat()
screenshot_path = os.path.join(self.SCREENSHOT_DIR, f"aviator_{iteration}.png")
# Take screenshot
self.driver.save_screenshot(screenshot_path)
self.logger.info(f"Screenshot saved: {screenshot_path}")
# Process screenshot with OCR
image = Image.open(screenshot_path)
custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.x'
text = pytesseract.image_to_string(image, config=custom_config)
# Extract multipliers
multipliers = re.findall(r'\d+\.\d+x', text)
current_multipliers = set()
new_multipliers = set()
for mult in multipliers:
# Filter out unwanted values
if not re.match(r'0\.00x|00\d\.', mult):
mult_value = float(mult.rstrip('x'))
current_multipliers.add(mult_value)
if mult_value not in self.previous_multipliers:
new_multipliers.add(mult_value)
self.logger.info(f"Found new valid multiplier: {mult}")
# Record new multipliers
for mult in new_multipliers:
self.multipliers_data.append({
'multiplier': f"{mult}x",
'timestamp': timestamp,
'iteration': iteration
})
# Update previous_multipliers for next iteration
self.previous_multipliers = current_multipliers
time.sleep(self.INTERVAL)
except Exception as e:
self.logger.error(f"Error in iteration {iteration}: {e}")
time.sleep(self.INTERVAL) # Still wait before next iteration
def save_data(self):
if not self.multipliers_data:
self.logger.warning("No data to save.")
return None
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'aviator_data_{timestamp}.json'
filepath = os.path.join(self.DATA_DIR, filename)
with open(filepath, 'w') as f:
json.dump(self.multipliers_data, f, indent=2)
self.logger.info(f"Data saved to {filepath}")
return filepath
def process_data_to_excel(self):
if not self.multipliers_data:
self.logger.warning("No data to process.")
return None
df = pd.DataFrame(self.multipliers_data)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['time_of_day'] = df['timestamp'].dt.time
df['month'] = df['timestamp'].dt.strftime('%B') # Full month name
df['multiplier'] = df['multiplier'].str.rstrip('x').astype(float)
# Rename columns
df = df.rename(columns={'multiplier': 'outcome'})
# Select and order columns
df = df[['outcome', 'time_of_day', 'month']]
# Generate Excel filename
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
excel_filename = f'aviator_data_{timestamp}.xlsx'
excel_filepath = os.path.join(self.EXCEL_DIR, excel_filename)
# Save to Excel
df.to_excel(excel_filepath, index=False)
self.logger.info(f"Excel file created: {excel_filepath}")
return excel_filepath
def run(self):
try:
self.setup_driver()
self.login()
self.navigate_to_aviator()
self.logger.info(f"Starting capture process. Will run for {self.TOTAL_TIME} seconds.")
self.capture_and_process()
json_filepath = self.save_data()
if self.multipliers_data:
print(f"Captured {len(self.multipliers_data)} unique multipliers")
print(f"JSON data saved to {json_filepath}")
excel_filepath = self.process_data_to_excel()
print(f"Excel data saved to {excel_filepath}")
else:
print("No multipliers captured")
except Exception as e:
self.logger.error(f"An error occurred: {e}")
finally:
if hasattr(self, 'driver'):
self.driver.quit()
self.logger.info("WebDriver closed")
def main():
scraper = AviatorOCRScraper()
scraper.run()
if __name__ == "__main__":
main()
Key Changes Explained
Removal of OrderedDict for multipliers_data:
Before:self.multipliers_data was an OrderedDict keyed by multiplier values, preventing duplicate entries of the same multiplier.
After: Changed to a simple list to allow multiple entries of the same multiplier at different times, ensuring all occurrences are captured.
Introduction of previous_multipliers:
A set self.previous_multipliers is maintained to keep track of multipliers detected in the previous screenshot.
Detection of New Multipliers:
In each iteration, after extracting multipliers from the current screenshot, the code identifies which multipliers are new by comparing them against previous_multipliers.
Only multipliers not present in previous_multipliers are considered new and are logged and stored.
Updating previous_multipliers:
After processing, previous_multipliers is updated to the current set of multipliers, ensuring the comparison basis for the next iteration is current.
Storing Multipliers as a List of Dictionaries:
Each multiplier is stored as a separate dictionary containing its value, timestamp, and iteration number. This structure facilitates easier processing and conversion to JSON and Excel formats.
Adjusted save_data and process_data_to_excel Methods:
These methods now handle self.multipliers_data as a list rather than an OrderedDict.
Benefits of the Revised Approach
Accurate Duplication Handling: By comparing current multipliers with those from the previous screenshot, the scraper accurately identifies genuinely new multipliers, avoiding duplicates caused by overlapping information in consecutive screenshots.
Comprehensive Data Logging: All occurrences of multipliers are captured with their respective timestamps, providing a complete dataset for analysis.
Flexibility for Future Enhancements: The new structure allows for easier integration of more sophisticated deduplication or data processing logic in the future.
Additional Recommendations
Increase TOTAL_TIME Appropriately:
The current TOTAL_TIME is set to 60 seconds for testing purposes. Adjust this value based on your actual use case (e.g., 300 seconds for 5 minutes).
Enhance OCR Accuracy:
Depending on the quality of the screenshots, consider preprocessing the images (e.g., grayscale conversion, noise reduction) to improve OCR accuracy.
Handle Dynamic Multipliers:
If multipliers can change rapidly or have specific patterns, consider implementing more advanced pattern recognition or machine learning techniques to enhance detection reliability.
Error Handling and Recovery:
Implement more robust error handling to recover from unexpected issues during the scraping process, such as network interruptions or changes in the website's structure.
Headless Mode for Efficiency:
Uncomment the --headless option in the Chrome Options to run the scraper without opening a visible browser window, which can improve performance and reduce resource usage.
Logging Enhancements:
Incorporate more detailed logging, such as the number of multipliers detected in each iteration, to facilitate easier debugging and monitoring.
Conclusion
By implementing a state-tracking mechanism for multipliers, the revised AviatorOCRScraper effectively eliminates duplicate entries caused by overlapping information in consecutive screenshots. This improvement ensures that your dataset accurately reflects all unique multiplier occurrences, enhancing the reliability and usefulness of the captured data.