import gradio as gr import requests from PIL import Image import io import os BASE_URL = "https://api.jigsawstack.com/v1" headers = {"x-api-key": os.getenv("")} # ----------------- JigsawStack API Wrappers ------------------ def enhanced_ai_scrape(input_method, url, html, prompts_str, selector, page_pos): def error_response(message): return ( message, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), ) try: # Validate element prompts prompts = [p.strip() for p in prompts_str.split(",") if p.strip()] if not prompts: return error_response("Error: No element prompts provided.") if len(prompts) > 5: return error_response("Error: Maximum 5 element prompts allowed.") payload = { "element_prompts": prompts, "root_element_selector": selector or "main", "page_position": int(page_pos) if str(page_pos).strip().isdigit() else 1 } # Add URL or HTML based on input method if input_method == "URL": if not url or not url.strip(): return error_response("Error: URL is required when using URL input method.") payload["url"] = url.strip() elif input_method == "HTML Content": if not html or not html.strip(): return error_response("Error: HTML content is required when using HTML input method.") payload["html"] = html.strip() response = requests.post(f"{BASE_URL}/ai/scrape", headers=headers, json=payload) response.raise_for_status() result = response.json() if not result.get("success"): return error_response(f"Error: Scraping failed - {result.get('message', 'Unknown error')}") # Extract all the data context = result.get("context", {}) selectors = result.get("selectors", {}) data = result.get("data", []) links = result.get("link", []) current_page = result.get("page_position", 1) total_pages = result.get("page_position_length", 1) # Format pagination info pagination_text = f"Page {current_page} of {total_pages}" if total_pages > 1: pagination_text += f" (Total pages available: {total_pages})" status_text = f"✅ Successfully scraped {len(data)} data items" if context: status_text += f" with {len(context)} context elements" return ( status_text, gr.update(value=context, visible=True if context else False), gr.update(value=selectors, visible=True if selectors else False), gr.update(value=data, visible=True if data else False), gr.update(value=links, visible=True if links else False), gr.update(value=pagination_text, visible=True), ) except requests.exceptions.RequestException as req_err: return error_response(f"Request failed: {str(req_err)}") except Exception as e: return error_response(f"Unexpected error: {str(e)}") # ----------------- Gradio UI ------------------ with gr.Blocks() as demo: gr.Markdown("""
Extract structured data from web pages with advanced AI models.
For more details and API usage, see the documentation.