Spaces:
Running on Zero
Running on Zero
Asmit commited on
Commit ·
9012453
0
Parent(s):
Initial commit
Browse filesFiles changed (19)
- .gitattributesAdded+35
- .gitignoreAdded+62
- README.mdAdded+64
- app.pyAdded+1156
- models/vision/14.ptAdded+3
- models/vision/15.ptAdded+3
- models/vision/16.ptAdded+3
- packages.txtAdded+1
- py_files/__init__.pyAdded+1
- py_files/bounding_clustering.pyAdded+220
- py_files/dataset_upload.pyAdded+237
- py_files/gemini_analysis.pyAdded+439
- py_files/ocr.pyAdded+157
- py_files/pycolor.pyAdded
- py_files/utils.pyAdded+60
- py_files/yolo.pyAdded+370
- requirements.txtAdded+19
- system_prompt.encAdded
- system_prompt_thinking.encAdded+1
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.egg
.env.venvenv/venv/ENV/env.bak/venv.bak/
.DS_Store.DS_Store?._*.Spotlight-V100.Trashesehthumbs.dbThumbs.db
*.loglogs/temp/tmp/
# IDE.vscode/.idea/*.swp*.swo
# Model files*.pt*.pthmodels/
# Credentialskey.json*.json
# Gradiogradio_cached_examples/flagged/
run.localconfig12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364---title: DeceptivePatternDetectoremoji: 🐨colorFrom: purplecolorTo: redsdk: gradiosdk_version: 5.46.0app_file: app.pypinned: falselicense: cc-by-nc-4.0---
# 🔍 Deceptive Pattern Detector
An AI-powered tool that analyzes website screenshots to detect potentially deceptive design patterns (also known as "dark patterns").
## 🚀 Features
- **Image Upload**: Upload screenshots of websites for analysis- **OCR Analysis**: Extracts text and UI elements from images- **Element Detection**: Identifies buttons, checkboxes, and other interactive elements- **AI Analysis**: Uses Google Gemini AI to classify potential deceptive patterns- **Pattern Categories**: Detects various types including: - Confirm-shaming - Urgency manipulation - Scarcity tactics - Misdirection - Privacy violations - And more...
## 📋 How to Use
1. **Upload Image**: Take a screenshot of a website and upload it2. **API Key**: Enter your Google Gemini API key ([Get one here](https://makersuite.google.com/app/apikey))3. **Analyze**: Click the analyze button and wait for results4. **Review**: Examine the detected patterns and explanations
## 🔧 Requirements
- Google Gemini API key for AI analysis- Google Cloud Vision API credentials (optional, for enhanced OCR)
## 🛠️ Technical Details
This tool combines:- **Computer Vision**: For UI element detection- **OCR**: For text extraction using Google Cloud Vision- **AI Analysis**: Using Google Gemini for pattern classification- **Rule-based Fallbacks**: For basic detection when AI is unavailable
## ⚠️ Disclaimer
This tool uses AI analysis and may not catch all deceptive patterns or may flag legitimate design elements. The results should be used as a supplementary guide and not as a definitive assessment.
## 🏗️ Architecture
- **Frontend**: Gradio interface- **Backend**: Python with simplified computer vision- **AI**: Google Gemini for pattern analysis- **Deployment**: HuggingFace Spaces compatible
## 📄 License
MIT License - See LICENSE file for details.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156import osimport shutilimport tempfileimport timeimport uuidfrom pathlib import Path
import gradio as grimport pandas as pdimport pybboxes as pbxfrom PIL import Imagefrom huggingface_hub import CommitScheduler
# Import our custom modulesfrom py_files import yolofrom py_files import dataset_uploadfrom py_files.ocr import get_text_from_image_doc
def take_screenshot_and_process(url, gemini_api_key): """ Take a screenshot of the provided URL and process it for deceptive pattern detection. Returns (dataframe, status_message, image_path, eval_dir_for_cleanup) """ print(f"\n[CONSOLE] ===== STARTING ANALYSIS PROCESS =====") print(f"[CONSOLE] URL: {url}") print(f"[CONSOLE] Gemini API Key provided: {'Yes' if gemini_api_key else 'No'}") if not url or not (url.startswith("http://") or url.startswith("https://")): print(f"[CONSOLE] ERROR: Invalid URL format - {url}") yield (None, "❌ Invalid URL format - please use http:// or https://", None, None) raise gr.Error("Please enter a valid URL (starting with http:// or https://).") if not gemini_api_key: print(f"[CONSOLE] ERROR: No Gemini API key provided") yield (None, "❌ No Gemini API key provided", None, None) raise gr.Error("Please provide a Gemini API Key.") # Set the Gemini API key in the environment os.environ["GEMINI_API"] = gemini_api_key print(f"[CONSOLE] Gemini API key set in environment") # Create temporary directory for processing eval_dir = tempfile.mkdtemp() print(f"[CONSOLE] Created temporary directory: {eval_dir}") try: # Step 1: Taking screenshot print(f"[CONSOLE] STEP 1/6: Taking screenshot of the website...") yield (None, "Step 1/6: Taking screenshot of the website...", None, eval_dir) screenshots_dir = os.path.join(eval_dir, "screenshots") ocr_dir = os.path.join(eval_dir, "ocr") yolo_dir = os.path.join(eval_dir, "yolo") csv_yolo_dir = os.path.join(eval_dir, "csv_with_yolo") gemini_fs_dir = os.path.join(eval_dir, "gemini_fs") for d in [screenshots_dir, ocr_dir, yolo_dir, csv_yolo_dir, gemini_fs_dir]: os.makedirs(d, exist_ok=True) print(f"[CONSOLE] Created directory: {d}") # Take screenshot using Selenium image_path = os.path.join(screenshots_dir, "screenshot.png") print(f"[CONSOLE] Taking screenshot, saving to: {image_path}") image = take_website_screenshot(url, image_path) print(f"[CONSOLE] Screenshot completed successfully") # Display the original screenshot immediately print(f"[CONSOLE] Displaying original screenshot") yield (None, "📷 Screenshot captured! Starting analysis...", image_path, eval_dir) # Step 2: Setup directories print(f"[CONSOLE] STEP 2/6: Setting up processing directories...") yield (None, "Step 2/6: Setting up processing directories...", image_path, eval_dir) # Step 3: Run OCR print(f"[CONSOLE] STEP 3/6: Running OCR analysis...") yield (None, "Step 3/6: Running OCR analysis...", image_path, eval_dir) csv_path = os.path.join(ocr_dir, "screenshot.csv") print(f"[CONSOLE] Running OCR on image...") ocr_result = get_text_from_image_doc(image)[0] ocr_df = ocr_result.get_dataframe(image) ocr_df.to_csv(csv_path, index=False) print(f"[CONSOLE] OCR completed, saved to: {csv_path}") print(f"[CONSOLE] OCR found {len(ocr_df)} text elements") # Step 4: Run YOLO object detection print(f"[CONSOLE] STEP 4/6: Running YOLO object detection...") yield (None, "Step 4/6: Running YOLO object detection...", image_path, eval_dir) yolo_result_path = os.path.join(yolo_dir, "screenshot.txt") # Use real YOLO ensemble print(f"[CONSOLE] Loading YOLO ensemble models...") models = yolo.YoloEnsemble(weights=["models/vision/16.pt", "models/vision/15.pt", "models/vision/14.pt"]) print(f"[CONSOLE] Running YOLO prediction with confidence threshold 0.3...") results = models.predict(image_path, conf=0.3, verbose=True) if results[0].boxes is None: print(f"[CONSOLE] YOLO: No objects detected") with open(yolo_result_path, 'w') as f: f.write("") else: print(f"[CONSOLE] YOLO: {len(results[0].boxes)} objects detected") results[0].save_txt(yolo_result_path) print(f"[CONSOLE] YOLO results saved to: {yolo_result_path}") # Step 5: Combine OCR and YOLO results print(f"[CONSOLE] STEP 5/6: Combining OCR and element detection results...") yield (None, "Step 5/6: Combining OCR and element detection results...", image_path, eval_dir) combined_csv_path = os.path.join(csv_yolo_dir, "screenshot.csv") # Combine results using original logic print(f"[CONSOLE] Combining OCR and YOLO results...") combined_df = combine_ocr_yolo_results_original(ocr_df, yolo_result_path, image) combined_df.to_csv(combined_csv_path, index=False) print(f"[CONSOLE] Combined results saved to: {combined_csv_path}") print(f"[CONSOLE] Combined dataframe has {len(combined_df)} rows") # Step 6: Analyze with Gemini print(f"[CONSOLE] STEP 6/6: Analyzing for deceptive patterns with Gemini...") yield (None, "Step 6/6: Analyzing for deceptive patterns with Gemini...", image_path, eval_dir) # Use the generator version for real-time notifications from py_files.gemini_analysis import few_shots_generator # Enhanced progress reporting for Gemini analysis yield (None, "🔧 Preparing data for Gemini analysis...", image_path, eval_dir) # Save the combined results for few_shots processing os.makedirs(gemini_fs_dir, exist_ok=True) print(f"[CONSOLE] Running Gemini few_shots analysis...") print(f"[CONSOLE] Input file: {combined_csv_path}") yield (None, f"📊 Processing {len(combined_df)} UI elements for deceptive pattern analysis...", image_path, eval_dir) # Use the generator version that yields real-time notifications final_df = None try: for status, data in few_shots_generator(eval_dir=eval_dir, files=[combined_csv_path], api_key=gemini_api_key): if status == 'notification': # Yield the notification immediately to the UI yield None, data, image_path, eval_dir elif status == 'result': final_df = data break print(f"[CONSOLE] Gemini analysis completed") except gr.Error: # Re-raise gr.Error exceptions as they should propagate to the UI print(f"[CONSOLE] Gemini analysis raised gr.Error, propagating...") raise except Exception as gemini_error: # Handle any other unexpected errors from Gemini analysis print(f"[CONSOLE] Unexpected error in Gemini analysis: {str(gemini_error)}") error_msg = f"❌ Gemini analysis failed: {str(gemini_error)}" yield (None, error_msg, image_path, eval_dir) # Don't raise here - let the function continue with final_df = None if final_df is None: print(f"[CONSOLE] Gemini analysis failed completely") yield (None, "❌ Gemini analysis failed - please check your API key and try again", image_path, eval_dir) if final_df is not None: print(f"[CONSOLE] Final analysis result: {len(final_df)} rows detected") deceptive_count = len(final_df[final_df['Deceptive Design Category'].str.lower() != 'non-deceptive']) if 'Deceptive Design Category' in final_df.columns else 0 total_count = len(final_df) yield (None, f"📊 Analysis complete! Found {deceptive_count} deceptive patterns out of {total_count} UI elements", image_path, eval_dir) yield (None, "🎨 Creating annotated screenshot with colored highlights...", image_path, eval_dir) # Create annotated screenshot annotated_path = create_annotated_screenshot(image_path, final_df, eval_dir) print(f"[CONSOLE] Annotated screenshot created at: {annotated_path}") # Yield the final results with annotated screenshot replacing the original # annotated_path will always be valid now (either annotated or original as fallback) status_message = "✅ Analysis complete! All elements annotated with colored bounding boxes." if annotated_path == image_path: status_message = "✅ Analysis complete! (Note: Screenshot annotation failed, showing original)" yield (final_df, status_message, annotated_path, eval_dir) else: print(f"[CONSOLE] WARNING: Final analysis result is None") yield (None, "❌ Analysis failed - unable to process results", None, eval_dir) print(f"[CONSOLE] ===== ANALYSIS PROCESS COMPLETED =====") except Exception as e: print(f"[CONSOLE] ERROR in take_screenshot_and_process: {str(e)}") print(f"[CONSOLE] Exception type: {type(e).__name__}") # Send notification to user about the error before yielding error state error_msg = f"❌ Error occurred: {str(e)}" yield (None, error_msg, None, eval_dir) raise gr.Error(f"Error processing website: {str(e)}")
def cleanup_temp_directory(eval_dir): """ Clean up temporary files after image has been displayed to the frontend. This should be called after the UI has had time to display the image. """ if not eval_dir: return try: print(f"[CONSOLE] Cleaning up temporary directory: {eval_dir}") if os.path.exists(eval_dir): shutil.rmtree(eval_dir) print(f"[CONSOLE] Cleanup completed successfully") else: print(f"[CONSOLE] Temp directory {eval_dir} does not exist or was already cleaned up") except Exception as cleanup_error: print(f"[CONSOLE] WARNING: Failed to cleanup temp directory: {cleanup_error}") # Try to clean up individual files if directory removal fails try: if eval_dir and os.path.exists(eval_dir): for root, dirs, files in os.walk(eval_dir): for file in files: try: os.remove(os.path.join(root, file)) print(f"[CONSOLE] Removed individual file: {file}") except Exception as file_error: print(f"[CONSOLE] Failed to remove file {file}: {file_error}") # Try to remove empty directories for root, dirs, files in os.walk(eval_dir, topdown=False): for dir in dirs: try: os.rmdir(os.path.join(root, dir)) except Exception: pass # Try to remove the main directory os.rmdir(eval_dir) print(f"[CONSOLE] Manual cleanup completed") except Exception as manual_cleanup_error: print(f"[CONSOLE] ERROR: Complete cleanup failure: {manual_cleanup_error}") print(f"[CONSOLE] Temp directory may not be fully cleaned: {eval_dir}")
def take_website_screenshot(url, output_path): """ Take a screenshot of a website using Selenium WebDriver. """ print(f"[CONSOLE] take_website_screenshot: Starting selenium screenshot capture for {url}") print(f"[CONSOLE] Output path: {output_path}") from selenium import webdriver from selenium.webdriver.chrome.options import Options import time try: # Setup Chrome options for headless mode print(f"[CONSOLE] Setting up Chrome WebDriver in headless mode...") chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") # chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1280,1024") # chrome_options.add_argument("--disable-extensions") # chrome_options.add_argument("--disable-plugins") # chrome_options.add_argument("--disable-images") # Faster loading # chrome_options.add_argument("--disable-javascript") # Faster loading, optional # Create WebDriver instance print(f"[CONSOLE] Creating Chrome WebDriver instance...")
css_to_inject = ":root { color-scheme: only light; }" javascript_code = """ var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = arguments[0]; document.head.appendChild(style); """
driver = webdriver.Chrome(options=chrome_options) driver.set_window_size(1280, 1024) driver.execute_script(javascript_code, css_to_inject) time.sleep(0.5) try: # Set page load timeout driver.set_page_load_timeout(30) # Navigate to the URL print(f"[CONSOLE] Navigating to URL: {url}") driver.get(url) # Wait a bit for the page to render print(f"[CONSOLE] Waiting for page to load... (5 secs)") time.sleep(5) # Take screenshot print(f"[CONSOLE] Taking screenshot...") driver.save_screenshot(output_path) print(f"[CONSOLE] Screenshot saved to: {output_path}") # Load and return the image image = Image.open(output_path) print(f"[CONSOLE] Screenshot completed successfully, image size: {image.size}") return image finally: # Always close the driver print(f"[CONSOLE] Closing WebDriver...") driver.quit() except Exception as e: print(f"[CONSOLE] Exception in selenium screenshot: {str(e)}") print(f"[CONSOLE] Exception type: {type(e).__name__}") raise Exception(f"Screenshot failed: {str(e)}")
def combine_ocr_yolo_results_original(ocr_df, yolo_result_path, image): """ Combine OCR results with YOLO detection results using the original logic. """ W, H = image.size # Load YOLO results if not os.path.exists(yolo_result_path) or os.path.getsize(yolo_result_path) == 0: # If no YOLO results, just add Element Type column and return ocr_df['Element Type'] = 'text' return ocr_df # Read YOLO results yolo_df = pd.read_csv(yolo_result_path, sep=" ", names=["class", "x1", "y1", "x2", "y2"]) # Convert YOLO format to pixel coordinates for j in range(len(yolo_df)): scaled = pbx.convert_bbox( [yolo_df.iloc[j]['x1'], yolo_df.iloc[j]['y1'], yolo_df.iloc[j]['x2'], yolo_df.iloc[j]['y2']], from_type="yolo", to_type="voc", image_size=(W, H) ) yolo_df.iat[j, 1], yolo_df.iat[j, 2], yolo_df.iat[j, 3], yolo_df.iat[j, 4] = scaled # Class mapping cls_dict = { 0: "button", 1: "checked checkbox", 2: "unchecked checkbox", 3: "checked radio button", 4: "unchecked radio button", 5: "checked switch", 6: "unchecked switch" } # Ensure coordinate columns exist and are strings before processing if 'Top Co-ordinates' not in ocr_df.columns or 'Bottom Co-ordinates' not in ocr_df.columns: ocr_df['Element Type'] = 'text' return ocr_df # Create coordinates column for easier processing ocr_df['Coordinates'] = ( ocr_df['Top Co-ordinates'].astype(str).str.replace('(', '', regex=False).str.replace(')', '', regex=False) + ', ' + ocr_df['Bottom Co-ordinates'].astype(str).str.replace('(', '', regex=False).str.replace(')', '', regex=False) ) ele_types = ["text"] * len(ocr_df) bboxes = yolo_df[['x1', 'y1', 'x2', 'y2']].values.tolist() clss = yolo_df['class'].tolist() if not isinstance(clss, list): clss = [clss] coords = ocr_df['Coordinates'].tolist() # Match YOLO detections with OCR text for ele_cls, ele_rect in zip(clss, bboxes): distance_dict = {} for ci, coord in enumerate(coords): try: rect_text = list(map(float, coord.split(','))) except (ValueError, AttributeError): continue # Skip if coordinate string is invalid if ele_cls == 0: # button if yolo.do_rectangles_overlap(ele_rect, rect_text): ele_types[ci] = cls_dict[ele_cls] break elif ele_cls in [1, 2, 3, 4]: # checkbox or radio e_y1, e_y2 = ele_rect[1], ele_rect[3] r_y1, r_y2 = rect_text[1], rect_text[3] text_mid_y = (r_y1 + r_y2) / 2 if e_y1 < text_mid_y < e_y2 and rect_text[0] > ele_rect[0] and rect_text[0] - ele_rect[2] < 100: distance_dict[rect_text[0] - ele_rect[2]] = ci if ele_cls > 0 and len(distance_dict) > 0: ele_types[sorted(distance_dict.items(), key=lambda x: x[0])[0][1]] = cls_dict[ele_cls] ocr_df['Element Type'] = ele_types ocr_df = ocr_df.drop(columns=['Coordinates']) # Reorder columns cols = ocr_df.columns.tolist() cols = cols[:1] + cols[-1:] + cols[1:-1] ocr_df = ocr_df[cols] return ocr_df
def create_result_display(df): """ Create a display of the analysis results. """ if df is None or df.empty: return "No results to display." # Count deceptive patterns if 'Deceptive Design Category' in df.columns: deceptive_count = len(df[df['Deceptive Design Category'].str.lower() != 'non-deceptive']) total_count = len(df) html_output = f""" <div style="padding: 20px; border: 1px solid var(--border-color-primary); border-radius: 8px; background-color: var(--block-background-fill); color: var(--body-text-color);"> <h3 style="color: var(--body-text-color); margin-top: 0;">Analysis Results</h3> <p style="color: var(--body-text-color);"><strong>Total elements analyzed:</strong> {total_count}</p> <p style="color: var(--body-text-color);"><strong>Potentially deceptive elements:</strong> {deceptive_count}</p> <p style="color: var(--body-text-color);"><strong>Non-deceptive elements:</strong> {total_count - deceptive_count}</p> </div> """ return html_output else: return "Analysis completed, but results format is unexpected."
def create_annotated_screenshot(image_path, df, eval_dir=None): """ Create an annotated screenshot with bounding boxes for deceptive patterns. """ from PIL import Image, ImageDraw, ImageFont import tempfile print(f"[CONSOLE] Creating annotated screenshot from: {image_path}") try: # Load the original image image = Image.open(image_path) annotated_image = image.copy() draw = ImageDraw.Draw(annotated_image) # Define colors for different deceptive pattern categories color_map = { 'forced-action': '#FF0000', # Red 'interface-interference': '#FF8C00', # Dark Orange 'obstruction': '#800080', # Purple 'sneaking': '#FF1493', # Deep Pink 'confirmshaming': '#FF4500', # Orange Red 'nudge': '#32CD32', # Lime Green 'fake-scarcity-fake-urgency': '#FFD700', # Gold 'hard-to-cancel': '#DC143C', # Crimson 'pre-selection': '#8A2BE2', # Blue Violet 'visual-interference': '#FF6347', # Tomato 'jargon': '#4169E1', # Royal Blue 'hidden-subscription': '#B22222', # Fire Brick 'hidden-costs': '#CD5C5C', # Indian Red 'disguised-ads': '#FF69B4', # Hot Pink 'trick-wording': '#FF7F50', # Coral 'non-deceptive': '#90EE90' # Light Green (for non-deceptive elements) } # Default color for unknown categories default_color = '#FFFF00' # Yellow # Try to load a bigger font (at least 2x size) try: font = ImageFont.truetype("arial.ttf", 18) except: try: font = ImageFont.load_default().font_variant(size=18) except: font = ImageFont.load_default() deceptive_count = 0 non_deceptive_count = 0 # Track used text positions to avoid overlaps used_text_regions = [] # Draw bounding boxes for each element for idx, row in df.iterrows(): if 'Deceptive Design Category' not in df.columns: continue category = str(row.get('Deceptive Design Category', '')).lower().strip() subtype = str(row.get('Deceptive Design Subtype', '')).lower().strip() # Count deceptive vs non-deceptive elements if category == 'non-deceptive' or category == 'not-applicable': non_deceptive_count += 1 else: deceptive_count += 1 # Get bounding box coordinates x1, y1, x2, y2 = None, None, None, None # Method 1: Try to extract from 'Top Co-ordinates' and 'Bottom Co-ordinates' columns try: top_coords = row.get('Top Co-ordinates') bottom_coords = row.get('Bottom Co-ordinates') if top_coords is not None and bottom_coords is not None: # Parse tuple strings like "(10, 20)" or tuple objects if isinstance(top_coords, str): top_coords = top_coords.strip('()') x1, y1 = map(float, top_coords.split(',')) elif isinstance(top_coords, (tuple, list)): x1, y1 = float(top_coords[0]), float(top_coords[1]) if isinstance(bottom_coords, str): bottom_coords = bottom_coords.strip('()') x2, y2 = map(float, bottom_coords.split(',')) elif isinstance(bottom_coords, (tuple, list)): x2, y2 = float(bottom_coords[0]), float(bottom_coords[1]) except (ValueError, TypeError, AttributeError): # Method 2: Try direct coordinate columns (x1, y1, x2, y2) try: x1 = float(row.get('x1', 0)) y1 = float(row.get('y1', 0)) x2 = float(row.get('x2', 0)) y2 = float(row.get('y2', 0)) except (ValueError, TypeError): # Method 3: Try alternative coordinate column names (X1, Y1, X2, Y2) try: x1 = float(row.get('X1', 0)) y1 = float(row.get('Y1', 0)) x2 = float(row.get('X2', 0)) y2 = float(row.get('Y2', 0)) except (ValueError, TypeError): print(f"[CONSOLE] Warning: Could not extract coordinates for row {idx}") continue # Validate that all coordinates were successfully extracted if any(coord is None for coord in [x1, y1, x2, y2]): print(f"[CONSOLE] Warning: Missing coordinates for row {idx}") continue # Ensure coordinates are within image bounds x1 = max(0, min(x1, image.width)) x2 = max(0, min(x2, image.width)) y1 = max(0, min(y1, image.height)) y2 = max(0, min(y2, image.height)) # Ensure x1 <= x2 and y1 <= y2 (swap if necessary) if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 # Skip if box is too small or invalid if (x2 - x1) < 5 or (y2 - y1) < 5: continue # Choose color based on category or subtype color = color_map.get(category, color_map.get(subtype, default_color)) # Draw bounding box draw.rectangle([x1, y1, x2, y2], outline=color, width=2) # Draw label text = f"{category}" if subtype and subtype != 'not-applicable' and subtype != 'n/a': text = f"{category}: {subtype}" # Get text dimensions text_bbox = draw.textbbox((0, 0), text, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] # Function to check if a rectangle overlaps with any used regions def check_overlap(x, y, w, h, used_regions): new_rect = (x, y, x + w, y + h) for used_rect in used_regions: if not (new_rect[2] < used_rect[0] or new_rect[0] > used_rect[2] or new_rect[3] < used_rect[1] or new_rect[1] > used_rect[3]): return True return False # Try different positions for the text to avoid overlaps text_x = x1 text_y = None padding = 4 # Position 1: Above the bounding box candidate_y = y1 - text_height - padding if candidate_y >= 0: # Within image bounds # Adjust x position to stay within image bounds if text_x + text_width > image.width: text_x = image.width - text_width if text_x < 0: text_x = 0 # Check for overlaps if not check_overlap(text_x, candidate_y, text_width, text_height, used_text_regions): text_y = candidate_y # Position 2: Below the bounding box (if above didn't work) if text_y is None: candidate_y = y2 + padding if candidate_y + text_height <= image.height: # Within image bounds # Adjust x position to stay within image bounds text_x = x1 if text_x + text_width > image.width: text_x = image.width - text_width if text_x < 0: text_x = 0 # Check for overlaps if not check_overlap(text_x, candidate_y, text_width, text_height, used_text_regions): text_y = candidate_y # Position 3: To the right of the bounding box if text_y is None: candidate_x = x2 + padding if candidate_x + text_width <= image.width: # Within image bounds candidate_y = y1 if candidate_y + text_height > image.height: candidate_y = image.height - text_height if candidate_y < 0: candidate_y = 0 # Check for overlaps if not check_overlap(candidate_x, candidate_y, text_width, text_height, used_text_regions): text_x = candidate_x text_y = candidate_y # Position 4: To the left of the bounding box if text_y is None: candidate_x = x1 - text_width - padding if candidate_x >= 0: # Within image bounds candidate_y = y1 if candidate_y + text_height > image.height: candidate_y = image.height - text_height if candidate_y < 0: candidate_y = 0 # Check for overlaps if not check_overlap(candidate_x, candidate_y, text_width, text_height, used_text_regions): text_x = candidate_x text_y = candidate_y # Position 5: Find any available space (fallback) if text_y is None: # Try to find space by scanning the image in a grid pattern step_size = 20 found = False for scan_y in range(0, image.height - text_height, step_size): if found: break for scan_x in range(0, image.width - text_width, step_size): if not check_overlap(scan_x, scan_y, text_width, text_height, used_text_regions): text_x = scan_x text_y = scan_y found = True break # Last resort: place at top-left corner (may overlap) if text_y is None: text_x = 0 text_y = 0 # Draw text background rectangle draw.rectangle([text_x, text_y, text_x + text_width, text_y + text_height], fill=color, outline=color) # Draw text draw.text((text_x, text_y), text, fill='white', font=font) # Add this text region to used regions to prevent future overlaps used_text_regions.append((text_x, text_y, text_x + text_width, text_y + text_height)) print(f"[CONSOLE] Annotated screenshot created with {deceptive_count} deceptive patterns and {non_deceptive_count} non-deceptive elements highlighted") # Save annotated image to temporary file if eval_dir: # Create in the managed temp directory that will be cleaned up temp_filename = os.path.join(eval_dir, "annotated_screenshot.png") annotated_image.save(temp_filename) return temp_filename else: # Fallback to system temp directory temp_file = tempfile.NamedTemporaryFile(suffix='.png', delete=False) annotated_image.save(temp_file.name) return temp_file.name except Exception as e: print(f"[CONSOLE] Error creating annotated screenshot: {e}") print(f"[CONSOLE] Falling back to original image: {image_path}") # Return the original image path as fallback return image_path
# Create the Gradio interfacedef create_interface(): global scheduler, dataset_dir, jsonl_path with gr.Blocks(title="Deceptive Pattern Detector", theme=gr.themes.Soft()) as demo: gr.HTML(""" <div style="text-align: center; margin-bottom: 30px;"> <h1>🔍 Deceptive Pattern Detector</h1> <p style="font-size: 18px; color: #666;"> Enter a website URL to analyze for deceptive design patterns </p> <div style="margin-top: 12px;"> <a href="https://arxiv.org/abs/2411.07441" target="_blank" rel="noopener noreferrer" aria-label="Read our arXiv paper" style="display: inline-block; padding: 10px 14px; border-radius: 999px; background: #2563eb; color: white; text-decoration: none; font-weight: 600; box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);"> 📄 Read our paper on arXiv </a> </div> </div> """) # How to Use section - collapsible accordion with tab format with gr.Tabs(): with gr.TabItem("🔒 Privacy Policy"): gr.HTML(""" <div style="padding: 20px; background-color: var(--block-background-fill); border-radius: 8px; border-left: 4px solid #28a745; border: 1px solid var(--border-color-primary);"> <div style="display: flex; gap: 20px; flex-wrap: wrap; align-items: stretch;"> <!-- Left Column: Privacy Highlights --> <div style="flex: 1; min-width: 300px; display: flex; flex-direction: column;"> <div style="margin-bottom: 16px; padding: 16px; background-color: var(--block-background-fill); border-radius: 6px; border: 1px solid #10b981; opacity: 0.9;"> <div style="margin-bottom: 12px;"> <strong style="color: #10b981;">🔐 API Keys:</strong> <span style="color: var(--body-text-color); font-size: 14px; line-height: 1.6;">We <strong style="color: #dc2626;">NEVER</strong> save or store your Gemini API keys. They are only used temporarily in memory during your analysis session and are immediately discarded.</span> </div> <div style="margin-bottom: 0;"> <strong style="color: #8b5cf6;">🚫 No PII Storage:</strong> <span style="color: var(--body-text-color); font-size: 14px; line-height: 1.6;">We do not store any Personally Identifiable Information (PII), including API keys, user identifiers, or sensitive data from analyzed websites.</span> </div> </div> </div> <!-- Right Column: Data Usage --> <div style="flex: 1; min-width: 300px; display: flex; flex-direction: column; gap: 12px;"> <div style="padding: 16px; background-color: var(--block-background-fill); border-radius: 6px; border: 1px solid #f59e0b; opacity: 0.9; flex-grow: 1;"> <strong style="color: #f59e0b;">🌐 Website URLs & Classifications:</strong> <ul style="margin: 8px 0; padding-left: 20px; color: var(--body-text-color); font-size: 14px; line-height: 1.6;"> <li style="margin-bottom: 6px;">We <strong style="color: #f59e0b;">may</strong> save the websites you analyze (URLs only) and their corresponding deceptive pattern classifications</li> <li style="margin-bottom: 6px;">This data helps us improve our detection system and fine-tune our framework</li> <li style="margin-bottom: 6px;">No personal information is linked to this data</li> <li>This data is used solely for research and system improvement purposes</li> </ul> </div> </div> </div> <div style="margin-top: 20px; padding: 15px; background-color: var(--block-background-fill); border-radius: 6px; border: 1px solid #10b981; text-align: center;"> <strong style="color: #10b981;">✅ Summary:</strong> <span style="color: var(--body-text-color); font-size: 14px;">Your API keys are never stored. Anonymized URL and classification data may be retained for system improvement.</span> </div> </div> """) with gr.TabItem("ℹ️ How to Use"): gr.HTML(""" <div style="padding: 20px; background-color: var(--block-background-fill); border-radius: 8px; border-left: 4px solid #2196F3; border: 1px solid var(--border-color-primary);"> <div style="display: flex; gap: 20px; flex-wrap: wrap; align-items: stretch;"> <!-- Left Column: Steps --> <div style="flex: 1; min-width: 300px; display: flex; flex-direction: column;"> <ol style="margin: 0; color: var(--body-text-color); line-height: 1.6; flex-grow: 1;"> <li style="margin-bottom: 12px;"><strong>Enter URL:</strong> Provide the website URL you want to analyze (must start with http:// or https://)</li> <li style="margin-bottom: 12px;"><strong>API Key:</strong> Enter your Google Gemini API key (get a free one at <a href="https://makersuite.google.com/app/apikey" target="_blank" style="color: #2196F3;">Google AI Studio</a>). We may make 1-2 Gemini-2.5-Pro API calls per analysis.</li> <li style="margin-bottom: 12px;"><strong>Analyze:</strong> Click the analyze button and watch as the screenshot appears and the analysis runs</li> <li style="margin-bottom: 12px;"><strong>Review:</strong> The annotated screenshot will show all elements with colored bounding boxes (light green for non-deceptive, various colors for deceptive patterns). Rerun the analysis if the detailed results and annotation mismatch.</li> <li style="margin-bottom: 12px;"><strong>Note:</strong> E2E Analysis time may range from <5 sec to 5 mins based on various factors such as cloud infrastructure, demand, amount of text on page</li> </ol> </div> <!-- Right Column: Disclaimer and Technical Info --> <div style="flex: 1; min-width: 300px; display: flex; flex-direction: column; gap: 12px;"> <div style="padding: 12px; background-color: var(--block-background-fill); border-radius: 4px; border: 1px solid var(--border-color-accent); opacity: 0.9; flex-grow: 1;"> <strong style="color: #ff9800;">⚠️ Disclaimer:</strong> <span style="color: var(--body-text-color); font-size: 14px; line-height: 1.6;">This tool uses AI analysis and may not catch all deceptive patterns or may flag legitimate design elements. Use as a supplementary guide only.</span> </div> <div style="padding: 12px; background-color: var(--block-background-fill); border-radius: 4px; border: 1px solid var(--border-color-accent); opacity: 0.9; flex-grow: 1;"> <strong style="color: var(--body-text-color);">📷 Screenshot Method:</strong> <ul style="margin: 8px 0; padding-left: 20px; color: var(--body-text-color); font-size: 14px; line-height: 1.6;"> <li style="margin-bottom: 6px;"><strong>Selenium WebDriver:</strong> Automatic screenshots using Chrome in headless mode (~1280x1080)</li> <li><span style="color: #dc2626; font-weight: bold;">Static capture of front page only (no scrolling), with 5 second wait from initial page load</span></li> </ul> </div> </div> </div> </div> """) with gr.Row(): with gr.Column(scale=2): # Input section gr.Markdown("### 🌐 Website Analysis") # with gr.Tabs(): # with gr.TabItem("📱 URL Analysis"): url_input = gr.Textbox( type="text", label="Website URL (Required)", placeholder="https://example.com" )
gemini_api_key = gr.Textbox( type="password", label="Gemini API Key (Required)", placeholder="Enter your Google Gemini API key...", info='Create your free API key by visiting <a href="https://makersuite.google.com/app/apikey" target="_blank" style="color: #2196F3;">Google AI Studio</a>' ) # Expandable guide for getting API key with gr.Accordion("❓ How to get a free Gemini API key (Step-by-step guide)", open=False): gr.HTML(""" <div style="padding: 15px; background-color: var(--block-background-fill); border-radius: 8px; border-left: 4px solid #4CAF50;"> <h4 style="color: var(--body-text-color); margin-top: 0; margin-bottom: 15px;">🔑 Get Your Free Google Gemini API Key:</h4> <div style="margin-bottom: 20px;"> <ol style="color: var(--body-text-color); line-height: 1.8; margin: 0; padding-left: 20px;"> <li style="margin-bottom: 10px;"> <strong>Visit Google AI Studio:</strong> Go to <a href="https://makersuite.google.com/app/apikey" target="_blank" style="color: #2196F3; text-decoration: underline;"> https://makersuite.google.com/app/apikey </a> </li> <li style="margin-bottom: 10px;"> <strong>Sign in:</strong> Use your Google account to sign in (create one if needed) </li> <li style="margin-bottom: 10px;"> <strong>Create API Key:</strong> Click the "Create API Key" button </li> <li style="margin-bottom: 10px;"> <strong>Select Project:</strong> Choose an existing Google Cloud project or create a new one </li> <li style="margin-bottom: 10px;"> <strong>Copy Key:</strong> Once generated, copy the API key to your clipboard </li> <li style="margin-bottom: 10px;"> <strong>Paste Here:</strong> Paste the API key into the field above and start analyzing! </li> </ol> </div> <div style="padding: 12px; background-color: var(--background-fill-secondary); border-radius: 6px; border: 1px solid var(--border-color-accent);"> <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;"> <span style="font-size: 16px;">💡</span> <strong style="color: var(--body-text-color);">Pro Tips:</strong> </div> <ul style="color: var(--body-text-color); font-size: 14px; line-height: 1.6; margin: 0; padding-left: 20px;"> <li style="margin-bottom: 6px;">This tool typically uses 1-2 API calls per analysis</li> <li>Your API key is never <strong>STORED</strong> by this application</li> </ul> </div> </div> """)
analyze_url_btn = gr.Button( "🔍 Analyze Website URL", variant="primary", size="lg" )
# Status moved to left column gr.Markdown("### 📊 Analysis Status") status_text = gr.Textbox( label="Status", value="Ready to analyze...", lines=2, interactive=False ) # Results display moved to left column results_display = gr.HTML( value="<div style='text-align: center; padding: 40px; color: var(--body-text-color); opacity: 0.7;'>Enter a URL and click analyze to see results here.</div>" ) results_dataframe = gr.Dataframe( label="Detailed Results (Scroll right to see all columns)", visible=False ) with gr.Column(scale=3): # Screenshot section - only screenshot in right column gr.Markdown("### 📷 Website Screenshot") # Placeholder container for screenshot screenshot_placeholder = gr.HTML( value=""" <div style=" border: 2px dashed var(--border-color-primary); border-radius: 12px; padding: 60px 20px; text-align: center; background-color: var(--block-background-fill); background-image: radial-gradient(circle at 20% 50%, var(--border-color-accent) 0%, transparent 50%), radial-gradient(circle at 80% 50%, var(--border-color-accent) 0%, transparent 50%); background-size: 100px 100px; background-position: 0 0, 50px 50px; min-height: 400px; display: flex; flex-direction: column; justify-content: center; align-items: center; opacity: 0.8; "> <div style=" background-color: var(--block-background-fill); padding: 20px 30px; border-radius: 8px; border: 1px solid var(--border-color-primary); backdrop-filter: blur(10px); "> <h3 style=" color: var(--body-text-color); margin: 0 0 10px 0; font-size: 20px; ">📷 Screenshot Preview Area</h3> <p style=" color: var(--body-text-color); margin: 0; opacity: 0.8; font-size: 16px; line-height: 1.5; "> Website screenshots will appear here during analysis.<br> <span style="font-size: 14px; opacity: 0.7;"> Original screenshot → Annotated with deceptive pattern highlights </span> </p> </div> </div> """, visible=True ) screenshot_display = gr.Image( label="Website Screenshot", visible=False, interactive=False ) # Event handlers def handle_url_analysis(url, api_key): """Handle URL analysis with screenshot capture.""" print(f"[CONSOLE] handle_url_analysis called with URL: {url}") print(f"[CONSOLE] API key provided: {'Yes' if api_key else 'No'}") eval_dir_for_cleanup = None # Track eval_dir for cleanup try: print(f"[CONSOLE] Starting analysis generator for URL: {url}") # Clear any previous error messages at the start of new analysis yield ( "🚀 Starting new analysis...", gr.update(visible=True), # Show placeholder initially gr.update(visible=False), # Hide screenshot initially "<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Preparing analysis...</div>", # Clear previous errors gr.update(visible=False) # Hide dataframe ) analysis_generator = take_screenshot_and_process(url, api_key) final_result = None final_image = None original_image = None # Track original screenshot separately for dataset upload print(f"[CONSOLE] Processing generator results...") for result_tuple in analysis_generator: if len(result_tuple) == 4: dataframe_result, status_update, image_path, eval_dir = result_tuple eval_dir_for_cleanup = eval_dir # Store for cleanup if dataframe_result is None: # Progress update - show screenshot if available and clear any previous error messages if image_path: # Store the first image as original (before annotation) if original_image is None: original_image = image_path final_image = image_path # Update the current image for display yield ( status_update, gr.update(visible=False), # Hide placeholder gr.update(value=image_path, visible=True, label="📷 Original Screenshot"), # Show original screenshot "<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errors gr.update(visible=False) ) else: yield ( status_update, gr.update(visible=True), # Keep placeholder visible gr.update(visible=False), # Hide screenshot "<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Analysis in progress...</div>", # Clear previous errors gr.update(visible=False) ) else: print(f"[CONSOLE] Received final result with {len(dataframe_result)} rows") final_result = dataframe_result final_status = status_update final_image = image_path # This will be the annotated image for display # Store the first image as original if not already set if original_image is None: original_image = image_path # Clear any previous errors when we get successful results yield ( final_status, gr.update(visible=False), # Hide placeholder gr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False), "<div style='text-align: center; padding: 20px; color: var(--body-text-color); opacity: 0.7;'>Processing results...</div>", # Clear previous errors gr.update(visible=False) ) break # Generator approach provides real-time notifications automatically if final_result is not None: print(f"[CONSOLE] Creating result display HTML") results_html = create_result_display(final_result) print(f"[CONSOLE] Yielding final results to UI")
save_url = url.lower().replace("http://", "").replace("https://", "").strip().replace("www.", "") \ .replace(".", "_x01x_") \ .replace("/", "_x02x_") \ .replace("-", "_x03x_") \ .replace("=", "_x04x_") \ .replace("?", "_x05x_") \ .replace("&", "_x06x_") \ .replace("%", "_x07x_") \ .replace(":", "_x08x_") \ .replace("#", "_x09x_") \ .replace("'", "_x10x_") \ .replace('"', "_x11x_") \ .replace("*", "_x12x_") \ .replace("<", "_x13x_") \ .replace(">", "_x14x_") \ .replace("|", "_x15x_") save_url = save_url + "__" + str(uuid.uuid4()).replace("-", "_") save_dict = { save_url: final_result }
# Create DataFrame for image dataset with "id" and "image" columns # Use original screenshot (not annotated) for dataset upload dataset_image_path = original_image if original_image else final_image annotated_image_path = final_image if final_image else original_image print(f"[CONSOLE] Using image for dataset upload: {dataset_image_path} (original: {original_image}, final: {final_image})") print(f"[CONSOLE] Using annotated image for display: {annotated_image_path} (original: {original_image}, final: {final_image})") if dataset_image_path and os.path.exists(dataset_image_path) and annotated_image_path and os.path.exists(annotated_image_path): try: # Load the original image using PIL pil_image = Image.open(dataset_image_path) pil_final = Image.open(annotated_image_path) # Convert to RGB if needed (removes alpha channel if present) if pil_image.mode != 'RGB': pil_image = pil_image.convert('RGB')
if pil_final.mode != 'RGB': pil_final = pil_final.convert('RGB')
image_df = pd.DataFrame([{"id": save_url, "image": pil_image, "annotated_image": pil_final}]) print(f"[CONSOLE] Loaded original image for dataset: {dataset_image_path} -> PIL Image {pil_image.size}") except Exception as e: print(f"[CONSOLE] Error loading image {dataset_image_path}: {e}") # Fallback to path if image loading fails image_df = pd.DataFrame([{"id": save_url, "image": dataset_image_path, "annotated_image": annotated_image_path}]) else: print(f"[CONSOLE] Warning: Image path not found or invalid: {dataset_image_path}") image_df = pd.DataFrame([{"id": save_url, "image": None, "annotated_image": None}])
dataset_upload.update_dataset_with_new_splits(save_dict) dataset_upload.update_dataset_with_new_images(image_df, scheduler=scheduler, dataset_dir=dataset_dir, jsonl_path=jsonl_path) # Show final results with annotated screenshot yield ( final_status, gr.update(visible=False), # Hide placeholder gr.update(value=final_image, visible=True, label="🎯 Annotated Screenshot (Analysis Complete)") if final_image else gr.update(visible=False), results_html, gr.update(value=final_result, visible=True) )
# Clean up temporary files after successful display # Add small delay to let frontend finish loading images before cleanup time.sleep(5) # Give frontend time to load the images cleanup_temp_directory(eval_dir_for_cleanup)
else: print(f"[CONSOLE] No final result generated, analysis failed") # Clean up temp files even on failure cleanup_temp_directory(eval_dir_for_cleanup) yield ( "❌ Analysis failed - no results generated", gr.update(visible=True), # Show placeholder again gr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset label "<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>Analysis failed. Please check your Gemini API key and try again.</div>", gr.update(visible=False) ) except Exception as e: print(f"[CONSOLE] Exception in handle_url_analysis: {str(e)}") print(f"[CONSOLE] Exception type: {type(e).__name__}") # Clean up temp files on exception cleanup_temp_directory(eval_dir_for_cleanup) error_msg = f"❌ Error: {str(e)}" yield ( error_msg, gr.update(visible=True), # Show placeholder again gr.update(visible=False, label="Website Screenshot"), # Hide screenshot and reset label f"<div style='color: #ef4444; text-align: center; background-color: var(--block-background-fill); padding: 15px; border-radius: 8px; border: 1px solid #ef4444; opacity: 0.9;'>{error_msg}</div>", gr.update(visible=False) ) if e.__class__ == gr.exceptions.Error: raise e # Connect the analyze buttons print(f"[CONSOLE] Setting up button click handlers") analyze_url_btn.click( fn=handle_url_analysis, inputs=[url_input, gemini_api_key], outputs=[status_text, screenshot_placeholder, screenshot_display, results_display, results_dataframe], show_progress="full" ) return demo
# Create unique directory for this session using temp directorysession_id = str(uuid.uuid4())[:8]temp_base = Path(tempfile.gettempdir()) / "deceptive_pattern_images"dataset_dir = temp_base / f"{session_id}"dataset_dir.mkdir(parents=True, exist_ok=True)jsonl_path = dataset_dir / "metadata.jsonl"
scheduler = CommitScheduler( repo_id=os.environ["IMAGE_REPO_ID"], repo_type="dataset", folder_path=dataset_dir, path_in_repo=dataset_dir.name, token=os.environ["HF_TOKEN"], every=1)
# Create and launch the interfaceif __name__ == "__main__": # import torch # # print(f"Is CUDA available: {torch.cuda.is_available()}") # print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
from py_files.utils import decrypt_system_prompts
if not decrypt_system_prompts(): print(f"[CONSOLE] Failed to decrypt system prompts, exiting...") exit(1)
print(f"[CONSOLE] ===== STARTING GRADIO APPLICATION =====") print(f"[CONSOLE] Creating Gradio interface...") demo = create_interface() print(f"[CONSOLE] Interface created successfully") print(f"[CONSOLE] Launching server on 0.0.0.0:7860...") demo.queue().launch(server_name="0.0.0.0", server_port=7860)123version https://git-lfs.github.com/spec/v1oid sha256:2c917fdc79430e67dc9dd236b3377998a0239f6c59db74d17be6fa9ac0b93648size 33596919123version https://git-lfs.github.com/spec/v1oid sha256:ce60b06896e9d42039041c11e4aa394d26cf0bce09ac94238864d6e94a1b1029size 33596919123version https://git-lfs.github.com/spec/v1oid sha256:839c7f6337f3fab6828708e5f12b109d8b210078fe1d2e9b6238e1dd3d4564casize 335969191chromium-driver1# Empty init file to make this a Python package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""Bounding box clustering module for grouping nearby text elements.Copied from the original with minimal modifications for HuggingFace Spaces."""
from math import sqrt, distimport extcolorsfrom py_files.pycolor import find
class Node: def __init__(self, data=None, x1=None, y1=None, x2=None, y2=None, font_size=None, children=None): if children is None: children = [] self.data = data self.top_left_x = min(int(x1), int(x2)) if x1 is not None and x2 is not None else None self.top_left_y = min(int(y1), int(y2)) if y1 is not None and y2 is not None else None self.bottom_right_x = max(int(x1), int(x2)) if x1 is not None and x2 is not None else None self.bottom_right_y = max(int(y1), int(y2)) if y1 is not None and y2 is not None else None
self.font_size = abs(self.bottom_right_y - self.top_left_y) if not font_size else font_size
self.children = children
def add_child(self, child): child_top_left_x = child.top_left_x child_top_left_y = child.top_left_y child_bottom_right_x = child.bottom_right_x child_bottom_right_y = child.bottom_right_y self.top_left_x = min(self.top_left_x, child_top_left_x) self.top_left_y = min(self.top_left_y, child_top_left_y) self.bottom_right_x = max(self.bottom_right_x, child_bottom_right_x) self.bottom_right_y = max(self.bottom_right_y, child_bottom_right_y) self.data += " " + child.data self.children.append(child) self.font_size = (max(self.font_size, 0) + max(child.font_size, 0)) // 2
def get_data(self): return self.data
def __repr__(self): return f'Node({self.data}, size: {self.font_size}, {self.top_left_x}, {self.top_left_y}, {self.bottom_right_x}, {self.bottom_right_y}, {self.children})'
class ImageNode(Node): def __init__(self, category=None, top_left_x=None, top_left_y=None, bottom_right_x=None, bottom_right_y=None, text=""): super().__init__(data=None, top_left_x=top_left_x, top_left_y=top_left_y, bottom_right_x=bottom_right_x, bottom_right_y=bottom_right_y) self.category = category self.text = text
def get_boundaries(self): return self.top_left_x, self.top_left_y, self.bottom_right_x, self.bottom_right_y
def get_text(self): return self.text
def set_text(self, text): self.text = text
def get_category(self): return self.category
def __repr__(self): return f'ImageNode({self.text}, {self.top_left_x}, {self.top_left_y}, {self.bottom_right_x}, {self.bottom_right_y})'
def distance_between_parallel_lines(pt1, pt2, pt3, pt4): x1, y1 = pt1 x2, y2 = pt2 x3, y3 = pt3
numerator = abs((y2 - y1) * x3 - (x2 - x1) * y3 + x2 * y1 - y2 * x1) denominator = sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
if denominator == 0: return None
return numerator / denominator
def create_node_lines(node): top_left = (node.top_left_x, node.top_left_y) top_right = (node.bottom_right_x, node.top_left_y) bottom_left = (node.top_left_x, node.bottom_right_y) bottom_right = (node.bottom_right_x, node.bottom_right_y)
return { "left_line": [top_left, bottom_left], "right_line": [top_right, bottom_right], "top_line": [top_left, top_right], "bottom_line": [bottom_left, bottom_right], }
def rect_distance(x1, y1, x1b, y1b, x2, y2, x2b, y2b): left = x2b < x1 right = x1b < x2 bottom = y2b < y1 top = y1b < y2 if top and left: return dist((x1, y1b), (x2b, y2)) elif left and bottom: return dist((x1, y1), (x2b, y2b)) elif bottom and right: return dist((x1b, y1), (x2, y2b)) elif right and top: return dist((x1b, y1b), (x2, y2)) elif left: return x1 - x2b elif right: return x2 - x1b elif bottom: return y1 - y2b elif top: return y2 - y1b else: # rectangles intersect return 0
def distance_between_nodes(node1, node2): return rect_distance(node1.top_left_x, node1.top_left_y, node1.bottom_right_x, node1.bottom_right_y, node2.top_left_x, node2.top_left_y, node2.bottom_right_x, node2.bottom_right_y)
class QuadTree: def __init__(self, root=None, max_dist=5): self.root = root if isinstance(root, Node) else Node(None, 0, 0, 0, 0) self.max_dist = max_dist
def insert(self, node: Node, parent=None): if parent is None: parent = self.root
if len(parent.children) == 0: parent.children.append(node) return
min_dist = float('inf') min_child = None for child in parent.children: _dist = distance_between_nodes(node, child) if _dist < min_dist: min_dist = _dist min_child = child
if min_dist <= self.max_dist: min_child.add_child(node) return True else: parent.children.append(node) return False
def get_root(self): return self.root
def get_children(self, data=False): boxes = [] datas = [] for child in self.root.children: boxes.append([child.top_left_x, child.top_left_y, child.bottom_right_x, child.bottom_right_y]) datas.append(child.data) if data: return datas, boxes return boxes
def get_children_nodes(self): return self.root.children
def get_dataframe(self, image): import pandas as pd
def custom_sort(row): x, y = row return (y, x)
data = [] for child in self.root.children: x1, y1, x2, y2 = child.top_left_x, child.top_left_y, child.bottom_right_x + 3, child.bottom_right_y + 3 try: img_crop = image.crop((x1, y1, x2, y2)) colors, pixel_count = extcolors.extract_from_image(img_crop) # Get background and font colors bg_color = colors[0][0] if colors else (255, 255, 255) font_color = colors[-1][0] if len(colors) > 1 else (0, 0, 0) data.append([ child.data, (child.top_left_x, child.top_left_y), (child.bottom_right_x, child.bottom_right_y), child.font_size, f"{find(bg_color)}, (RGB: {bg_color[0]}, {bg_color[1]}, {bg_color[2]})", f"{find(font_color)}, (RGB: {font_color[0]}, {font_color[1]}, {font_color[2]})" ]) except Exception as e: # Fallback for color extraction errors data.append([ child.data, (child.top_left_x, child.top_left_y), (child.bottom_right_x, child.bottom_right_y), child.font_size, "white, (RGB: 255, 255, 255)", "black, (RGB: 0, 0, 0)" ]) df = pd.DataFrame(data, columns=["Text", "Top Co-ordinates", "Bottom Co-ordinates", "Font Size", "Background Color", "Font Color"]) df = df.sort_values(by="Top Co-ordinates", key=lambda x: x.apply(custom_sort))
return df
def __repr__(self): repr = "" for c in self.root.children: repr += f'Node({c.data}, size: {c.font_size}, {c.top_left_x}, {c.top_left_y}, {c.bottom_right_x}, {c.bottom_right_y})\n' return repr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237import jsonimport osimport tempfileimport timeimport uuidfrom pathlib import Path
import datasetsimport pandas as pdfrom datasets import Imagefrom huggingface_hub import repo_exists, CommitScheduler
def update_dataset_with_new_splits(new_splits: dict, process_name: str = "Main"): """ Add new splits to a regular HuggingFace dataset without downloading existing data. This function pushes individual splits to the Hub using the split parameter, which preserves all existing splits and only adds/updates the specified ones. Key Features: - No downloading of existing dataset required - Existing splits are preserved (not overwritten) - Each split is pushed individually using dataset.push_to_hub(split="name") - Efficient for large datasets with many splits Args: new_splits: dict of {split_name: DataFrame} - splits to add/update process_name: Name for logging and commit messages Example: new_splits = { "validation_2024": val_df, "test_batch_1": test_df, "custom_split": custom_df } update_dataset_with_new_splits(new_splits) """ repo_id = os.environ["REPO_ID"] hf_token = os.environ["HF_TOKEN"] print(f"\n[{process_name}] Starting dataset splits update process...")
# --- Start of Critical Section --- if not repo_exists(repo_id, repo_type="dataset", token=hf_token): print(f"[{process_name}] Repository {repo_id} not found. Cannot update.") return
# Skip downloading existing dataset - we'll push only new splits print(f"[{process_name}] Preparing to push {len(new_splits)} new splits individually...") # Prepare each split for individual pushing splits_to_push = [] for split_id, df in new_splits.items(): new_split_dataset = datasets.Dataset.from_pandas(df) splits_to_push.append((split_id, new_split_dataset)) print(f"[{process_name}] Prepared split '{split_id}' with {len(new_split_dataset)} entries.")
# Push individual splits to Hub with Retry Mechanism _push_splits_to_hub(splits_to_push, repo_id, hf_token, process_name) print(f"[{process_name}] Finished pushing new dataset splits to Hub.")
def update_dataset_with_new_images(image_df: pd.DataFrame, process_name: str = "Main", scheduler: CommitScheduler=None, dataset_dir: Path=None, jsonl_path: Path=None): """ Add new images to an image HuggingFace dataset using smart approach: - If dataset is empty/doesn't exist: Create proper HuggingFace dataset - If dataset has data: Use CommitScheduler for efficient incremental updates Key Features: - Automatically detects empty datasets and bootstraps them - Uses CommitScheduler for incremental updates on existing datasets - Saves images as PNG files with unique names - Stores metadata in JSONL format for file-based approach - Thread-safe with scheduler locking Args: image_df: DataFrame with 'id' and 'image' columns (image should be PIL Image objects) process_name: Name for logging and commit messages Example: img_df = pd.DataFrame([{"id": "img1", "image": pil_image}]) update_dataset_with_new_images(img_df) """ print(f"\n[{process_name}] Starting image dataset update...")
# Validate input format for image datasets if not hasattr(image_df, 'columns'): raise ValueError(f"image_df must be a pandas DataFrame with 'id' and 'image' columns, got {type(image_df)}") # Validate required columns required_columns = ['id', 'image', 'annotated_image'] missing_columns = [col for col in required_columns if col not in image_df.columns] if missing_columns: raise ValueError(f"Missing required columns: {missing_columns}. Found columns: {list(image_df.columns)}") print(f"[{process_name}] Validated DataFrame with {len(image_df)} entries and columns: {list(image_df.columns)}")
return _append_images_with_scheduler(image_df, process_name, scheduler, dataset_dir, jsonl_path)
def _append_images_with_scheduler(image_df: pd.DataFrame, process_name: str, scheduler, dataset_dir, jsonl_path): """ Append images to existing dataset using CommitScheduler for efficient incremental updates. """
print(f"[{process_name}] Using CommitScheduler for incremental updates...")
print(f"[IMAGE_SCHEDULER] Created CommitScheduler for {os.environ['IMAGE_REPO_ID']} with local path: {dataset_dir}") # Process each image saved_count = 0 failed_count = 0 for idx, row in image_df.iterrows(): try: image_id = row['id'] image = row['image'] annotated_image = row['annotated_image'] # Optional # Skip if image is None if image is None: print(f"[{process_name}] Skipping image {image_id}: image is None") failed_count += 1 continue
if annotated_image is None: print(f"[{process_name}] Warning: annotated_image is None for {image_id}") failed_count += 1 continue # Generate unique filename unique_filename_orig = f"{uuid.uuid4()}_orig.png" unique_filename_ann = f"{uuid.uuid4()}_ann.png"
image_path_orig = dataset_dir / unique_filename_orig image_path_ann = dataset_dir / unique_filename_ann # Save image and metadata with scheduler with scheduler.lock: # Save image file if hasattr(image, 'save'): # PIL Image object image.save(image_path_orig, format='PNG') elif hasattr(image, 'shape'): # Numpy array from PIL import Image as PILImage PILImage.fromarray(image).save(image_path_orig, format='PNG') else: print(f"[{process_name}] Warning: Unsupported image type for {image_id}: {type(image)}") failed_count += 1 continue
# Save annotated image file if hasattr(annotated_image, 'save'): annotated_image.save(image_path_ann, format='PNG') elif hasattr(annotated_image, 'shape'): from PIL import Image as PILImage PILImage.fromarray(annotated_image).save(image_path_ann, format='PNG') else: print(f"[{process_name}] Warning: Unsupported annotated_image type for {image_id}: {type(annotated_image)}") failed_count += 1 continue # Append metadata to JSONL metadata = { "id": image_id, "file_name": unique_filename_orig, "annotated_file_name": unique_filename_ann }
with jsonl_path.open("a", encoding="utf-8") as f: json.dump(metadata, f, ensure_ascii=False) f.write("\n") saved_count += 1 print(f"[{process_name}] Saved image {saved_count}/{len(image_df)}: {image_id} -> {unique_filename_orig}") except Exception as e: print(f"[{process_name}] Error processing image {image_id}: {e}") failed_count += 1 continue print(f"[{process_name}] Finished image dataset update:") print(f"[{process_name}] - Successfully saved: {saved_count} images") print(f"[{process_name}] - Failed: {failed_count} images") print(f"[{process_name}] - Images will be automatically committed to dataset repository") if saved_count == 0: print(f"[{process_name}] Warning: No images were successfully saved") return saved_count, failed_count
def _push_splits_to_hub(splits_to_push: list, repo_id: str, hf_token: str, process_name: str): """ Helper function to push individual splits to Hub with retry mechanism. Args: splits_to_push: List of (split_name, dataset) tuples repo_id: HuggingFace repository ID hf_token: HuggingFace token process_name: Process name for logging """ max_retries = 5 successful_splits = [] failed_splits = [] for split_name, split_dataset in splits_to_push: print(f"[{process_name}] Pushing split '{split_name}' with {len(split_dataset)} entries...") for attempt in range(max_retries): try: print(f"[{process_name}] Pushing split '{split_name}' (Attempt {attempt + 1}/{max_retries})...") split_dataset.push_to_hub( repo_id=repo_id, split=split_name, # This preserves existing splits token=hf_token, commit_message=f"feat: Add split '{split_name}' from {process_name} with {len(split_dataset)} entries" ) print(f"[{process_name}] Split '{split_name}' pushed successfully on attempt {attempt + 1}.") successful_splits.append(split_name) break # Exit retry loop on success except Exception as e: print(f"[{process_name}] Split '{split_name}' push attempt {attempt + 1} failed: {e}") if attempt < max_retries - 1: wait_time = 5 print(f"[{process_name}] Waiting for {wait_time} seconds before retrying...") time.sleep(wait_time) else: print(f"[{process_name}] All {max_retries} push attempts failed for split '{split_name}'.") failed_splits.append(split_name) # Report results if successful_splits: print(f"[{process_name}] Successfully pushed splits: {successful_splits}") if failed_splits: print(f"[{process_name}] Failed to push splits: {failed_splits}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439"""Gemini AI analysis module for deceptive pattern detection.Updated to match gemini_prompting_to_make_dp_csvs_genai.py structure."""
import pandas as pdimport osimport timeimport csvfrom io import StringIOimport jsonfrom glob import globfrom tqdm.auto import tqdmimport gradio as gr
try: from google import genai from google.genai import types from google.genai.errors import ServerError GENAI_AVAILABLE = Trueexcept ImportError: GENAI_AVAILABLE = False
def check_csv_format(df: pd.DataFrame) -> str: """ Check if the csv file generated is in the correct format as is expected. Expectation is that the csv file has 10 columns and the index is integer. It is also expected that all the cells in the csv file are strings and not null. If the csv file has only one column, it is considered as a bad file. Args: df: pandas DataFrame object that is read from the csv file. Returns: str: A string that indicates the status of the csv """ if 1 < len(df.columns) < 10: return "The CSV file has less than 10 columns." elif len(df.columns) > 10: return "The CSV file has more than 10 columns." elif not isinstance(df.index, pd.core.indexes.range.RangeIndex): return "The CSV file has an incorrect index. Probably issue with the PIPE (|) separation variable." elif len(df.columns) == 1: return "The CSV file has only one column." elif 'Text' in df.columns and not isinstance(df.Text.dtype, object): return "The CSV file has non-string values in the Text column."
else: return "The CSV file is in the correct format."
# analyze_with_gemini function removed - using few_shots_generator instead
def few_shots_generator(eval_dir='./eval', files=None, api_key=None): """ Generator version of few_shots that yields notifications in real-time. Yields: tuple: (status, message) where status is 'notification' or 'result' """ print(f"[CONSOLE] few_shots_generator: Starting analysis...") print(f"[CONSOLE] eval_dir: {eval_dir}") print(f"[CONSOLE] files: {files}") print(f"[CONSOLE] API key provided: {'Yes' if api_key else 'No'}") if not api_key: print(f"[CONSOLE] No API key provided, returning None") yield ('notification', "❌ No API key provided for analysis") raise gr.Error("No API key provided for analysis") # Read system prompt from gradio-demo directory try: system_prompt_path = os.path.join(os.path.dirname(__file__), '..', 'system_prompt.txt') with open(system_prompt_path, 'r', encoding='utf-8') as f: textsi_1 = f.read() print(f"[CONSOLE] System prompt loaded from: {system_prompt_path}") except Exception as e: print(f"[CONSOLE] Failed to load system prompt: {e}") yield ('notification', "❌ Failed to load system prompt") raise gr.Error(f"Failed to load system prompt: {str(e)}") os.makedirs(f"{eval_dir}/gemini_fs", exist_ok=True) print(f"[CONSOLE] Created gemini_fs directory: {eval_dir}/gemini_fs") try: client = genai.Client(api_key=api_key) print(f"[CONSOLE] Gemini client initialized") except Exception as e: error_msg = f"❌ Failed to initialize Gemini client: {str(e)}" yield ('notification', error_msg) print(f"[CONSOLE] Client initialization failed: {e}") raise gr.Error(f"Failed to initialize Gemini client: {str(e)}")
if files is None: files = glob(os.path.join(f"{eval_dir}/csv_with_yolo", "*.csv")) if not isinstance(files, list): files = [files] print(f"[CONSOLE] Processing {len(files)} files")
for f in files: print(f"[CONSOLE] Processing file: {f}") try: data = pd.read_csv(f, index_col=0) data.index = data.index.str.replace('|', '', regex=False) data = data.to_csv() print(f"[CONSOLE] Data loaded and converted to CSV format") except Exception as e: print(f"[CONSOLE] Failed to read the file: {f}, error: {e}") raise gr.Error(f"Failed to read input file: {str(e)}")
try_cnt = 0 while try_cnt < 2: try: try_cnt += 1 yield ('notification', f"🤖 Calling Gemini AI for pattern analysis (attempt {try_cnt})...") if try_cnt == 1: gr.Info("🤖 Starting Gemini analysis...") print(f"[CONSOLE] Attempt {try_cnt} - Calling Gemini API...") response = client.models.generate_content( model='gemini-2.5-pro', contents=data, config=types.GenerateContentConfig( system_instruction=textsi_1, temperature=0, top_p=0.1, top_k=1, max_output_tokens=12288, safety_settings=[ types.SafetySetting(category='HARM_CATEGORY_HARASSMENT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_HATE_SPEECH', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_DANGEROUS_CONTENT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_CIVIC_INTEGRITY', threshold='BLOCK_NONE') ] ) ) yield ('notification', f"✅ Gemini API call successful! Processing results...") gr.Info("✅ Gemini analysis successful!") print(f"[CONSOLE] Gemini API call successful") break except ServerError as e: if try_cnt > 3: error_msg = f"❌ Failed to get response after {try_cnt} attempts" yield ('notification', error_msg) print(f"[CONSOLE] Failed to get response for {f} after {try_cnt} attempts") raise gr.Error(f"Analysis failed after {try_cnt} attempts") wait_msg = f"⚠️ Server error occurred. Retrying attempt {try_cnt + 1}/2 in 60 seconds..." yield ('notification', wait_msg) gr.Warning(f"⚠️ Server error. Retrying in 60 seconds... (attempt {try_cnt + 1}/2)") print(f"[CONSOLE] Server error: {e.message}, sleeping for 60 seconds") print(e) time.sleep(60) continue except Exception as e: # Handle non-server errors (API key issues, quota errors, etc.) error_msg = f"❌ Gemini API error: {str(e.message)}" print(f"[CONSOLE] Non-server error in Gemini API call: {e}") yield 'notification', error_msg raise gr.Error(f"Gemini API error: {str(e.message)}")
try: # Process the response _f = os.path.join(f"{eval_dir}", "gemini_fs", os.path.basename(f)) df = pd.read_csv(StringIO(response.text.replace("```csv", '').replace("```", '').strip()), sep='|') csv_with_yolo = pd.read_csv(f, index_col=0) gemini_cols = df[["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"]] csv_with_yolo.reset_index(inplace=True) final_df = pd.concat([csv_with_yolo, gemini_cols], axis=1) final_df.to_csv(_f, index=False, quoting=csv.QUOTE_ALL) print(f"[CONSOLE] Results saved to: {_f}") # Check if thinking is needed (if any deceptive patterns found) if set(final_df['Deceptive Design Category'].tolist()) != {'non-deceptive'}: yield ('notification', "🧠 Deceptive patterns detected! Running advanced thinking analysis...") gr.Info("🧠 Deceptive patterns found! Running advanced analysis...") print(f"[CONSOLE] Deceptive patterns found, running thinking analysis...") # Use generator version of thinking thinking_result = None for thinking_status, thinking_data in thinking_generator(eval_dir, files=[_f], api_key=api_key): if thinking_status == 'notification': yield ('notification', thinking_data) elif thinking_status == 'result': thinking_result = thinking_data break if thinking_result is not None: yield ('notification', "✅ Advanced thinking analysis completed successfully!") gr.Info("✅ Advanced analysis completed!") print(f"[CONSOLE] Thinking analysis completed, using refined results") final_df = thinking_result else: yield ('notification', "⚠️ Advanced thinking analysis failed, using original results") gr.Warning("⚠️ Advanced analysis failed, using basic results") print(f"[CONSOLE] Thinking analysis failed, using original results") else: yield ('notification', "✅ No deceptive patterns found, analysis complete!") gr.Info("✅ No deceptive patterns detected!") print(f"[CONSOLE] No deceptive patterns found, skipping thinking analysis") yield 'result', final_df return except Exception as e: print(f"[CONSOLE] Error parsing with pipe separator, trying comma: {e}") try: df = pd.read_csv(StringIO(response.text.replace("```csv", '').replace("```", '').strip()), sep=',') csv_with_yolo = pd.read_csv(f, index_col=0) gemini_cols = df[["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"]] csv_with_yolo.reset_index(inplace=True) final_df = pd.concat([csv_with_yolo, gemini_cols], axis=1) final_df.to_csv(_f, index=False, quoting=csv.QUOTE_ALL) print(f"[CONSOLE] Results saved to: {_f} (comma separated)") # Check if thinking is needed if set(final_df['Deceptive Design Category'].tolist()) != {'non-deceptive'}: yield ('notification', "🧠 Deceptive patterns detected! Running advanced thinking analysis...") gr.Info("🧠 Deceptive patterns found! Running advanced analysis...") print(f"[CONSOLE] Deceptive patterns found, running thinking analysis...") # Use generator version of thinking thinking_result = None for thinking_status, thinking_data in thinking_generator(eval_dir, files=[_f], api_key=api_key): if thinking_status == 'notification': yield ('notification', thinking_data) elif thinking_status == 'result': thinking_result = thinking_data break if thinking_result is not None: yield ('notification', "✅ Advanced thinking analysis completed successfully!") gr.Info("✅ Advanced analysis completed!") print(f"[CONSOLE] Thinking analysis completed, using refined results") final_df = thinking_result else: yield ('notification', "⚠️ Advanced thinking analysis failed, using original results") gr.Warning("⚠️ Advanced analysis failed, using basic results") print(f"[CONSOLE] Thinking analysis failed, using original results") else: yield ('notification', "✅ No deceptive patterns found, analysis complete!") gr.Info("✅ No deceptive patterns detected!") print(f"[CONSOLE] No deceptive patterns found, skipping thinking analysis") yield ('result', final_df) return except Exception as e2: error_msg = f"❌ Error parsing Gemini response with both separators: {str(e2)}" yield ('notification', error_msg) print(f"[CONSOLE] FEW_SHOT Error with both separators: {e2}") try: error_file = _f.replace(".csv", "e1.txt") with open(error_file, 'w') as _fs: _fs.write(response.text) print(f"[CONSOLE] Error response saved to: {error_file}") except Exception as e3: print(f"[CONSOLE] Failed to save error response: {e3}") raise gr.Error(f"Failed to parse response: {str(e2)}") yield ('result', None)
def thinking_generator(eval_dir="./eval", files=None, api_key=None): """ Generator version of thinking that yields notifications in real-time. """ print(f"[CONSOLE] thinking_generator: Starting thinking analysis...") print(f"[CONSOLE] eval_dir: {eval_dir}") print(f"[CONSOLE] files: {files}") if not api_key: print(f"[CONSOLE] No API key provided for thinking analysis") raise gr.Error("No API key provided for thinking analysis") # Read thinking system prompt from gradio-demo directory try: thinking_prompt_path = os.path.join(os.path.dirname(__file__), '..', 'system_prompt_thinking.txt') with open(thinking_prompt_path, 'r', encoding='utf-8') as f: textsi_1 = f.read() print(f"[CONSOLE] Thinking system prompt loaded from: {thinking_prompt_path}") except Exception as e: print(f"[CONSOLE] Failed to load thinking system prompt: {e}") raise gr.Error(f"Failed to load thinking system prompt: {str(e)}") os.makedirs(f"{eval_dir}/gemini_fs", exist_ok=True) try: client = genai.Client(api_key=api_key, http_options={'api_version':'v1beta'}) print(f"[CONSOLE] Thinking client initialized with v1beta") except Exception as e: error_msg = f"❌ Failed to initialize thinking client: {str(e)}" print(f"[CONSOLE] Thinking client initialization failed: {e}") raise gr.Error(f"Failed to initialize thinking client: {str(e)}")
if files is None: files = glob(os.path.join(f"{eval_dir}/gemini_fs", "*.csv")) if not isinstance(files, list): files = [files] print(f"[CONSOLE] Processing {len(files)} files for thinking analysis")
for f in files: print(f"[CONSOLE] Thinking analysis for file: {f}") try: data = pd.read_csv(f, index_col=0) data.index = data.index.str.replace('|', '', regex=False) data = data.to_csv() print(f"[CONSOLE] Data prepared for thinking analysis") # Make API call to Gemini with retry logic for thinking analysis try_cnt = 0 response = None while try_cnt < 2: try: try_cnt += 1 yield ('notification', f"🧠 Running advanced thinking analysis (attempt {try_cnt})...") print(f"[CONSOLE] Attempt {try_cnt} - Calling Gemini API for thinking...") response = client.models.generate_content( model='gemini-2.5-pro', contents=data, config=types.GenerateContentConfig( system_instruction=textsi_1, temperature=0, top_p=0.1, top_k=1, max_output_tokens=65536, safety_settings=[ types.SafetySetting(category='HARM_CATEGORY_HARASSMENT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_HATE_SPEECH', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_DANGEROUS_CONTENT', threshold='BLOCK_NONE'), types.SafetySetting(category='HARM_CATEGORY_CIVIC_INTEGRITY', threshold='BLOCK_NONE') ] ) ) yield ('notification', f"✅ Advanced thinking analysis API call successful!") print(f"[CONSOLE] Thinking API call successful") break except ServerError as e: if try_cnt > 3: error_msg = f"❌ Failed to complete thinking analysis after {try_cnt} attempts" yield ('notification', error_msg) print(f"[CONSOLE] Failed to get thinking response after {try_cnt} attempts") raise gr.Error(f"Advanced analysis failed after {try_cnt} attempts") wait_msg = f"⚠️ Server error in thinking analysis. Retrying attempt {try_cnt + 1}/2 in 60 seconds..." yield ('notification', wait_msg) gr.Warning(f"⚠️ Thinking server error. Retrying in 60s... (attempt {try_cnt + 1}/2)") print(f"[CONSOLE] Server error in thinking analysis: {e.message}, sleeping for 60 seconds") print(e) time.sleep(60) continue except Exception as e: # Handle non-server errors in thinking analysis error_msg = f"❌ Thinking analysis API error: {str(e)}" yield ('notification', error_msg) print(f"[CONSOLE] Non-server error in thinking API call: {e}") raise gr.Error(f"Thinking analysis API error: {str(e)}") output_csv = "" thought_txt = "" for part in response.candidates[0].content.parts: if part.thought == True: thought_txt = part.text print(f"[CONSOLE] Extracted thought text ({len(thought_txt)} chars)") else: output_csv = part.text print(f"[CONSOLE] Extracted output CSV ({len(output_csv)} chars)")
_f = os.path.join(f"{eval_dir}", "gemini_fs", os.path.basename(f)) _f_thought = os.path.join(f"{eval_dir}", "gemini_fs", os.path.basename(f).replace(".csv", "_thinking.txt"))
# Save thinking text with open(_f_thought, 'w', encoding='utf-8') as _f_thought_file: _f_thought_file.write(thought_txt) print(f"[CONSOLE] Thinking text saved to: {_f_thought}")
# Parse and save updated CSV with similar process as main analysis try: # Parse the thinking response CSV df_thinking = pd.read_csv(StringIO(output_csv), sep='|') # Read the original CSV file to get the base data csv_with_yolo = pd.read_csv(f, index_col=0).drop(columns=["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"], errors='ignore') # Extract the thinking analysis columns (similar to main process) thinking_cols = df_thinking[["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"]] # Reset index and concatenate with original data csv_with_yolo.reset_index(inplace=True) final_df = pd.concat([csv_with_yolo, thinking_cols], axis=1) # Save the updated dataframe final_df.to_csv(_f, index=False, quoting=csv.QUOTE_ALL) print(f"[CONSOLE] Thinking results saved to: {_f} (pipe separated)") yield ('result', final_df) # Return the updated dataframe return except Exception as e: print(f"[CONSOLE] Error with pipe separator, trying comma: {e}") try: # Parse the thinking response CSV with comma separator df_thinking = pd.read_csv(StringIO(output_csv), sep=',') # Read the original CSV file to get the base data csv_with_yolo = pd.read_csv(f, index_col=0).drop(columns=["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"], errors='ignore') # Extract the thinking analysis columns (similar to main process) thinking_cols = df_thinking[["Deceptive Design Category", "Deceptive Design Subtype", "Reasoning"]] # Reset index and concatenate with original data csv_with_yolo.reset_index(inplace=True) final_df = pd.concat([csv_with_yolo, thinking_cols], axis=1) # Save the updated dataframe final_df.to_csv(_f, index=False, quoting=csv.QUOTE_ALL) print(f"[CONSOLE] Thinking results saved to: {_f} (comma separated)") yield ('result', final_df) # Return the updated dataframe return except Exception as e2: error_msg = f"❌ Error parsing thinking analysis response with both separators: {str(e2)}" yield ('notification', error_msg) print(f"[CONSOLE] THINKING ERROR with both separators: {e2}") try: error_file = _f.replace(".csv", "e2.txt") with open(error_file, 'w') as _fs: _fs.write(output_csv) print(f"[CONSOLE] Thinking error response saved to: {error_file}") except Exception as e3: print(f"[CONSOLE] Failed to save thinking error response: {e3}") raise gr.Error(f"Failed to parse thinking response: {str(e2)}") except Exception as e: error_msg = f"❌ Error in thinking analysis: {str(e)}" yield ('notification', error_msg) print(f"[CONSOLE] Error in thinking analysis for {f}: {e}") raise gr.Error(f"Thinking analysis error: {str(e)}") yield ('result', None) # Return None if no files processed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""OCR module adapted for HuggingFace Spaces.Uses Google Cloud Vision API for text detection."""
from PIL import Image, ImageDraw, ImageFilterfrom google.cloud import visionimport numpy as npimport ioimport osimport jsonimport tempfilefrom py_files.bounding_clustering import QuadTree, Node
def change_contrast(img, level): """Adjust image contrast for better OCR results.""" factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c): return 128 + factor * (c - 128)
return img.point(contrast)
def get_bounding_box_doc(blk): """Extract bounding box coordinates from document text block.""" vertices = [int(blk.bounding_box.vertices[0].x), int(blk.bounding_box.vertices[0].y), int(blk.bounding_box.vertices[2].x), int(blk.bounding_box.vertices[2].y)] return vertices
def get_text_from_image_doc(img, debug=False, get_response=False, resp=None, max_dist=20): """ Extract text from image using Google Cloud Vision Document Text Detection. Adapted for HuggingFace Spaces environment. """ response = resp if resp is None: # Initialize the client with credentials from environment try: # Try to get credentials from environment variable google_creds = os.environ.get('GOOGLE_CLOUD_CREDENTIALS') if google_creds: # Create temporary credentials file creds_data = json.loads(google_creds) with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: json.dump(creds_data, f) creds_path = f.name os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = creds_path client = vision.ImageAnnotatorClient() # Enhance image contrast for better OCR img = change_contrast(img, 20) # Convert PIL image to bytes imgByteArr = io.BytesIO() img.save(imgByteArr, format='PNG') image = vision.Image(content=imgByteArr.getvalue()) # Perform document text detection response = client.document_text_detection(image=image) # Clean up temporary credentials file if google_creds and 'creds_path' in locals(): try: os.unlink(creds_path) except: pass except Exception as e: # Fallback: create a dummy response for demo purposes print(f"Warning: Google Cloud Vision not available: {e}") response = create_dummy_ocr_response(img)
# Process the response word_boxes = [] if hasattr(response, 'full_text_annotation') and response.full_text_annotation: for page in response.full_text_annotation.pages: for block in page.blocks: if block.confidence < 0.9: continue if debug: print(f"\nBlock confidence: {block.confidence}") print(f"Block box: {get_bounding_box_doc(block)}") words = "" fonts = [] for paragraph in block.paragraphs: for word in paragraph.words: word_text = "".join([symbol.text for symbol in word.symbols]) words += word_text + " " word_bbox = get_bounding_box_doc(word) fonts.append(abs(word_bbox[3] - word_bbox[1])) if debug: print(f"Words: {words}") if fonts: # Only add if we have font information word_boxes.append([words.strip()] + get_bounding_box_doc(block) + [sum(fonts) // len(fonts)]) # If no text was detected, create a minimal entry if not word_boxes: word_boxes.append(["No text detected", 0, 0, 100, 20, 12])
# Create QuadTree for clustering nearby text tree = QuadTree(max_dist=max_dist) for i in range(len(word_boxes)): tree.insert(Node(*tuple(word_boxes[i])))
if get_response: return tree, response return tree, {}
def create_dummy_ocr_response(img): """ Create a dummy OCR response for demo purposes when Google Cloud Vision is not available. This allows the demo to work without requiring actual OCR credentials. """ W, H = img.size # Create a simple mock response object class MockResponse: def __init__(self): self.full_text_annotation = None # For demo purposes, we'll just return an empty response # In a real scenario, you might want to use an alternative OCR library like pytesseract return MockResponse()
def draw_boxes(img, bound, color, width=5): """Draw bounding boxes on image for visualization.""" _img = img.copy() draw = ImageDraw.Draw(_img)
x0 = min(bound[0], bound[2]) - 7 x1 = max(bound[0], bound[2]) + 10 y0 = min(bound[1], bound[3]) - 7 y1 = max(bound[1], bound[3]) + 10
draw.rectangle([x0, y0, x1, y1], outline=color, width=width) return _img, x0, y0, x1, y1
def get_image_with_boxes_doc(image, color='red', width=5, get_response=False, response=None): """Get image with OCR bounding boxes drawn on it.""" tree, resp = get_text_from_image_doc(image, get_response=get_response, resp=response) bxs = tree.get_children(False) for bx in bxs: image, x0, y0, x1, y1 = draw_boxes(image, bx, color, width) if get_response: return image, resp return image123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import base64import os
from cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMACfrom cryptography.hazmat.backends import default_backendfrom cryptography.fernet import Fernet, InvalidToken
def decrypt(password: str, token: bytes) -> bytes | None: """Decrypts a token using a password.""" try: salt = token[:16] encrypted_data = token[16:] kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=480000, backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(password.encode())) f = Fernet(key) return f.decrypt(encrypted_data) except InvalidToken: return None
def decrypt_file(password: str, input_path: str, output_path: str): """Reads an encrypted file, decrypts it, and saves the original content.""" try: with open(input_path, 'rb') as f_in: encrypted_data = f_in.read()
decrypted_data = decrypt(password, encrypted_data)
if decrypted_data is None: print("❌ Decryption failed! Wrong password or corrupted file.") return
with open(output_path, 'wb') as f_out: f_out.write(decrypted_data) print(f"✅ File '{input_path}' decrypted successfully to '{output_path}'.") except FileNotFoundError: print(f"❌ Error: Input file not found at '{input_path}'.") except Exception as e: print(f"❌ An unexpected error occurred during decryption: {e}")
def decrypt_system_prompts() -> bool: """Decrypts system prompts stored in a dictionary.""" password = os.environ.get("PROMPT_PASSWORD") if not password: print("❌ PROMPT_PASSWORD environment variable not set.") return False try: decrypt_file(password, "./system_prompt.enc", "./system_prompt.txt") decrypt_file(password, "./system_prompt_thinking.enc", "./system_prompt_thinking.txt") return True except Exception as e: print(f"❌ An error occurred while decrypting system prompts: {e}") return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370import math# from YoloVal import DetectionValidatorEnsemblefrom argparse import ArgumentParserfrom collections import deque
import cv2import numpy as npimport torchfrom torch import nnfrom ultralytics import YOLOfrom ultralytics.engine.results import Resultsfrom ultralytics.models.yolo.detect import DetectionValidatorfrom ultralytics.nn.autobackend import AutoBackendfrom ultralytics.utils import ops, nms
def do_rectangles_overlap(rect1, rect2, overlap_threshold=0.5): # Rect1 coords x1_min, y1_min, x1_max, y1_max = rect1 # Rect2 coords x2_min, y2_min, x2_max, y2_max = rect2
# Check if one rectangle is to the left of the other if x1_max < x2_min or x2_max < x1_min: return False
# Check if one rectangle is above the other if y1_max < y2_min or y2_max < y1_min: return False
# Find the area of the first rectangle area_rect1 = (x1_max - x1_min) * (y1_max - y1_min) area_rect2 = (x2_max - x2_min) * (y2_max - y2_min)
# Find the coordinates of the intersection rectangle inter_x_min = max(x1_min, x2_min) inter_x_max = min(x1_max, x2_max) inter_y_min = max(y1_min, y2_min) inter_y_max = min(y1_max, y2_max)
# Check if there is no intersection if inter_x_max <= inter_x_min or inter_y_max <= inter_y_min: return False
# Calculate the area of the intersection rectangle inter_area = (inter_x_max - inter_x_min) * (inter_y_max - inter_y_min)
# Calculate the percentage of overlap relative to both rectangles overlap_percentage_1 = inter_area / area_rect1 overlap_percentage_2 = inter_area / area_rect2
# Check for complete containment contained = ((x1_min <= x2_min <= x1_max and x1_min <= x2_max <= x1_max) and (y1_min <= y2_min <= y1_max and y1_min <= y2_max <= y1_max)) or \ ((x2_min <= x1_min <= x2_max and x2_min <= x1_max <= x2_max) and (y2_min <= y1_min <= y2_max and y2_min <= y1_max <= y2_max))
# Return True if the overlap meets the threshold return overlap_percentage_1 >= overlap_threshold or overlap_percentage_2 >= overlap_threshold or contained
import spaces
class YoloEnsemble: def __init__(self, weights: list[str]): self.models = [YOLO(weight) for weight in weights]
@spaces.GPU(duration=10) def predict(self, img_path: str, conf: float = 0.25, verbose: bool = True):
import torch import numpy as np import random
seed = 42 torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
# For full reproducibility, you might also need this torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
predictions = [_model(img_path, conf=conf, verbose=verbose) for _model in self.models]
if len(self.models) > 1: return self.ensemble(predictions) return predictions[0]
def ensemble(self, predictions: list): hits = None orig_shape = None names = None orig_img = None path = None speed = None
for results in predictions: for result in results: _hits = result.boxes.data.unsqueeze(dim=0) if hits is None: hits = _hits else: hits = torch.cat((hits, _hits), dim=1)
if orig_shape is None: orig_shape = result.orig_shape names = result.names orig_img = result.orig_img path = result.path speed = result.speed
# hits = hits.unsqueeze(dim=0) nms_hits = nms.non_max_suppression(hits, conf_thres=0.25, classes=[0, 1, 2, 3, 4, 5, 6]) boxes = deque(nms_hits[0].tolist()) non_overlapping_boxes = [] while len(boxes) > 0: box = boxes.popleft() overlappers = [box] rem = [] for i, b in enumerate(boxes): if do_rectangles_overlap(box[:4], b[:4]): overlappers.append(b) rem.append(i) for _i, _ in enumerate(rem): del boxes[_ - _i] keep_box = sorted(overlappers, key=lambda x: x[4], reverse=True)[0] non_overlapping_boxes.append(keep_box) if len(non_overlapping_boxes) == 0: return [Results(names=names, orig_img=orig_img, path=path, speed=speed)] # result = Results(boxes=torch.Tensor(non_overlapping_boxes).to(nms_hits[0].get_device()), names=names, orig_img=orig_img, path=path, speed=speed) return [Results(boxes=torch.Tensor(non_overlapping_boxes), #.to(nms_hits[0].get_device()), names=names, orig_img=orig_img, path=path, speed=speed)]
class YoloEnsembleAutoBackend: def __init__(self, weights: list[str], val=False, **kwargs): if isinstance(weights, list): self.models = [ # AutoBackend( # weights=weight, # device=kwargs.get('device', None), # dnn=kwargs.get('dnn', False), # data=kwargs.get('data', None), # fp16=kwargs.get('fp16', False), # ) for weight in weights YOLO(weight) for weight in weights ] else: self.models = [ AutoBackend( weights=weights, device=kwargs.get('device', None), dnn=kwargs.get('dnn', False), data=kwargs.get('data', None), fp16=kwargs.get('fp16', False), ) ] model = AutoBackend( weights=weights[0], device=kwargs.get('device', None), dnn=kwargs.get('dnn', False), data=kwargs.get('data', None), fp16=kwargs.get('fp16', False), )
# self.models[0].val()
self.device = kwargs.get('device', None) self.fp16 = model.fp16 self.stride = model.stride self.pt = model.pt self.jit = model.jit self.engine = model.engine self.val = val self.names = model.names
def warmup(self, imgsz=(1, 3, 640, 640)): pass
def eval(self): for model in self.models: model.eval()
def predict(self, imgs, conf=0.25, verbose=True): predictions = [_model(imgs, conf=conf, verbose=verbose) for _model in self.models] predictions = [list(x) for x in zip(*predictions)] if len(self.models) > 1: # return self.ensemble([torch.cat([p[0] for p in predictions], 1)]) return self.ensemble2(predictions) if not self.val: return predictions[0] return predictions[0]
def ensemble(self, predictions: list): final_preds = [] device = None
for ip, results in enumerate(predictions): for ir, result in enumerate(results): device = result.device _array = deque(result.cpu().tolist()) non_overlapping_boxes = [] while len(_array) > 0: box = _array.popleft() overlappers = [box] rem = [] for i, b in enumerate(_array): if do_rectangles_overlap(box[:4], b[:4]): overlappers.append(b) rem.append(i) for _i, _ in enumerate(rem): del _array[_ - _i] keep_box = sorted(overlappers, key=lambda x: x[4], reverse=True)[0] non_overlapping_boxes.append(keep_box)
repeat = int(math.ceil(300 / len(non_overlapping_boxes))) non_overlapping_boxes = non_overlapping_boxes * repeat final_preds.append(non_overlapping_boxes[:300])
_new_preds = torch.tensor(final_preds, device=device)
return _new_preds
def ensemble2(self, predictions: list): final_preds = [] device = None
preds = [] for ip, prediction in enumerate(predictions): # for image i model_preds = [] for ir, result in enumerate(prediction): # for model r's prediction on image i if not device: device = result.boxes.xyxy.device boxes = np.array(result.boxes.xyxy.cpu().tolist()) if len(boxes) == 0: continue _cls = np.array(result.boxes.cls.cpu().tolist()) _cls = _cls.reshape(-1, 1) _conf = np.array(result.boxes.conf.cpu().tolist()) _conf = _conf.reshape(-1, 1) try: np.hstack((boxes, _conf, _cls)) except: breakpoint() boxes = np.hstack((boxes, _conf, _cls)) boxes = boxes.tolist() model_preds.extend(boxes) preds.append(model_preds)
for ip, pred in enumerate(preds): # for image i _array = deque(pred) non_overlapping_boxes = [] while len(_array) > 0: box = _array.popleft() overlappers = [box] rem = [] for i, b in enumerate(_array): if do_rectangles_overlap(box[:4], b[:4]): overlappers.append(b) rem.append(i) for _i, _ in enumerate(rem): del _array[_ - _i] keep_box = sorted(overlappers, key=lambda x: x[4], reverse=True)[0] non_overlapping_boxes.append(keep_box) # increase to 100 if len(non_overlapping_boxes) != 0: repeat = int(math.ceil(100 / len(non_overlapping_boxes))) non_overlapping_boxes = non_overlapping_boxes * repeat final_preds.append(non_overlapping_boxes[:100])
_new_preds = torch.tensor(final_preds, device=device)
# for ip, results in enumerate(predictions): # per_img_preds = [] # for ir, result in enumerate(results): # device = result.boxes.xyxy.device # boxes = np.array(result.boxes.xyxy.cpu().tolist()) # _cls = np.array(result.boxes.cls.cpu().tolist()) # _cls = _cls.reshape(-1, 1) # _conf = np.array(result.boxes.conf.cpu().tolist()) # _conf = _conf.reshape(-1, 1) # # boxes = np.hstack((boxes, _conf, _cls)) # boxes = boxes.tolist() # # _array = deque(boxes) # non_overlapping_boxes = [] # while len(_array) > 0: # box = _array.popleft() # overlappers = [box] # rem = [] # for i, b in enumerate(_array): # if do_rectangles_overlap(box[:4], b[:4]): # overlappers.append(b) # rem.append(i) # for _i, _ in enumerate(rem): # del _array[_ - _i] # keep_box = sorted(overlappers, key=lambda x: x[4], reverse=True)[0] # non_overlapping_boxes.append(keep_box) # # # repeat = int(math.ceil(100 / len(non_overlapping_boxes))) # # non_overlapping_boxes = non_overlapping_boxes * repeat # # final_preds.append(non_overlapping_boxes[:100]) # per_img_preds.extend(non_overlapping_boxes) # # # _new_preds = torch.tensor(final_preds, device=device) return _new_preds
class YoloPreprocess(nn.Module): def __init__(self): super(YoloPreprocess, self).__init__()
def pre_transform(self, img: np.ndarray): img = img shape = len(img), len(img[0]) new_shape = [1280, 1280] r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding dw, dh = np.mod(dw, 32), np.mod(dh, 32) dw /= 2 dh /= 2
if shape[::-1] != new_unpad: # resize img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR) top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) img = cv2.copyMakeBorder( img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114) ) return [img]
def forward(self, im): im = np.stack(self.pre_transform(im)) im = im[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW, (n, 3, h, w) im = np.ascontiguousarray(im) # contiguous # im = torch.from_numpy(im) _im = im / 255
return _im
if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--weights', nargs='+', help="Model paths", required=True) args = parser.parse_args()
# img = cv2.imread('askubuntu2.png') # x = YoloPreprocess() # x(img)
# model = YoloEnsemble(args.weights) # model = YOLO('./train16.pt').to('cuda') # results = model.predict(['askubuntu2.png'], conf=0.7) # for result in results: # boxes = result.boxes # Boxes object for bounding box outputs # masks = result.masks # Masks object for segmentation masks outputs # keypoints = result.keypoints # Keypoints object for pose outputs # probs = result.probs # Probs object for classification outputs # # result.show() # display to screen # result.save(filename='result.jpg')
args = dict(model='./train16.pt', data='dataset/data.yaml') validator = DetectionValidator(args=args) validator()12345678910111213141516171819gradio>=4.44.0pandas==2.0.3numpy==1.24.3Pillow>=10.0.0extcolors==1.0.0google-cloud-vision==3.4.4google-genai>=0.3.0ultralytics>=8.0.196--extra-index-url https://download.pytorch.org/whl/cu113torchtorchvisionpybboxes==0.1.6tqdm>=4.66.1playwright==1.40.0requests>=2.31.0selenium>=4.15.0datasetshuggingface_hub[hf_xet]cryptography12��ެoPt��v�gAAAAABo4AkWwV9Mh02cKBl8q-8O7D3gJF5k2vqltw99VgUgYOWDKaj1RGKEUnSOYM5Rnzeg7FonjdqUF5ZE5rqNPvAWau5MPIsCT9IzkB_LacwkjEUZsDDiUuQHGegLTFwm8ni6vG59L86Xzt9jnWJ-1btNcB2r7CdR_EZHGXceJPPCjWiVdp6Oa2ddFlebuQxR1io1jFvd2QuaZEr6O8oNYtUL_4v4itmMv2pl1tniSymqOcHyosJcEc8-MMzAl5DgEo7f0viRdp6L9_MjEEenXpr4fVKVbtmQhgdDyeZmfC32FVOcGZz4tt9lAZCeTsTT3hu2vJOQrevoy4EXBxYOqe8PS09rL6Nk8_lvvvn4U5fk85HtCR2zqxokIB0lOor4EhqUM4BqqAn3XSJTQeE7Q4WcVx6sEbiL52hg1WkvXVar-eezBwHZw23DZec_E3mjdHYsZ73kQnpi5auGk3AM5WATlqGc_qgynvbz8L8df5hc6xcaZOlHH9xVU0XXCGCuPZ1VSnzLqjvXq7f3XfMTnAPgETMu2YyPyZjbcL02SabNXN2KqBe4jhZ2BDBhTTiZ2yu0YgjE0ZTGSI07l7EAVvL-uKa03eobSrtlrLorKjeoPAALEhCbSr9oouACgcLntkmD8bEyOqguvsMY3io6Z6BxZOriP7010UmQ23AiY46c8E5H050MFe00W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oqB2noIHFrLLvfIIUgj9pgNRX4DM1zCssWBigN5DX-p4SxODCQZAO_kAAXjLc6zSEp1zrCbEMweINUT5Q.gitattributesAdded+35
.gitignoreAdded+62
README.mdAdded+64
app.pyAdded+1156
models/vision/14.ptAdded+3
models/vision/15.ptAdded+3
models/vision/16.ptAdded+3
packages.txtAdded+1
py_files/__init__.pyAdded+1
py_files/bounding_clustering.pyAdded+220
py_files/dataset_upload.pyAdded+237
py_files/gemini_analysis.pyAdded+439
py_files/ocr.pyAdded+157
py_files/pycolor.pyAdded
py_files/utils.pyAdded+60
py_files/yolo.pyAdded+370
requirements.txtAdded+19
system_prompt.encAdded
system_prompt_thinking.encAdded+1