# Keble-Keepa

A powerful Python wrapper for the Keepa API with enhanced data analysis capabilities and caching.

## Overview

Keble-Keepa provides a convenient interface to interact with [Keepa's API](https://keepa.com/#!api) for accessing Amazon product data. The package includes:

- Complete API client with sync and async methods
- MongoDB-based caching system for efficient API usage
- Enhanced data models with additional properties and analysis methods
- Batch loading system for processing multiple products

## Installation

```bash
pip install keble-keepa
```

## Quick Start

```python
from keble_keepa import KeepaApi, RequestProductsQuery, DomainId

# Initialize the API client
keepa_api = KeepaApi(
    mongo=mongo_client,
    api_token="your-keepa-api-token",
    mongo_database="keepa_cache_db",
    keepa_cache_collection="keepa_cache",
    cache_days=7,  # Cache data for 7 days
)

# Request product data
products_data = keepa_api.request_products(
    RequestProductsQuery(
        asin=["B07B7K7N3P"],  # ASIN of the product
        domain=DomainId.COM,   # Amazon US
        stats=90,              # Get stats for the last 90 days
        offers=20,             # Get up to 20 marketplace offers
        rating=1,              # Include rating history
    )
)

# Access the product data
product = products_data.products[0]
print(f"Title: {product.title}")
print(f"Average price: ${product.average_price_int/100:.2f}")
print(f"Current rating: {product.latest_ratings_int/10:.1f}/5.0 ({product.latest_reviews} reviews)")

# Get size and weight information
size, weight = product.size_and_weight
if size:
    print(f"Size (L×W×H): {size[0]}×{size[1]}×{size[2]} cm")
if weight:
    print(f"Weight: {weight} g ({weight/453.59237:.2f} lb)")
```

## KeepaApi

The main class for interacting with the Keepa API.

### Initialization

```python
from keble_keepa import KeepaApi
from pymongo import MongoClient

# Initialize
keepa_api = KeepaApi(
    mongo=MongoClient("mongodb://localhost:27017"),
    api_token="your-keepa-api-token",
    mongo_database="keepa_cache_db",
    keepa_cache_collection="keepa_cache",
    cache_days=7,
)
```

### Key Methods

```python
# Sync Methods
keepa_api.request_products(query)             # Get product data by ASIN
keepa_api.product_finder(query)               # Search for products
keepa_api.product_search(query)               # Search for products by keywords
keepa_api.category_lookup(query)              # Look up category details
keepa_api.category_search(query)              # Search for categories
keepa_api.browsing_deal(query)                # Find deals on Amazon
keepa_api.lightning_deal(query)               # Find lightning deals
keepa_api.request_best_sellers(query)         # Get best seller lists
keepa_api.request_seller_information(query)   # Get seller information
keepa_api.retrieve_token_status()             # Check API token status

# Async Methods
await keepa_api.arequest_products(query, amongo=amongo, extended_aredis=aredis)
await keepa_api.aproduct_finder(query, amongo=amongo, extended_aredis=aredis)
await keepa_api.acategory_lookup(query, amongo=amongo, extended_aredis=aredis)
await keepa_api.acategory_search(query, amongo=amongo, extended_aredis=aredis)
# ... and more
```

## Batch Loader

For loading multiple products efficiently:

```python
from keble_keepa import KeepaApiBatchLoader

# Initialize
batch_loader = KeepaApiBatchLoader(
    keepa_api=keepa_api,
    max_concurrent_tasks=20,
    retry_sleep_secs=30,
    max_retry_per_request=3,
)

# Load multiple products by ASINs
products = await batch_loader.aload_asins_from_keepa(
    amongo=amongo,
    extended_aredis=aredis,
    asins=["B07B7K7N3P", "B0113UZJE2"],
    marketplace=AmazonMarketplace.US,
    with_reviews=True,
)

# Load similar products based on a reference product
similar_products = await batch_loader.aload_similar_products(
    product=reference_product,
    category_id=category_id,
    amongo=amongo,
    extended_aredis=aredis,
    marketplace=AmazonMarketplace.US,
    search_same_category_asins_page_size=100,
    search_same_category_asins_max_page=10,
    search_same_category_tolerant_ratio=0.5,
    keyword="digital camera",
    with_reviews=True,
)

# Load similar products with a limit
limited_similar = await batch_loader.aload_similar_products_with_limit(
    product=reference_product,
    amongo=amongo,
    extended_aredis=aredis,
    marketplace=AmazonMarketplace.US,
    limit=50,
)
```

## Request Schemas

### RequestProductsQuery

For retrieving detailed product data by ASIN.

```python
from keble_keepa import RequestProductsQuery, DomainId

query = RequestProductsQuery(
    domain=DomainId.COM,            # Amazon marketplace (1: US, 2: UK, 3: DE, etc.)
    asin=["B07B7K7N3P"],           # List of ASINs to fetch (up to 100)
    # Alternative: Use product codes
    # product_code=["885909950805"], # UPC, EAN, or ISBN-13 codes
    
    # Optional parameters (same as Keepa official doc)
    stats=90,                       # Get stats for the last 90 days
    update=1,                       # Force refresh if data is older than 1 hour
    offers=20,                      # Get up to 20 marketplace offers
    buybox=1,                       # Include buy box data
    rating=1,                       # Include rating history
    # ...and more
)
```

### Other Query Types

- `ProductFinderQuery`: Advanced product search with filtering
- `ProductSearchQuery`: Simple keyword search
- `CategoryLookupQuery`: Category information lookup
- `CategorySearchQuery`: Search for categories
- `RequestBestSellersQuery`: Get best seller products
- `RequestSellerInformationQuery`: Get seller information

## Response Schemas

### Product Model

The core model representing Amazon product data with enhanced properties:

```python
# Basic Keepa data fields (same as Keepa official doc)
product.asin                      # Amazon Standard Identification Number
product.title                     # Product title
product.domain_id                 # Amazon locale ID
product.manufacturer              # Manufacturer name
product.brand                     # Brand name
product.product_group             # Product category group
product.csv                       # CSV data with price/rank history
# ...many more fields

# Enhanced properties (not in Keepa API)
product.size_and_weight           # Tuple of (dimensions tuple, weight in grams)
product.average_price_int         # Average price as integer (100 = $1.00)
product.latest_ratings_int        # Current rating (0-50, integer)
product.latest_reviews            # Current number of reviews
product.marketplace               # Marketplace enum (US, UK, DE, etc.)
product.amazon_marketplace        # Amazon marketplace enum
product.currency                  # Currency enum
product.currency_symbol           # Currency symbol
product.monthly_sales_unit_data_list  # Monthly sales data
product.amazon_prices_unit_data_list  # Amazon price history
product.new_prices_unit_data_list     # 3rd party new price history
product.used_prices_unit_data_list    # Used price history
product.bsr_list                  # List of Best Seller Ranks
product.categories_ids            # List of category IDs
product.image_urls                # List of image URLs
product.has_offer_since_datetime  # First date product was available
product.is_bsr_stable             # Whether BSR is stable over time
product.baseline_monthly_sales    # Estimated minimum monthly sales
# ...and more
```

### Other Response Types

- `ProductFinderResponse`: Results from product finder search
- `ProductSearchResponse`: Results from keyword search
- `CategoryLookupResponse`: Category details
- `RequestBestSellersResponse`: Best seller products

## License

MIT
