Spaces:
Sleeping
Sleeping
Commit ·
1d8ff49
1
Parent(s): e617155
Bug-Fixed
Browse filesFiles changed (4)
- Dockerfile+16-1
- requirements.txt+1-1
- server.py+6-5
- worker.py+82-41
1233 unmodified lines78910111213141516178 unmodified lines26272829FROM python:3.11-slimWORKDIR /app3 unmodified linesENV HOME=/home/appuserENV PYTHONUSERBASE=/home/appuser/.localRUN apt-get update && apt-get install -y --no-install-recommends \chromium \chromium-driver \&& rm -rf /var/lib/apt/lists/*RUN addgroup --system appuser && adduser --system --ingroup appuser appuserRUN mkdir -p /home/appuser/.local && chown -R appuser:appuser /app /home/appuser8 unmodified linesEXPOSE 7860CMD ["python", "server.py"]12343 unmodified lines8910111213141516171819202122232425262728293031328 unmodified lines41424344# DockerfileFROM python:3.11-slimWORKDIR /app3 unmodified linesENV HOME=/home/appuserENV PYTHONUSERBASE=/home/appuser/.local# System deps + Chromium + ChromeDriver + common headless libsRUN apt-get update && apt-get install -y --no-install-recommends \wget \gnupg \unzip \ca-certificates \chromium \chromium-driver \libnss3 \libxss1 \libasound2 \libxtst6 \libatk-bridge2.0-0 \libgtk-3-0 \libgbm1 \fonts-liberation \&& rm -rf /var/lib/apt/lists/*# Create unprivileged userRUN addgroup --system appuser && adduser --system --ingroup appuser appuserRUN mkdir -p /home/appuser/.local && chown -R appuser:appuser /app /home/appuser8 unmodified linesEXPOSE 7860CMD ["python", "server.py"]
6 unmodified lines789106 unmodified linesseleniumgoogle-api-python-clientgoogle-auth-httplib2google-auth-oauthlib6 unmodified lines789106 unmodified linesseleniumgoogle-api-python-clientgoogle-auth-httplib2google-auth-oauthlib
12319 unmodified lines232425262728296 unmodified lines3637383940414296 unmodified lines13914014114214314414514627 unmodified lines174175176177import eventleteventlet.monkey_patch()19 unmodified linesapp = Flask(__name__)app.config['SECRET_KEY'] = 'secret-key-for-hillside-automation'FRONTEND_ORIGIN = os.getenv('FRONTEND_URL', 'http://127.0.0.1:5500')CORS(app, resources={r"/*": {"origins": FRONTEND_ORIGIN}})socketio = SocketIO(app, cors_allowed_origins=FRONTEND_ORIGIN, async_mode='eventlet')6 unmodified linesself.sender_email = os.getenv('EMAIL_SENDER')self.password = os.getenv('EMAIL_PASSWORD')self.smtp_server = "smtp.gmail.com"; self.smtp_port = 587if not self.sender_email or not self.password: print("[Email] WARNING: Email credentials not found in secrets.")def send_report(self, recipients, subject, body, attachments=None):if not self.sender_email or not self.password: return Falsetry:96 unmodified linessession_data[session_id] = {'csv_content': data['content'], 'emails': data['emails'], 'filename': data['filename']}if bot_instance: bot_instance.shutdown()bot_instance = QuantumBot(socketio, app)# --- Definitive Fix: Capture and send detailed error message ---is_success, error_message = bot_instance.initialize_driver()if is_success:emit('bot_initialized')27 unmodified linesprint(" Make sure all secrets are set in your Hugging Face Space.")print(" Listening on http://127.0.0.1:5000")print("====================================================================")socketio.run(app, host='0.0.0.0', port=int(os.getenv('PORT', 7860)))123419 unmodified lines242526272829306 unmodified lines373839404142434496 unmodified lines14114214314414514614727 unmodified lines175176177178# server.pyimport eventleteventlet.monkey_patch()19 unmodified linesapp = Flask(__name__)app.config['SECRET_KEY'] = 'secret-key-for-hillside-automation'FRONTEND_ORIGIN = os.getenv('FRONTEND_URL', 'http://127.0.0.1:5500')CORS(app, resources={r"/*": {"origins": FRONTEND_ORIGIN}})socketio = SocketIO(app, cors_allowed_origins=FRONTEND_ORIGIN, async_mode='eventlet')6 unmodified linesself.sender_email = os.getenv('EMAIL_SENDER')self.password = os.getenv('EMAIL_PASSWORD')self.smtp_server = "smtp.gmail.com"; self.smtp_port = 587if not self.sender_email or not self.password:print("[Email] WARNING: Email credentials not found in secrets.")def send_report(self, recipients, subject, body, attachments=None):if not self.sender_email or not self.password: return Falsetry:96 unmodified linessession_data[session_id] = {'csv_content': data['content'], 'emails': data['emails'], 'filename': data['filename']}if bot_instance: bot_instance.shutdown()bot_instance = QuantumBot(socketio, app)is_success, error_message = bot_instance.initialize_driver()if is_success:emit('bot_initialized')27 unmodified linesprint(" Make sure all secrets are set in your Hugging Face Space.")print(" Listening on http://127.0.0.1:5000")print("====================================================================")socketio.run(app, host='0.0.0.0', port=int(os.getenv('PORT', 7860)))
12345678910111213141516172 unmodified lines2021222324252627282930313233343536373839404142434445464748495018 unmodified lines69707172737475767778796 unmodified lines86878889909192939422 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import pandas as pdimport timeimport ioimport osimport threadingimport tempfileimport shutilfrom selenium import webdriverfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.webdriver.chrome.options import Options as ChromeOptionsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementNotInteractableExceptionclass QuantumBot:def __init__(self, socketio, app):2 unmodified linesself.driver = Noneself.DEFAULT_TIMEOUT = 30self.termination_event = threading.Event()self.temp_dir = Nonedef initialize_driver(self):try:self.micro_status("Initializing isolated headless browser...")options = ChromeOptions()options.binary_location = "/usr/bin/chromium"user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"self.temp_dir = tempfile.mkdtemp()options.add_argument(f"user-agent={user_agent}")options.add_argument("--headless=new")options.add_argument("--window-size=1920,1080")options.add_argument("--no-sandbox")options.add_argument("--disable-dev-shm-usage")options.add_argument("--disable-gpu")options.add_argument(f"--user-data-dir={self.temp_dir}")options.add_argument('--disable-blink-features=AutomationControlled')options.add_experimental_option("excludeSwitches", ["enable-automation"])options.add_experimental_option('useAutomationExtension', False)service = ChromeService(executable_path="/usr/bin/chromedriver")self.driver = webdriver.Chrome(service=service, options=options)self.driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"})18 unmodified linesself.driver.get("https://gateway.quantumepay.com/")time.sleep(2)self.micro_status("Entering credentials...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "Username"))).send_keys(username)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "Password"))).send_keys(password)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.ID, "login"))).click()self.micro_status("Waiting for OTP screen...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "code1")))return True, Noneexcept Exception as e:error_message = f"Error during login: {str(e)}"6 unmodified linesotp_digits = list(otp)for i in range(6):self.driver.find_element(By.ID, f"code{i+1}").send_keys(otp_digits[i])WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.ID, "login"))).click()self.micro_status("Verifying login success...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Payments']")))return True, Noneexcept Exception as e:error_message = f"Error during OTP submission: {str(e)}"22 unmodified linestry:self.micro_status(f"Navigating to Void page for '{patient_name}'")self.driver.get("https://gateway.quantumepay.com/credit-card/void")search_successful = Falsefor attempt in range(15):try:self.micro_status(f"Searching for patient (Attempt {attempt + 1})...")WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'table-wrapper')]")))search_box = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']")))search_box.click(); time.sleep(0.5)search_box.clear(); time.sleep(0.5)search_box.send_keys(patient_name)search_successful = Truebreakexcept Exception: time.sleep(1)if not search_successful: raise Exception("Failed to search for patient.")time.sleep(3)self.micro_status("Opening transaction details...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, f"//tr[contains(., \"{patient_name}\")]//button[@data-v-b6b33fa0]"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.LINK_TEXT, "Transaction Detail"))).click()self.micro_status("Adding to Vault...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Add to Vault']"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='modal-footer']//button/span[normalize-space()='Confirm']"))).click()try:self.micro_status("Verifying success and saving...")company_input = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, "company_name")))company_input.clear()company_input.send_keys(patient_name)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Save Changes']"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Confirm']]"))).click()time.sleep(5)return 'Done'except TimeoutException:self.micro_status(f"'{patient_name}' is in a bad state, cancelling.")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Cancel']]"))).click()return 'Bad'except Exception as e:print(f"An error occurred while processing {patient_name}: {e}")return 'Error'def shutdown(self):if self.driver:self.driver.quit()if self.temp_dir and os.path.exists(self.temp_dir):shutil.rmtree(self.temp_dir)print(f"[Bot] Cleaned up temporary directory: {self.temp_dir}")1234567891011121314151617182 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585918 unmodified lines787980818283848586878889909192939495966 unmodified lines10310410510610710810911011111211311411522 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# worker.pyimport timeimport osimport threadingimport tempfileimport shutilfrom selenium import webdriverfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.webdriver.chrome.options import Options as ChromeOptionsfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import TimeoutExceptionclass QuantumBot:def __init__(self, socketio, app):2 unmodified linesself.driver = Noneself.DEFAULT_TIMEOUT = 30self.termination_event = threading.Event()self.chrome_user_data_dir = Noneself.chrome_cache_dir = Nonedef initialize_driver(self):try:self.micro_status("Initializing headless browser...")options = ChromeOptions()# Use system Chromium installed in the imageoptions.binary_location = "/usr/bin/chromium"# Per-run, unique profile and cache to avoid "already in use" locksself.chrome_user_data_dir = tempfile.mkdtemp(prefix="chrome-user-data-")self.chrome_cache_dir = tempfile.mkdtemp(prefix="chrome-cache-")options.add_argument(f"--user-data-dir={self.chrome_user_data_dir}")options.add_argument(f"--disk-cache-dir={self.chrome_cache_dir}")# Stable/headless startup flagsuser_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"options.add_argument(f"--user-agent={user_agent}")options.add_argument("--headless=new")options.add_argument("--window-size=1920,1080")options.add_argument("--no-first-run")options.add_argument("--no-default-browser-check")options.add_argument("--no-sandbox")options.add_argument("--disable-dev-shm-usage")options.add_argument("--disable-gpu")options.add_argument("--disable-features=Translate,AutomationControlled")service = ChromeService(executable_path="/usr/bin/chromedriver")self.driver = webdriver.Chrome(service=service, options=options)# De-emphasize webdriver flagself.driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"})18 unmodified linesself.driver.get("https://gateway.quantumepay.com/")time.sleep(2)self.micro_status("Entering credentials...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "Username"))).send_keys(username)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "Password"))).send_keys(password)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.ID, "login"))).click()self.micro_status("Waiting for OTP screen...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.presence_of_element_located((By.ID, "code1")))return True, Noneexcept Exception as e:error_message = f"Error during login: {str(e)}"6 unmodified linesotp_digits = list(otp)for i in range(6):self.driver.find_element(By.ID, f"code{i+1}").send_keys(otp_digits[i])WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.ID, "login"))).click()self.micro_status("Verifying login success...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Payments']")))return True, Noneexcept Exception as e:error_message = f"Error during OTP submission: {str(e)}"22 unmodified linestry:self.micro_status(f"Navigating to Void page for '{patient_name}'")self.driver.get("https://gateway.quantumepay.com/credit-card/void")search_successful = Falsefor attempt in range(15):try:self.micro_status(f"Searching for patient (Attempt {attempt + 1})...")WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'table-wrapper')]")))search_box = WebDriverWait(self.driver, 2).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search']")))search_box.click(); time.sleep(0.5)search_box.clear(); time.sleep(0.5)search_box.send_keys(patient_name)search_successful = Truebreakexcept Exception:time.sleep(1)if not search_successful:raise Exception("Failed to search for patient.")time.sleep(3)self.micro_status("Opening transaction details...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, f"//tr[contains(., \"{patient_name}\")]//button[@data-v-b6b33fa0]"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.LINK_TEXT, "Transaction Detail"))).click()self.micro_status("Adding to Vault...")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Add to Vault']"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='modal-footer']//button/span[normalize-space()='Confirm']"))).click()try:self.micro_status("Verifying success and saving...")company_input = WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.NAME, "company_name")))company_input.clear()company_input.send_keys(patient_name)WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button/span[normalize-space()='Save Changes']"))).click()WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Confirm']]"))).click()time.sleep(5)return 'Done'except TimeoutException:self.micro_status(f"'{patient_name}' is in a bad state, cancelling.")WebDriverWait(self.driver, self.DEFAULT_TIMEOUT).until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Cancel']]"))).click()return 'Bad'except Exception as e:print(f"An error occurred while processing {patient_name}: {e}")return 'Error'def shutdown(self):if self.driver:self.driver.quit()# Cleanup per-run temp dirsfor d in [self.chrome_user_data_dir, self.chrome_cache_dir]:if d and os.path.exists(d):shutil.rmtree(d, ignore_errors=True)print(f"[Bot] Cleaned up temporary Chrome profile and cache.")
Dockerfile+16-1
requirements.txt+1-1
server.py+6-5
worker.py+82-41