{ "cells": [ { "cell_type": "code", "execution_count": 101, "id": "5223b1b7", "metadata": {}, "outputs": [], "source": [ "from web2json.preprocessor import *\n", "from web2json.ai_extractor import *\n", "from web2json.postprocessor import *\n", "from web2json.pipeline import *" ] }, { "cell_type": "code", "execution_count": 102, "id": "5ccc96b7", "metadata": {}, "outputs": [], "source": [ "def seed_everything(seed=42):\n", " random.seed(seed)\n", " np.random.seed(seed)\n", " torch.manual_seed(seed)\n", "\n", " if torch.cuda.is_available():\n", " torch.cuda.manual_seed(seed)\n", " torch.cuda.manual_seed_all(seed) # if using multi-GPU\n", "\n", " torch.backends.cudnn.deterministic = True\n", " torch.backends.cudnn.benchmark = False\n", "\n", "seed_everything(44)" ] }, { "cell_type": "code", "execution_count": 103, "id": "ae4e7f03", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import dotenv\n", "dotenv.load_dotenv()" ] }, { "cell_type": "code", "execution_count": 104, "id": "9e6b0eb9", "metadata": {}, "outputs": [], "source": [ "llm = NvidiaLLMClient(config={'api_key': os.getenv('NVIDIA_API_KEY'),'model_name': 'qwen/qwen2.5-7b-instruct'})\n", "reranker = NvidiaRerankerClient(config={'api_key': os.getenv('NVIDIA_API_KEY'),'model_name': \"nv-rerank-qa-mistral-4b:1\"})\n", "# reranker = HFRerankerClient()" ] }, { "cell_type": "code", "execution_count": 105, "id": "114ce917", "metadata": {}, "outputs": [], "source": [ "from pydantic import BaseModel, Field, constr, condecimal\n", "\n", "class ProductModel(BaseModel):\n", " productTitle: constr(min_length=1, max_length=200) = Field(\n", " ...,\n", " title=\"Product Title\",\n", " description=\"The full title of the product\"\n", " )\n", " price: condecimal(gt=0, decimal_places=2) = Field(\n", " ...,\n", " title=\"Product Price\",\n", " description=\"Unit price (must be > 0, two decimal places).\"\n", " )\n", " manufacturer: constr(min_length=1, max_length=1000) = Field(\n", " ...,\n", " title=\"Manufacturer\",\n", " description=\"Name of the product manufacturer.\"\n", " )\n" ] }, { "cell_type": "code", "execution_count": 106, "id": "2d6c1215", "metadata": {}, "outputs": [], "source": [ "url = \"https://www.amazon.com/Instant-Pot-Multi-Use-Programmable-Pressure/dp/B00FLYWNYQ?_encoding=UTF8&content-id=amzn1.sym.2f889ce0-246f-467a-a086-d9a721167240&dib=eyJ2IjoiMSJ9.2EzBddTDEktLY8ckTsraM_cZ6pzKuNkA6y_gLR0-Uz1ekttQU6tuQEcjb8PThy0PfhvxLqeYWh3N7pQrGgRxAWzapVklC_aU6xBzD-3Wwqx3qyQRHsmOhPRsSpeCOIIZqS3SKDowZEPYrGnCbRMt5vxnsYMW-fD-zBbgeoeGYmbsN2U6_HNhLjrpePKCbQPmnZBJ9UhgYE4fE3DVuYm8xlJe9l5GixDLVFtZUq4m5FE.Ol-jiuu9P6mQie0yXLJj-Ht5-TXmIXuRPije85p_YVo&dib_tag=se&keywords=cooker&pd_rd_r=2cede598-f3ae-49ca-8a46-e5945a9c2631&pd_rd_w=2HLSC&pd_rd_wg=ZyUUn&qid=1749508157&sr=8-3\"\n", "schema = ProductModel # pydantic class\n", "\n", "# read html file \n", "# with open(r'C:\\Users\\abdfa\\Desktop\\UNI STUFFING\\GRADUATION PROJECT\\Group Work\\MCP_WEB2JSON\\0000.htm', 'r', encoding='utf-8') as file:\n", "# content = file.read()\n", "\n", "# with open(r'C:\\Users\\abdfa\\Desktop\\UNI STUFFING\\GRADUATION PROJECT\\Group Work\\MCP_WEB2JSON\\Amazon.com_ Instant Pot Duo 7-in-1 Electric Pressure Cooker, Slow Cooker, Rice Cooker, Steamer, Sauté, Yogurt Maker, Warmer & Sterilizer, Includes App With Over 800 Recipes, Stainless Steel, 6 Quart.htm', 'r', encoding='utf-8') as file:\n", "# content = file.read()\n" ] }, { "cell_type": "code", "execution_count": 107, "id": "3bc223d0", "metadata": {}, "outputs": [], "source": [ "prompt_template = \"\"\"\n", "You are a helpful assistant that extracts structured data from web pages.\n", "You will be given a web page and you need to extract the following information:\n", "{content}\n", "\n", "schema: {schema}\n", "Please provide the extracted data in JSON format.\n", "WITH ONLY THE FIELDS THAT ARE IN THE SCHEMA.\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 108, "id": "475fccd2", "metadata": {}, "outputs": [], "source": [ "classification_prompt_template = schema.model_json_schema()" ] }, { "cell_type": "code", "execution_count": 109, "id": "974417de", "metadata": {}, "outputs": [], "source": [ "# classification_prompt_template = \"\"\"\n", "# # HTML Chunk Relevance Classification Prompt\n", "\n", "# You are an HTML content classifier. Your task is to analyze an HTML chunk against a given schema and determine if the content is relevant.\n", "\n", "# ## Instructions:\n", "# 1. Carefully examine the provided HTML chunk\n", "# 2. Compare it against the given schema/criteria\n", "# 3. Determine if the HTML chunk contains content that matches or is relevant to the schema\n", "# 4. Respond with ONLY a JSON object containing a single field \"relevant\" with value 1 (relevant) or 0 (not relevant)\n", "\n", "# ## Input Format:\n", "# **Schema/Criteria:**\n", "# {schema}\n", "\n", "# **HTML Chunk:**\n", "# ```html\n", "# {content}\n", "# ```\n", "\n", "# ## Output Format:\n", "# Your response must be ONLY a valid JSON object with no additional text:\n", "\n", "# ```json\n", "# {{\n", "# \"relevant\": 1\n", "# }}\n", "# ```\n", "\n", "# OR\n", "\n", "# ```json\n", "# {{\n", "# \"relevant\": 0\n", "# }}\n", "# ```\n", "\n", "# ## Classification Rules:\n", "# - Output 1 if the HTML chunk contains content that matches the schema criteria\n", "# - Output 0 if the HTML chunk does not contain relevant content\n", "# - Consider semantic meaning, not just exact keyword matches\n", "# - Look at text content, attributes, structure, and context\n", "# - Ignore purely structural HTML elements (like divs, spans) unless they contain relevant content\n", "# - Be STRICT in your evaluation - only mark as relevant (1) if there is clear, meaningful content that directly relates to the schema\n", "# - Empty elements, placeholder text, navigation menus, headers/footers, and generic UI components should typically be marked as not relevant (0)\n", "# - The HTML chunk does not need to contain ALL schema information, but it must contain SUBSTANTIAL and SPECIFIC content related to the schema\n", "\n", "# CRITICAL: Your entire response MUST be exactly one JSON object. DO NOT include any explanations, reasoning, markdown formatting, code blocks, or additional text. Output ONLY the raw JSON object.\n", "# \"\"\"" ] }, { "cell_type": "code", "execution_count": 110, "id": "58436d65", "metadata": {}, "outputs": [], "source": [ "pre = BasicPreprocessor(config={'keep_tags':True})\n", "# llm = GeminiLLMClient(config={'api_key': os.getenv('GEMINI_API_KEY'),})\n", "# ai = AIExtractor(llm_client=llm ,prompt_template=prompt_template)\n", "ai = LLMClassifierExtractor(reranker=reranker, llm_client=llm, prompt_template=prompt_template, classifier_prompt=classification_prompt_template)\n", "post = PostProcessor()" ] }, { "cell_type": "code", "execution_count": 111, "id": "c4e75e63", "metadata": {}, "outputs": [], "source": [ "html_chunks = [\n", " \"\"\"\n", "
\n", "

Wireless Noise Cancelling Headphones

\n", "

Experience immersive sound with active noise cancellation and long battery life.

\n", " $299.99\n", " \n", "
\n", " \"\"\",\n", "\n", " \"\"\"\n", "
\n", "

Top 5 AI Tools to Try in 2025

\n", "

Artificial intelligence continues to evolve. Here are five tools you should explore in 2025:

\n", " \n", " \n", "
\n", " \"\"\",\n", "\n", " \"\"\"\n", "
\n", "

Top 5 AI Tools to Try in 2025

\n", "

Artificial intelligence continues to evolve. Here are five tools you should explore in 2025:

\n", " \n", " \n", "
\n", " \"\"\",\n", "\n", " \"\"\"\n", "
\n", "

User Review: Amazing Performance!

\n", "

I’ve been using this laptop for a few months and it’s blazing fast. Great for deep learning workloads!

\n", "
Rating: ⭐⭐⭐⭐⭐
\n", " – Sarah M.\n", "
\n", " \"\"\"\n", "]\n" ] }, { "cell_type": "code", "execution_count": 112, "id": "bb4edecf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(html_chunks)" ] }, { "cell_type": "code", "execution_count": 113, "id": "9927a78e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "raw scores [-11.34375 -13.8984375 -14.7578125 -14.7578125]\n", "Sigmoid scores: [1.18431390e-05 9.20417541e-07 3.89729515e-07 3.89729515e-07]\n", "Normalized scores: [1. 0.0463345 0. 0. ]\n", "Filtered pairs:\n", "[(Document(metadata={'relevance_score': -11.34375}, page_content='\\n
\\n

Wireless Noise Cancelling Headphones

\\n

Experience immersive sound with active noise cancellation and long battery life.

\\n $299.99\\n \\n
\\n '), 1.0)]\n" ] } ], "source": [ "output = reranker.rerank(query=classification_prompt_template,passages=html_chunks)" ] }, { "cell_type": "code", "execution_count": 114, "id": "b77015f3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "
\n", "

Wireless Noise Cancelling Headphones

\n", "

Experience immersive sound with active noise cancellation and long battery life.

\n", " $299.99\n", " \n", "
\n", " \n", "--------------------------------------------------------------------------------\n" ] } ], "source": [ "for o in output:\n", " print(o)\n", " print('-'*80)" ] }, { "cell_type": "code", "execution_count": 115, "id": "bb3fa1b0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(output)" ] }, { "cell_type": "code", "execution_count": 116, "id": "c1c43f7c", "metadata": {}, "outputs": [], "source": [ "# ai.extract(chunks=[\"the price is $1000\", \"the title is 'NVIDIA H100 SXM'\"])" ] }, { "cell_type": "code", "execution_count": 117, "id": "9c78eec9", "metadata": {}, "outputs": [], "source": [ "pipe = Pipeline(preprocessor=pre, ai_extractor=ai, postprocessor=post)" ] }, { "cell_type": "code", "execution_count": 118, "id": "92a5fc23", "metadata": {}, "outputs": [], "source": [ "config = {\n", " 'keep_tags': True,\n", "}" ] }, { "cell_type": "code", "execution_count": 119, "id": "f07e1aca", "metadata": {}, "outputs": [], "source": [ "# import os\n", "\n", "# content = \"\"\"\n", "# \n", "# \"\"\"\n", "\n", "# from web2json.ai_extractor import HFRerankerClient, LLMClassifierExtractor, NvidiaLLMClient\n", "\n", "# hf_reranker = HFRerankerClient()\n", "# llm_client = NvidiaLLMClient(config={\"api_key\": os.environ.get('NVIDIA_API_KEY')})\n", "# extractor = LLMClassifierExtractor(\n", "# reranker=hf_reranker,\n", "# llm_client=llm_client,\n", "# prompt_template=\"Extract from: {content} using schema: {schema}\",\n", "# classifier_prompt=\"What is the price?\"\n", "# )\n", "\n", "# # Run using HuggingFace reranker\n", "# result = extractor.extract(content=content, schema=schema, hf=True)\n" ] }, { "cell_type": "code", "execution_count": 120, "id": "79cf2321", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n", "raw scores [-12.40625 -12.453125 -12.46875 -12.5546875 -12.6875 ]\n", "Sigmoid scores: [4.09291105e-06 3.90548374e-06 3.84493506e-06 3.52831186e-06\n", " 3.08949445e-06]\n", "Normalized scores: [1. 0.81321087 0.75286836 0.43732325 0. ]\n", "Filtered pairs:\n", "[(Document(metadata={'relevance_score': -12.40625}, page_content='
\\n

About this item

  • 7-IN-1 FUNCTIONALITY: Pressure cook, slow cook, rice cooker, yogurt maker, steamer, sauté pan and food warmer.
  • QUICK ONE-TOUCH COOKING: 13 customizable Smart Programs for pressure cooking ribs, soups, beans, rice, poultry, yogurt, desserts and more.
  • COOK FAST OR SLOW: Pressure cook delicious one-pot meals up to 70% faster than traditional cooking methods or slow cook your favorite traditional recipes – just like grandma used to make.
  • QUICK AND EASY CLEAN UP: Finger-print resistant, stainless-steel sides and dishwasher-safe lid, inner pot, and accessories.
  • SAFETY FEATURES: Includes over 10 safety features, plus overheat protection and safe-locking lid
  • GREAT FOR GROWING FAMILIES: Cook for up to 6 people – perfect for growing families, or meal prepping and batch cooking for singles.
  • VERSATILE INNER COOKING POT: We use food-grade stainless-steel, a tri-ply bottom for more even cooking and perfect for sautéing
  • DISCOVER AMAZING RECIPES: Includes the free Instant Brands Connect App, where you can find new recipes to create quick favorites and prepare delicious meals, available for iOS and Android.
\\n
See more product details
\\xa0 Report an issue with this product or seller

There is a newer model of this item:

Instant Pot RIO, 7-in-1 Electric Multi-Cooker, PressureCooker, SlowCooker, RiceCooker, Steamer, Sauté, Yogurt Maker, & Warmer, Includes App With Over 800 Recipes, 6 Quart $94.95 (2,377) In Stock

Product voltage: 120

This product is compatible with outlets that support 120 volts and might require a converter when used outside of the United States.

\\n More filters

\\n Price \\n

\\n
\\n <$25 \\n\\n $25 - $50 \\n\\n $50 - $100 \\n\\n $100 - $200 \\n\\n >$200 \\n

\\n Discover similar items

'), 1.0), (Document(metadata={'relevance_score': -12.453125}, page_content='

\\n Color \\n \\n Capacity \\n \\n Grade \\n \\n Power \\n \\n Heat Source \\n \\n Material \\n \\n Slow Cooker Type \\n \\n Brand \\n \\n Closure \\n \\n Width \\n \\n Finish \\n \\n Control Type \\n \\n Free From \\n \\n Heating Elements \\n \\n Heating Type \\n \\n Depth \\n \\n Premium Brands \\n \\n Output Wattage \\n \\n Features \\n \\n Uses \\n \\n Inclusions \\n \\n Height \\n \\n Length \\n \\n Lid Material \\n \\n Shape \\n \\n Top Brands in Home & Kitchen \\n \\n Style \\n

\\n
\\n \\nBlack \\n\\n \\nGrey \\n\\n \\nWhite \\n\\n \\nBrown \\n\\n \\nBeige \\n\\n \\nRed \\n\\n \\nPink \\n\\n \\nOrange \\n\\n \\nYellow \\n\\n \\nIvory \\n\\n \\nGreen \\n\\n \\nBlue \\n\\n \\nPurple \\n\\n \\nGold \\n\\n \\nSilver \\n\\n \\nMulti \\n\\n \\nClear \\n\\n \\nStainless Steel \\n
\\n
'), 0.8132108732268714), (Document(metadata={'relevance_score': -12.46875}, page_content=\"
\\n\\n\\n\\n
$$79.9979.99 \\n ()\\n Includes selected options. Includes initial monthly payment and selected options. \\n Details \\n
Price ($79.99x)
$79.99
Subtotal
$$79.9979.99
Subtotal
Initial payment breakdown
Shipping cost, delivery date, and order total (including tax) shown at checkout.\\n
Add to Cart
Buy Now
Enhancements you chose aren't available for this seller. Details
To add the following enhancements to your purchase, choose a different seller.
%cardName%
${cardName} not available for the seller you chose
${cardName} unavailable for quantities greater than ${maxQuantity}.
\"), 0.7528683592125947)]\n", "prompt: \n", "You are a helpful assistant that extracts structured data from web pages.\n", "You will be given a web page and you need to extract the following information:\n", "
\n", "

About this item

  • 7-IN-1 FUNCTIONALITY: Pressure cook, slow cook, rice cooker, yogurt maker, steamer, sauté pan and food warmer.
  • QUICK ONE-TOUCH COOKING: 13 customizable Smart Programs for pressure cooking ribs, soups, beans, rice, poultry, yogurt, desserts and more.
  • COOK FAST OR SLOW: Pressure cook delicious one-pot meals up to 70% faster than traditional cooking methods or slow cook your favorite traditional recipes – just like grandma used to make.
  • QUICK AND EASY CLEAN UP: Finger-print resistant, stainless-steel sides and dishwasher-safe lid, inner pot, and accessories.
  • SAFETY FEATURES: Includes over 10 safety features, plus overheat protection and safe-locking lid
  • GREAT FOR GROWING FAMILIES: Cook for up to 6 people – perfect for growing families, or meal prepping and batch cooking for singles.
  • VERSATILE INNER COOKING POT: We use food-grade stainless-steel, a tri-ply bottom for more even cooking and perfect for sautéing
  • DISCOVER AMAZING RECIPES: Includes the free Instant Brands Connect App, where you can find new recipes to create quick favorites and prepare delicious meals, available for iOS and Android.
\n", "
See more product details
  Report an issue with this product or seller

There is a newer model of this item:

Instant Pot RIO, 7-in-1 Electric Multi-Cooker, PressureCooker, SlowCooker, RiceCooker, Steamer, Sauté, Yogurt Maker, & Warmer, Includes App With Over 800 Recipes, 6 Quart $94.95 (2,377) In Stock

Product voltage: 120

This product is compatible with outlets that support 120 volts and might require a converter when used outside of the United States.

\n", " More filters

\n", " Price \n", "

\n", "
\n", " <$25 \n", "\n", " $25 - $50 \n", "\n", " $50 - $100 \n", "\n", " $100 - $200 \n", "\n", " >$200 \n", "

\n", " Discover similar items

\n", "\n", "

\n", " Color \n", " \n", " Capacity \n", " \n", " Grade \n", " \n", " Power \n", " \n", " Heat Source \n", " \n", " Material \n", " \n", " Slow Cooker Type \n", " \n", " Brand \n", " \n", " Closure \n", " \n", " Width \n", " \n", " Finish \n", " \n", " Control Type \n", " \n", " Free From \n", " \n", " Heating Elements \n", " \n", " Heating Type \n", " \n", " Depth \n", " \n", " Premium Brands \n", " \n", " Output Wattage \n", " \n", " Features \n", " \n", " Uses \n", " \n", " Inclusions \n", " \n", " Height \n", " \n", " Length \n", " \n", " Lid Material \n", " \n", " Shape \n", " \n", " Top Brands in Home & Kitchen \n", " \n", " Style \n", "

\n", "
\n", " \n", "Black \n", "\n", " \n", "Grey \n", "\n", " \n", "White \n", "\n", " \n", "Brown \n", "\n", " \n", "Beige \n", "\n", " \n", "Red \n", "\n", " \n", "Pink \n", "\n", " \n", "Orange \n", "\n", " \n", "Yellow \n", "\n", " \n", "Ivory \n", "\n", " \n", "Green \n", "\n", " \n", "Blue \n", "\n", " \n", "Purple \n", "\n", " \n", "Gold \n", "\n", " \n", "Silver \n", "\n", " \n", "Multi \n", "\n", " \n", "Clear \n", "\n", " \n", "Stainless Steel \n", "
\n", "
\n", "\n", "
\n", "\n", "\n", "\n", "
$$79.9979.99 \n", " ()\n", " Includes selected options. Includes initial monthly payment and selected options. \n", " Details \n", "
Price ($79.99x)
$79.99
Subtotal
$$79.9979.99
Subtotal
Initial payment breakdown
Shipping cost, delivery date, and order total (including tax) shown at checkout.\n", "
Add to Cart
Buy Now
Enhancements you chose aren't available for this seller. Details
To add the following enhancements to your purchase, choose a different seller.
%cardName%
${cardName} not available for the seller you chose
${cardName} unavailable for quantities greater than ${maxQuantity}.
\n", "\n", "schema: {'properties': {'productTitle': {'description': 'The full title of the product', 'maxLength': 200, 'minLength': 1, 'title': 'Product Title', 'type': 'string'}, 'price': {'anyOf': [{'exclusiveMinimum': 0.0, 'type': 'number'}, {'type': 'string'}], 'description': 'Unit price (must be > 0, two decimal places).', 'title': 'Product Price'}, 'manufacturer': {'description': 'Name of the product manufacturer.', 'maxLength': 1000, 'minLength': 1, 'title': 'Manufacturer', 'type': 'string'}}, 'required': ['productTitle', 'price', 'manufacturer'], 'title': 'ProductModel', 'type': 'object'}\n", "Please provide the extracted data in JSON format.\n", "WITH ONLY THE FIELDS THAT ARE IN THE SCHEMA.\n", "\n", "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n", "Final output: {'productTitle': 'Instant Pot RIO, 7-in-1 Electric Multi-Cooker, PressureCooker, SlowCooker, RiceCooker, Steamer, Sauté, Yogurt Maker, & Warmer, Includes App With Over 800 Recipes, 6 Quart', 'price': 94.95, 'manufacturer': 'Instant Pot'}\n", "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ] }, { "data": { "text/plain": [ "{'productTitle': 'Instant Pot RIO, 7-in-1 Electric Multi-Cooker, PressureCooker, SlowCooker, RiceCooker, Steamer, Sauté, Yogurt Maker, & Warmer, Includes App With Over 800 Recipes, 6 Quart',\n", " 'price': 94.95,\n", " 'manufacturer': 'Instant Pot'}" ] }, "execution_count": 120, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pipe.run(content=url,is_url=True, schema=schema, hf=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "6c4109c9", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "ef3a300c", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.8" } }, "nbformat": 4, "nbformat_minor": 5 }