Re-upload under an AGPL license

This commit is contained in:
Bo Peng
2025-03-14 14:39:23 -05:00
commit 75bceef3c6
79 changed files with 13429 additions and 0 deletions

35
.bumpversion.cfg Normal file
View File

@@ -0,0 +1,35 @@
[bumpversion]
commit = True
tag = False
current_version = 0.2.0
[bumpversion:file:pyproject.toml]
search = version = "{current_version}"
replace = version = "{new_version}"
[bumpversion:file:src/ai_marketplace_monitor/__init__.py]
search = __version__ = "{current_version}"
replace = __version__ = "{new_version}"
[bumpversion:file(title):CHANGELOG.md]
search = {#}{#} [Unreleased]
replace = {#}{#} [Unreleased]
{#}{#} [{new_version}] - {now:%Y-%m-%d}
[bumpversion:file(links):CHANGELOG.md]
search = [Unreleased]: https://github.com/BoPeng/ai-marketplace-monitor/compare/v{current_version}...HEAD
replace = [Unreleased]: https://github.com/BoPeng/ai-marketplace-monitor/compare/v{new_version}...HEAD
[{new_version}]: https://github.com/BoPeng/ai-marketplace-monitor/compare/v{current_version}...v{new_version}
[bumpversion:file(version):CITATION.cff]
search = version: {current_version}
replace = version: {new_version}
[bumpversion:file(tag):CITATION.cff]
search = https://github.com/BoPeng/ai-marketplace-monitor/releases/tag/v{current_version}
replace = https://github.com/BoPeng/ai-marketplace-monitor/releases/tag/v{new_version}
[bumpversion:file(description):CITATION.cff]
search = description: The Software Heritage link for version {current_version}.
replace = description: The Software Heritage link for version {new_version}.

10
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,10 @@
# This is a comment.
# Each line is a file pattern followed by one or more owners.
# More details are here: https://help.github.com/articles/about-codeowners/
# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @BoPeng will be requested for review when someone opens
# a pull request.
* @BoPeng

8
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
---
# This is a comment.
# You can configure the sponsor button in your repository to include
# sponsored developers in GitHub Sponsors, external funding platforms,
# or a custom funding URL.
# More details are here: https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
github: BoPeng

29
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,29 @@
---
name: 🐛 Bug report
about: Create a report to help us improve
title: "[Bug] Your title here"
labels: bug
assignees: ""
---
## Expected Behavior
---
## Actual Behavior
---
## Steps to Reproduce the Problem
1.
1.
1.
---
## Specifications
- Version:
- Platform:
- Subsystem:

2
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,2 @@
blank_issues_enabled: false
contact_links: []

31
.github/ISSUE_TEMPLATE/discussion.md vendored Normal file
View File

@@ -0,0 +1,31 @@
---
name: 💬 General discussion
about: Start a conversation or share thoughts on miscellaneous topics related to the project.
title: "[Discussion] Your topic here"
labels: discussion
assignees: ""
---
**Topic or Idea**
Briefly describe the topic or idea you'd like to discuss. Be clear and concise to help others understand the focus of the conversation.
---
**Details**
Provide more context or details about your topic. For example:
- Why is this topic relevant or important?
- Are there specific aspects you'd like feedback on?
---
**Goals or Outcomes**
What do you hope to achieve with this discussion? (e.g., gather opinions, brainstorm ideas, find solutions).
---
**Additional Context**
Include any relevant information, such as:
- Links to related issues, pull requests, or documentation.
- Examples, screenshots, or references to support your points.

33
.github/ISSUE_TEMPLATE/documentation.md vendored Normal file
View File

@@ -0,0 +1,33 @@
---
name: 📝 Documentation Improvement
about: Suggest updates or improvements to project documentation.
title: "[Docs] Your suggestion here"
labels: documentation
assignees: ""
---
**Current Issue**
Briefly describe the problem or limitation in the current documentation. Be specific about what is unclear, outdated, or missing.
---
**Proposed Improvement**
Explain how the documentation can be improved. Provide details about the changes you'd like to see, such as:
- Sections that need clarification.
- New topics that should be added.
- Updates to keep documentation accurate.
---
**Affected Pages or Sections**
List the specific pages, files, or sections in the documentation that are impacted. Example:
---
**Additional Context**
Provide any relevant details, such as:
- Links to related issues or pull requests.
- Screenshots or examples of the current documentation.
- External resources or references that could support the improvement.

View File

@@ -0,0 +1,25 @@
---
name: 🚀 Feature request
about: Suggest an idea for this project
title: "[Feature Request] Your title here"
labels: enhancement
assignees: ""
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
---
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
---
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
---
**Additional context**
Add any other context or screenshots about the feature request here.

38
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: 🤔 General question
about: Suggest an idea for this project
title: "[Question] Your title here"
labels: question
assignees: ""
---
**Description**
Provide a detailed explanation of your question or issue. Be as specific as possible.
---
**Steps to Reproduce (if applicable)**
If your question involves reproducing an issue, please list the steps to replicate it.
1. Step one
2. Step two
3. Step three
---
**Expected Outcome (if applicable)**
What did you expect to happen?
---
**Actual Outcome (if applicable)**
What actually happened?
---
**Additional Information**
Add any relevant details here, including:
- Versions of tools, dependencies, or environments.
- Screenshots (if they help explain the question).

7
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,7 @@
Fixes #
## Proposed Changes
-
-
-

14
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
- package-ecosystem: pip
directory: "/docs"
schedule:
interval: daily
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily

23
.github/workflows/close-stale-issue.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
name: Close Stale Issues
on:
schedule:
- cron: "0 0 * * *" # Runs daily at midnight UTC
permissions:
issues: write
jobs:
close-stale-issues:
runs-on: ubuntu-latest
steps:
- name: Close inactive issues
uses: actions/stale@v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "This issue has been inactive for a while. If theres no response, it will be closed automatically."
close-issue-message: "Closing this issue due to inactivity. Feel free to reopen if needed!"
days-before-stale: 7 # Days before marking the issue as stale
days-before-close: 3 # Days after being marked stale before closing
only-labels: "resolved" # Only apply to issues with this label
exempt-issue-creator: true # Do not auto-close issues created by the repo owner

41
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: "CodeQL"
on:
push:
branches:
pull_request:
branches:
schedule:
- cron: '0 6 * * 1'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'python' ]
steps:
- name: Checkout repository
uses: actions/checkout@v4.2.2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3

View File

@@ -0,0 +1,44 @@
name: "Pre-commit autoupdate"
on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:
jobs:
autoupdate:
name: autoupdate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- name: Set up Python 3.12
uses: actions/setup-python@v5.4.0
with:
python-version: 3.12
- name: Install system deps
shell: bash
run: |
pip install poetry
poetry config virtualenvs.in-project true
poetry install --no-root --only dev --only linters --sync
- name: Run autoupdate
run: poetry run pre-commit autoupdate
continue-on-error: true
- name: Run pre-commit
run: poetry run pre-commit run --all-files
- uses: peter-evans/create-pull-request@v7.0.8
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: chore-update-pre-commit-hooks
title: Update pre-commit hooks
commit-message: "Update pre-commit hooks"
body: |
# Update pre-commit hooks
- Update pre-commit hooks to the latest version.
delete-branch: true

78
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,78 @@
name: release
on:
push:
tags:
- "v*"
permissions:
id-token: write
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- name: Set up Python 3.12
uses: actions/setup-python@v5.4.0
with:
python-version: 3.12
- name: Install system deps
shell: bash
run: |
pip install poetry
poetry config virtualenvs.in-project true
- name: Build package
run: |
poetry build --ansi
- name: Publish package on PyPI
uses: pypa/gh-action-pypi-publish@v1.12.4
with:
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
attestations: false
- name: Publish package on TestPyPI
uses: pypa/gh-action-pypi-publish@v1.12.4
with:
user: __token__
password: ${{ secrets.TEST_PYPI_TOKEN }}
repository-url: https://test.pypi.org/legacy/
attestations: false
github_release:
needs: release
name: Create Github Release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- name: Get version from tag
id: tag_name
shell: bash
run: |
echo ::set-output name=current_version::${GITHUB_REF#refs/tags/v}
- name: Get Changelog Entry
id: changelog_reader
uses: mindsers/changelog-reader-action@v2.2.3
with:
version: ${{ steps.tag_name.outputs.current_version }}
path: ./CHANGELOG.md
- name: Create Release
id: create_release
uses: actions/create-release@v1.1.4
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
body: ${{ steps.changelog_reader.outputs.changes }}
draft: false
prerelease: false

114
.github/workflows/tests.yml vendored Normal file
View File

@@ -0,0 +1,114 @@
name: tests
on:
push:
branches:
pull_request:
branches:
jobs:
linting:
name: Linting
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- name: Set up Python 3.12
uses: actions/setup-python@v5.4.0
with:
python-version: 3.12
- name: Install system deps
shell: bash
run: |
pip install poetry
poetry config virtualenvs.in-project true
poetry install --no-root --only dev --only linters --sync
- name: Linting
shell: bash
run: poetry run pre-commit run --all-files
tests:
needs: linting
name: ${{ matrix.os }} / ${{ matrix.python-version }}
runs-on: ${{ matrix.os }}-latest
strategy:
matrix:
os: [Ubuntu, MacOS]
python-version: ["3.10", "3.11", "3.12"]
fail-fast: true
steps:
- uses: actions/checkout@v4.2.2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5.4.0
with:
python-version: ${{ matrix.python-version }}
- name: Install system deps
shell: bash
run: |
pip install nox-poetry==1.1.0
pip install poetry==1.8.5
poetry config virtualenvs.in-project true
- name: Run mypy with nox
shell: bash
run: nox --force-color -s mypy-${{ matrix.python-version }}
- name: Install Playwright Browsers
run: |
pip install playwright
playwright install --with-deps # Ensures browsers and dependencies are installed
- name: Run tests with nox
shell: bash
run: nox --force-color -s tests-${{ matrix.python-version }}
- name: Run securtity check
if: matrix.python-version == '3.12' && matrix.os == 'Ubuntu'
shell: bash
run: nox --force-color -s security
- name: Upload coverage data
uses: actions/upload-artifact@v4.6.1
with:
name: ${{ matrix.os }}-${{ matrix.python-version }}.coverage-data
path: ".coverage.*"
include-hidden-files: true
retention-days: 2
# coverage:
# needs: tests
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4.2.2
# - name: Set up Python 3.12
# uses: actions/setup-python@v5.4.0
# with:
# python-version: 3.12
# - name: Install system deps
# shell: bash
# run: |
# pip install nox-poetry==1.1.0
# pip install poetry==1.8.5
# poetry config virtualenvs.in-project true
# - name: Download coverage data
# uses: actions/download-artifact@v4.1.8
# with:
# pattern: "*.coverage-data"
# merge-multiple: true
# - name: Create coverage report
# shell: bash
# run: |
# nox --force-color --session=coverage -- --fmt xml
# - name: Upload coverage report
# uses: codecov/codecov-action@v5.1.2
# with:
# token: ${{ secrets.CODECOV_TOKEN }}

135
.gitignore vendored Normal file
View File

@@ -0,0 +1,135 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# pytype
.pytype/
# Pyre type checker
.pyre/
# Code editors
.vscode

42
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,42 @@
---
default_install_hook_types:
- pre-commit
- post-checkout
- post-merge
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: check-toml
- id: check-json
- id: check-yaml
- id: debug-statements
- id: check-merge-conflict
- id: pretty-format-json
args: [--autofix, "--no-sort-keys"]
exclude: .ipynb
- id: end-of-file-fixer
- id: trailing-whitespace
exclude: .bumpversion.cfg
# - repo: https://github.com/timothycrosley/isort
# rev: 5.13.2
# hooks:
# - id: isort
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.4
hooks:
- id: ruff
args: [--fix]
- repo: https://github.com/citation-file-format/cffconvert
rev: 5295f87c0e261da61a7b919fc754e3a77edd98a7
hooks:
- id: validate-cff
- repo: https://github.com/python-poetry/poetry
rev: 1.8.3
hooks:
- id: poetry-check
- id: poetry-install

17
.readthedocs.yml Normal file
View File

@@ -0,0 +1,17 @@
version: 2
build:
os: ubuntu-22.04
tools:
python: "3.12"
formats: all
sphinx:
configuration: docs/conf.py
python:
install:
- requirements: docs/requirements.txt
- method: pip
path: .

12
.safety-policy.yml Normal file
View File

@@ -0,0 +1,12 @@
version: '2.0'
# Safety Security and License Configuration file
security: # configuration for the `safety check` command
ignore-cvss-severity-below: 0 # A severity number between 0 and 10. Some helpful reference points: 9=ignore all vulnerabilities except CRITICAL severity. 7=ignore all vulnerabilities except CRITICAL
ignore-cvss-unknown-severity: False # True or False. We recommend you set this to False.
ignore-vulnerabilities: # Here you can list multiple specific vulnerabilities you want to ignore (optionally for a time period)
# We recommend making use of the optional `reason` and `expires` keys for each vulnerability that you ignore.
# 70612:
# reason: we do not use the vulnerable function
# expires: '2025-10-10'
continue-on-vulnerability-error: False # Suppress non-zero exit codes when vulnerabilities are found. Enable this in pipelines and CI/CD processes if you want to pass builds that have vulnerabilities

143
CHANGELOG.md Normal file
View File

@@ -0,0 +1,143 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.8.8] - 2025-03-13
- Re-release AI Marketplace Monitor under a AGLP license
## [0.8.8] - 2025-03-12
- Allow option date_listed to accept numeric value #96
- Fix importing pushover #91
## [0.8.6] - 2025-03-03
- Allow support for multiple languages.
## [0.8.5] - 2025-03-03
- Allow [pushover](https://pushover.net/) notification
## [0.8.2] - 2025-03-02
- Reorganize notification settings
- Support the use of environment variables for passwords
- Support browser proxy
**BREAKING CHANGES**
- Rename `smtp` sections to `notification`
- Rename parameter `smtp` to `notify_with`
## [0.7.11] - 2025-03-01
- Fix a bug on the handling of logical expressions for `keywords` and `antikeywords`.
- Add support for another auto layout page
## [0.8.9] - 2025-02-21
- Add options `prompt`, `extra_prompt` and `rating_prompt`
## [0.7.7] - 2025-02-17
- Expand the use of `enabled=False` to all sections
- Allow complex `AND` `OR` and `NOT` operations for `keywords` and `antikeywords`.
## [0.7.4] - 2025-02-10
- Rename `keywords` to `search_phrases`, `include_keywords` to `keywords` and `exclude_keywords` to `antikeywords` [#45]
- Separate statistics by item name [#46]
## [0.7.3] - 2025-02-07
- Allow email notification
## [0.7.0] - 2025-02-06
- Re-retrieve details of listings if there are title or price change
- Allow sending reminders for available items after specified time. (#41)
- Display counters
## [0.6.5] - 2025-02-05
- Allow checking URLs during monitoring (#34)
- Add option `ai` that allows the specification of AI models to use for certain marketplaces or items.
- Support locally hosted Ollama models
- Support DeepSeek-r1 model with `<think>` tags.
- Add option `timeout` to AI request.
- Expand command line option `--clear-cache`
## [0.6.2] - 2025-02-03
- Support extracting details from automobile listings.
## [0.6.1] - 2025-02-02
- Allow multiple `start_at`
## [0.6.0] - 2025-02-01
- Allow some parameters to different from initial and subsequent searches.
- Allow the AI to return a rating and some comments, and use the rating to determine if the user should be notified.
## [0.5.3] - 2025-01-31
- Add command line option `--diable-javascript` which can be helpful in some cases.
- Add option `include_keywords` to fine-tune the behavior of `keywords`.
- Add option `provider` to allow the specfication of more AI service providers.
- Allow `market_type` to marketplaces and allow multiple marketplaces.
## [0.5.1] - 2025-01-30
- Change the unit of `search-interval` to seconds to allow for more frequent search, although that is not recommended.
- Rename option `acceptable_locations` to `seller_locations`
## [0.5.0] - 2025-01-29
- Allow each time to add its own `search_interval`
- Add options such as `delivery_method`, `radius`, and `condition`
- Add options to define and use regions for searching large regions
## [0.4.5] - 2025-01-27
- Add option `--check` and `--for` to check particular listings
## [0.4.3] - 2025-01-26
- Add support for DeepSeek
## [0.4.0] - 2025-01-25
- Allow section `[ai.openai]`
- Use openAI to confirm if the item matches what user requests
- Slightly better logging
## [0.3.3] - 2025-01-21
- Allow option `enabled` for items
- Notify all users if no `notify` is specified for item or marketplace
- Compare string after normalization (#8)
- Stop sleeping if config files are changed. Allowing more interactive modification of search terms.
- Give more time after logging in, allow option `login_wait_time`.
- Allow entering username and password manually
## [0.2.0] - 2025-01-21
- Allow the definition of a reusable config file from `~/.ai-marketplace-monitor/config.toml`
- Allow options `exclude_sellers` and `exclude_by_description`
- Fix a bug that prevents the sending of phone notification
## [0.1.0] - 2025-01-20
### Added
- First release on PyPI.
[Unreleased]: https://github.com/BoPeng/ai-marketplace-monitor/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/BoPeng/ai-marketplace-monitor/compare/releases/tag/v0.1.0

24
CITATION.cff Normal file
View File

@@ -0,0 +1,24 @@
# This CITATION.cff file was generated with cffinit.
# Visit https://bit.ly/cffinit to generate yours today!
cff-version: 1.2.0
title: AI Marketplace Monitor
message: >-
If you use this software, please cite it using the
metadata from this file.
type: software
authors:
- given-names: Bo
family-names: Peng
alias: fedejaure
identifiers:
- type: url
value: >-
https://github.com/BoPeng/ai-marketplace-monitor/releases/tag/v0.1.0
description: The Software Heritage link for version 0.1.0.
repository-code: 'https://github.com/BoPeng/ai-marketplace-monitor'
abstract: An AI-based tool for monitoring facebook marketplace
keywords:
- ai-marketplace-monitor
license: MIT
version: 0.1.0

133
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,133 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official email address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
email.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

103
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,103 @@
# Contributing to AI Marketplace Monitor
👏🎉 First off all, Thanks for your interest in contributing to our project! 🎉👏
The following is a set of guidelines for contributing to AI Marketplace Monitor. These are
mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
## Code of Conduct
We take our open source community seriously and hold ourselves and other contributors to high standards of communication. By participating and contributing to this project, you agree to uphold our [Code of Conduct](CODE_OF_CONDUCT.md).
## Getting Started
### Requirements
We use `poetry` to manage and install dependencies. [Poetry](https://python-poetry.org/) provides a custom installer that will install `poetry` isolated from the rest of your system.
```
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python -
```
We'll also need `nox` for automated testing in multiple Python environments so [install that too](https://nox.thea.codes/en/stable/).
To install the local development requirements inside a virtual environment run:
```
$ poetry install
$ poetry run inv install-hooks
```
> For more information about `poetry` check the [docs](https://python-poetry.org/docs/).
We use [invoke](http://www.pyinvoke.org/) to wrap up some useful tasks like formatting, linting, testing and more.
Execute `inv[oke] --list` to see the list of available commands.
## Running _AI Marketplace Monitor_ from source code
If you would like to run the latest version of _AI Marketplace Monitor_ or test a branch, please checkout the repository
```sh
git clone https://github.com/BoPeng/ai-marketplace-monitor
cd ai-marketplace-monitor
```
or updating a local copy with commands
```sh
cd ai-marketplace-monitor
git pull
```
switch to a branch, e.g. `dev`, if needed,
```sh
git checkout dev
```
Then install the tool from source code with command
```sh
poetry install
```
## Contributing
### Issues
We use GitHub issues to track public bugs/enhancements. Report a new one by [opening a new issue](https://github.com/BoPeng/ai-marketplace-monitor/issues).
In this repository, we provide a couple of templates for you to fill in for:
- Bugs
- Feature Requests/Enhancements
Please read each section in the templates and provide as much information as you can. Please do not put any sensitive information,
such as personally identifiable information, connection strings or cloud credentials. The more information you can provide, the better we can help you.
### Pull Requests
Please follow these steps to have your contribution considered by the maintainers:
1. Fork the repo and create your branch locally with a succinct but descriptive name.
2. Add tests for the new changes
3. Edit documentation if you have changed something significant
4. Make sure to follow the [styleguides](#styleguides)
5. Open a PR in our repository and follow the PR template so that we can efficiently review the changes
6. After you submit your pull request, verify that all status checks are passing
While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design
work, tests, or other changes before your pull request can be ultimately accepted.
## Styleguides
### Python Code Style
All Python code is linted with [Ruff](https://github.com/astral-sh/ruff) and formated with
[Isort](https://github.com/PyCQA/isort) and [Black](https://github.com/psf/black). You can
execute `inv[oke] lint` and `inv[oke] format`.
## Additional Notes
If you have any question feel free to contact us at email.

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

675
README.md Normal file
View File

@@ -0,0 +1,675 @@
![AI Marketplace Monitor](docs/AIMM_neutral.png)
<div align="center">
[![PyPI - Version](https://img.shields.io/pypi/v/ai-marketplace-monitor.svg)](https://pypi.python.org/pypi/ai-marketplace-monitor)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/ai-marketplace-monitor.svg)](https://pypi.python.org/pypi/ai-marketplace-monitor)
[![Tests](https://github.com/BoPeng/ai-marketplace-monitor/workflows/tests/badge.svg)](https://github.com/BoPeng/ai-marketplace-monitor/actions?workflow=tests)
[![Codecov](https://codecov.io/gh/BoPeng/ai-marketplace-monitor/branch/main/graph/badge.svg)](https://codecov.io/gh/BoPeng/ai-marketplace-monitor)
[![Read the Docs](https://readthedocs.org/projects/ai-marketplace-monitor/badge/)](https://ai-marketplace-monitor.readthedocs.io/)
[![PyPI - License](https://img.shields.io/pypi/l/ai-marketplace-monitor.svg)](https://pypi.python.org/pypi/ai-marketplace-monitor)
[![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit)
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)
</div>
An intelligent tool that monitors Facebook Marketplace listings using AI to help you find the best deals. Get instant notifications when items matching your criteria are posted, with AI-powered analysis of each listing.
![Search In Action](docs/search_in_action.png)
Example notification from PushBullet:
```
Found 1 new gopro from facebook
[Great deal (5)] Go Pro hero 12
$180, Houston, TX
https://facebook.com/marketplace/item/1234567890
AI: Great deal; A well-priced, well-maintained camera meets all search criteria, with extra battery and charger.
```
**Table of content:**
- [✨ Key Features](#-key-features)
- [Usage](#usage)
- [Before the prerequisites](#before-the-prerequisites)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Set up a notification method (optional)](#set-up-a-notification-method-optional)
- [Sign up with an AI service or build your own (optional)](#sign-up-with-an-ai-service-or-build-your-own-optional)
- [Configuration](#configuration)
- [Run the program](#run-the-program)
- [Updating search](#updating-search)
- [Cost of operations](#cost-of-operations)
- [Advanced features](#advanced-features)
- [Setting up email notification](#setting-up-email-notification)
- [Adjust prompt and notification level](#adjust-prompt-and-notification-level)
- [Advanced Keyword-based filters](#advanced-keyword-based-filters)
- [Searching multiple cities and regions](#searching-multiple-cities-and-regions)
- [Support for non-English languages](#support-for-non-english-languages)
- [Check individual listing](#check-individual-listing)
- [Multiple marketplaces](#multiple-marketplaces)
- [First and subsequent searches](#first-and-subsequent-searches)
- [Showing statistics](#showing-statistics)
- [Self-hosted Ollama Model](#self-hosted-ollama-model)
- [Cache Management](#cache-management)
- [Support for different layouts of facebook listings](#support-for-different-layouts-of-facebook-listings)
- [Searching Anonymously with a Proxy Server](#searching-anonymously-with-a-proxy-server)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)
- [Credits](#credits)
## ✨ Key Features
🔍 **Smart Search**
- Search multiple products using keywords
- Filter by price and location
- Exclude irrelevant results and spammers
- Support for different Facebook Marketplace layouts
🤖 **AI-Powered**
- Intelligent listing evaluation
- Smart recommendations
- Multiple AI service providers supported
- Self-hosted model option (Ollama)
📱 **Notifications**
- PushBullet, PushOver, or Ntfy notifications
- HTML email notifications with images
- Customizable notification levels
- Repeated notification options
🌎 **Location Support**
- Multi-city search
- Pre-defined regions (USA, Canada, etc.)
- Customizable search radius
- Flexible seller location filtering
## Usage
### Before the prerequisites
_AI Marketplace Monitor_ is a tool designed to assist users in monitoring online marketplaces, with a focus on leveraging AI technologies to filter out spam and irrelevant listings. **This project was developed for personal, hobbyist use only**.
However, it is crucial to understand that **Facebook's [EULA](https://www.facebook.com/terms/)** explicitly prohibits the use of automated tools to collect or access data without prior authorization:
> You may not access or collect data from our Products using automated means (without our prior permission) or attempt to access data you do not have permission to access, regardless of whether such automated access or collection is undertaken while logged-in to a Facebook account.
By using _AI Marketplace Monitor_, you acknowledge and agree that **you are solely responsible for ensuring compliance with Facebooks (Metas) terms of service, as well as any applicable laws and regulations**. If you intend to use this tool — particularly for commercial or for-profit purposes — you **must** obtain explicit permission from Meta (and any other marketplaces that this tool may support in the future) before proceeding.
Unauthorized use of this tool may result in account suspension, legal consequences, or other penalties. **The developers and contributors of _AI Marketplace Monitor_ disclaim any liability for misuse, violations of platform policies, or any resulting consequences**. Use this tool at your own risk and ensure compliance with relevant terms and regulations before deployment.
### Prerequisites
- Python 3.x installed.
- Internet connection
### Installation
Install the program by
```sh
pip install ai-marketplace-monitor
```
Install a browser for Playwright using the command:
```sh
playwright install
```
### Set up a notification method (optional)
If you would like to receive notification from your phone via PushBullet
- Sign up for [PushBullet](https://www.pushbullet.com/), [PushOver](https://pushover.net/) or [Ntfy](https://ntfy.sh/)
- Install the app on your phone
- Go to the respective website and obtain necessary token(s)
If you would like to receive email notification, obtain relevant SMTP settings from your email provider. See [Setting up email notification](#setting-up-email-notification) for details.
### Sign up with an AI service or build your own (optional)
You can sign up for an AI service (e.g. [OpenAI](https://openai.com/) and [DeepSeek](https://www.deepseek.com/)) by
- Sign up for an account
- Go to the API keys section of your profile, generate a new API key, and copy it
You can also connect to any other AI service that provides an OpenAI compatible API, or host your own large language model using Ollama (see [Self-hosted Ollama Model](#self-hosted-ollama-model) for details.)
### Configuration
One or more configuration file in [TOML format](https://toml.io/en/) is needed. The following example ([`minimal_config.toml`](docs/minimal_config.toml)) shows the absolute minimal number of options, namely which city you are searching in, what item you are searching for, and how you get notified with matching listings.
```toml
[marketplace.facebook]
search_city = 'houston'
[item.name]
search_phrases = 'Go Pro Hero 11'
[user.user1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
```
The configuration file needs to be put as `$HOME/.ai-marketplace-monitor/config.toml`, or be specified via option `--config`.
A more realistic example using openAI would be
```toml
[ai.openai]
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
[marketplace.facebook]
search_city = 'houston'
username = 'your@email.com'
seller_locations = [
"sugar land",
"stafford",
"missouri city",
"pearland"
]
[item.name]
search_phrases = 'Go Pro Hero 11'
description = '''A new or used Go Pro version 11, 12 or 13 in
good condition. No other brand of camera is acceptable.
Please exclude sellers who offer shipping or asks to
purchase the item from his website.'''
keywords = "('Go Pro' OR gopro) AND (11 OR 12 OR 13)"
min_price = 100
max_price = 200
[item.name2]
search_phrases = 'something rare'
description = '''A rare item that has to be searched nationwide and be shipped.
listings from any location are acceptable.'''
search_region = 'usa'
delivery_method = 'shipping'
seller_locations = []
[user.user1]
email = 'you@gmail.com'
smtp_password = 'xxxxxxxxxxxxxxxx'
```
For a complete list of options, please see the [configuration documentation](docs/README.md).
### Run the program
```sh
ai-marketplace-monitor
```
or use option `--config` for a non-standard configuration file.
Use `Ctrl-C` to terminate the program.
**NOTE**
1. You need to keep the terminal running to allow the program to run indefinitely.
2. You will see a browser firing up. **You may need to manually enter username and/or password (if unspecified in config file), and answer any prompt (e.g. CAPTCHA) to login**. You may want to click "OK" to save the password, etc.
3. If you fail to login to facebook, _AI Marketplace Monitor_ will continue to operate. However, Facebook will not be able to provide results related to your user profile and will display a login screen over all search pages.
### Updating search
It is recommended that you **check the log messages and make sure that it includes and excludes listings as expected**. Modify the configuration file to update search criteria if needed. The program will detect changes and restart the search automatically.
### Cost of operations
1. **Licensing Costs**: None.
2. **External Service Costs**: Usage-dependent costs for notification services (e.g., PushBullet, SMTP) and AI platforms (e.g., OpenAI, DeepSeek).
3. **Infrastructure Costs**: Requires a PC, server, or cloud hosting (e.g., AWS t3.micro at ~$10/month) for 24/7 operation.
4. **Maintenance and Support**: Open-source support via GitHub; Active subscribers to our Pro or Business Plans get priority email support.
## Advanced features
### Setting up email notification
To send email notifications, you need to specify recipient email addresses in the `email` of a `user` or a notification setting. You can configure multiple users with individual or multiple email addresses like this:
```toml
[user.user1]
email = 'user1@gmail.com'
[user.user2]
email = ['user2@gmail.com', 'user2@outlook.com']
```
An SMTP server is required for sending emails, for which you will need to know `smtp_server`, `smtp_port`, `smtp_username` and `smtp_password`. Generally speaking, you will need to create a notification section with the information obtained from your email service provider.
```toml
[notification.myprovider]
smtp_username = 'username@EMAIL.COM' # default to email
smtp_server = 'smtp.EMAIL.COM' # default to smtp.EMAIL.COM
smtp_port = 587 # default for most providers
smtp_password = 'mypassword'
```
`ai-marketplace-monitor` will try to use `email` if `smtp_username` is unspecified, and determine `smtp_username` and `smtp_server` automatically from the sender email address. For example, your Gmail setup could be as simple as:
```toml
[notification.gmail]
smtp_password = 'abcdefghijklmnop'
```
You can specify `smtp_password` directly in the `user` section if you are not sharing the `notification` setting with other users.
```toml
[user.me]
email = 'myemail@gmail.com'
smtp_password = 'abcdefghijklmnop'
```
**Note:**
- **Gmail Users**; Your will need to create a separate app password for your Google account as `smtp_password`.
- **Commercial Users**: If you are a subscriber to our Pro or Business Plans, detailed instructions on configuring the SMTP service we provide will be sent to you via email.
### Adjust prompt and notification level
_ai-marketplace-monitor_ asks AI services to evaluate listings against the criteria that you specify with prompts in four parts:
Part 1: buyer intent
```
A user wants to buy a ... with search phrase ... description ..., price range ...,
with keywords .... and exclude ...
```
Part 2: listing details
```
The user found a listing titled ... priced at ..., located ... posted at ...
with description ...
```
Part 3: instruction to AI
```
Evaluate how well this listing matches the user's criteria. Assess the description,
MSRP, model year, condition, and seller's credibility.
```
Part 4: rating instructions
```
Rate from 1 to 5 based on the following:
1 - No match: Missing key details, wrong category/brand, or suspicious activity (e.g., external links).
2 - Potential match: Lacks essential info (e.g., condition, brand, or model); needs clarification.
3 - Poor match: Some mismatches or missing details; acceptable but not ideal.
4 - Good match: Mostly meets criteria with clear, relevant details.
5 - Great deal: Fully matches criteria, with excellent condition or price.
Conclude with:
"Rating [1-5]: [summary]"
where [1-5] is the rating and [summary] is a brief recommendation (max 30 words)."
```
Depending on your specific needs, you can replace part 3 and part 4 of the prompt with options `prompt` and `rating_prompt`, and add an extra prompt before rating prompt with option `extra_prompt`. These options can be specified at the `marketplace` and `item` levels, with the latter overriding the former.
For example, you can add
```toml
[marketplace.facebook]
extra_prompt = """Exclude any listing that recommend visiting an external website \
for purchase."""
```
to describe suspicious listings in a marketplace, and
```toml
[item.ipadpro]
prompt = """Find market value for listing on market places like Ebay \
or Facebook marketplace and compare the price of the listing, considering \
the description, selling price, model year, condition, and seller's \
credibility. Evaluate how well this listing matches the user's criteria.
"""
```
With these settings, the part 3 of the prompt for item `ipadpro` will be replaced
with `prompt` for `item.ipadpro` and the `extra_prompt` from `marketplace.facebook`.
When AI services are used, the program by default notifies you of all listing with a rating of 3 or higher. You can change this behavior by setting for example
```toml
rating = 4
```
to see only listings that match your criteria well. Note that all listings after non-AI-based filtering will be returned if no AI service is specified or non-functional.
### Advanced Keyword-based filters
Options `keywords` and `antikeywords` are used to filter listings according to specified keywords. In the simplest form, these options support a single string. For example,
```toml
keywords = 'drone'
antikeywords = 'Parrot'
```
will select all listings with `drone` in title or description, and `Parrot` not in title or description. You can use multiple keywords and operators `AND`, `OR`, and `NOT` in the parameter. For example
```toml
keywords = 'DJI AND drone'
```
looks for listings with both `DJI` and `drone` in title or description.
If you have multiple keywords specified in a list, they are by default joint by `OR`. That is to say,
```toml
keywords = ['drone', 'DJI', 'Orqa']
antikeywords = ['Parrot', 'Autel']
```
is equivalent to
```toml
keywords = 'drone OR DJI OR Orqa'
antikeywords = 'Parrot OR Autel'
```
which means selecting listings that contains `drone` or `DJI` or `Orga` in title or description, but exclude those listings with `Parrot` or `Autel` in title or description.
These criteria will however, not exclude listings for a `DJI Camera`. If you would like to make sure that `drone` is selected, you can use
```toml
keywords = 'drone AND (DJI OR Orqa)'
antikeywords = 'Parrot OR Autel'
```
If you have special characters and spaces in your keywords, you will need to quote them, such as
```toml
keywords = '("Go Pro" OR gopro) AND HERO'
```
**NOTE**:
1. A list of logical operations are allowed, and they are assumed to be joint by `OR`. For example, `['gopro AND (11 or 12)', 'DJI AND OSMO']` searches for either a gopro version 11 or 12, or a DJI COMO camera.
2. You can construct very complex logical operations using `AND`, `OR` and `NOT`, but it is usually recommended to use simple keyword-based filtering and let AI handle more subtle selection criteria.
### Searching multiple cities and regions
`search_city` is the name, sometimes numbers, used by Facebook marketplace to represent a city. To get the value of `search_city` for your region, visit facebook marketplace, perform a search, and the city should be the name after `marketplace` (e.g. `XXXXX` in a URL like `https://www.facebook.com/marketplace/XXXXX/search?query=YYYY`).
Multiple searches will be performed if multiple cities are provided to option `search_city`. You can also specify `seller_locations` to limit the location of sellers. These locations are names of cities as displayed on the listing pages.
```toml
[item.name]
search_city = ['city1', 'city2']
seller_locations = ['city1', 'city2', 'city3', 'city4']
```
You can also increase the radius of search using
```toml
[item.name]
search_city = ['city1', 'city2']
radius = 50
```
However, if you would like to search for a larger region (e.g. the USA), it is much easier to define `region`s with a list of `search_city` and large `radius`.
_ai-marketplace-monitor_ defines the following regions in its system
[config.toml](https://github.com/BoPeng/ai-marketplace-monitor/blob/main/src/ai_marketplace_monitor/config.toml):
- `usa` for USA (without AK or HI)
- `usa_full` for USA
- `can` for Canada
- `mex` for Mexico
- `bra` for Brazil
- `arg` for Argentina
- `aus` for Australia
- `aus_miles` for Australia using 500 miles radius
- `nzl` for New Zealand
- `ind` for India
- `gbr` for United Kingdom
- `fra` for France
- `spa` for Spain
Now, if you would like to search an item across the US, you can
```toml
[item.name]
search_region = 'usa'
seller_locations = []
delivery_method = 'shipping'
```
Under the hood, _ai-marketplace-monitor_ will simply replace `search_region` with corresponding pre-defined `search_city` and `radius`. Note that `seller_locations` does not make sense and need to be set to empty for region-based search, and it makes sense to limit the search to listings that offer shipping.
### Support for non-English languages
_AI Marketplace Monitor_ relies on specific keywords from webpages to extract relevant information. For example, it looks for words following `Condition` to determine the condition of an item. If your account is set to another language, _AI Marketplace Monitor_ will be unable to extract the relevant information. That is to say, if you see rampant error messages like
```
Failed to get details of listing https://www.facebook.com/marketplace/item/12121212121212121212
The listing might be missing key information (e.g. seller) or not in English.
Please add option language to your marketplace configuration is the latter is the case.
See https://github.com/BoPeng/ai-marketplace-monitor?tab=readme-ov-file#support-for-non-english-languages for details.
```
you will need to check `Setting -> Language` settings of your facebook account,
and let _AI Marketplace Monitor_ use the same language.
Currently, _AI Marketplace Monitor_ supports the following languages
- `es`: Spanish
- `zh`: Chinese
If your language is not defined, you will need to define your own [`translation` section](docs/README.md#translators) in your configuration file, following a format used by existing translators defined in [config.toml](https://github.com/BoPeng/ai-marketplace-monitor/blob/main/src/ai_marketplace_monitor/config.toml). This can be done by
1. Add a section to your configuration file, by copying one example from the system translators, for example,
```toml
[translator.LAN]
locale = "Your REGION"
"About this vehicle" = "Descripción del vendedor"
"Seller's description" = "Información sobre este vehículo"
"Collection of Marketplace items" = "Colección de artículos de Marketplace"
"Condition" = "Estado"
"Details" = "Detalles"
"Location is approximate" = "La ubicación es aproximada"
"Description" = "Descripción"
```
2. Find example listings (from for example [here](https://github.com/BoPeng/ai-marketplace-monitor/issues/29#issuecomment-2632057196)), locate the relevant words, and update the section. You can switch between different langauges (Facebook -> Settings -> Language) and see the location of the English version.
3. After you have completed the translation, add `language="LAN"` to the `marketplace` section as follows:
```toml
[translation.LAN]
"Condition" = "Condition in your LAN"
"Details" = "Details in your LAN"
...
```
in your configuration file, then add `language="LAN"` to the `marketplace` section as follows:
```toml
[marketplace.facebook]
language = "LAN"
```
It would be very helpful for other users of _AI Marketplace Monitor_ if you could contribute your dictionary to this project by creating a pull request or simply creating a ticket with your translations.
### Check individual listing
If you ever wonder why a listing was excluded, or just want to check a listing against your configuration, you can get the URL (or the item ID) of the listing, and run
```sh
ai-marketplace-monitor --check your-url
```
If you have multiple items specified in your config file, _ai-marketplace-monitor_ will check the product against the configuration of all of them. If you know the _name_ of the item in your config file, you can let the program only check the configuration of this particular item.
```sh
ai-marketplace-monitor --check your-url --for item_name
```
Option `--check` will load the details of the item from the cache if it was previously examined. Otherwise a browser will be started to retrieve the page.
Another way to check individual IDs is to enter interactive mode when the _ai-marketplace-monitor_ is running. If you press `Esc`, then confirm with `c` when prompted, you can enter the `URL` and `item_name` interactively and check the URL. Enter `exit` to exit the interactive session after you are done. However, using this method requires OS to allow the program to monitor your keyboard. It would not work on a terminal accessed through SSH, and you have to allow the terminal that you use to run _ai-marketplace-monitor_ to monitor keyboard from the _Privacy and Security_ settings on MacOS.
### Multiple marketplaces
Although facebook is currently the only supported marketplace, you can create multiple marketplaces such as`marketplace.city1` and `marketplace.city2` with different options such as `search_city`, `search_region`, `seller_locations`, and `notify`. You will need to add options like `marketplace='city1'` in the items section to link these items to the right marketplace.
For example
```toml
[marketplace.facebook]
search_city = 'houston'
seller_locations = ['houston', 'sugarland']
[marketplace.nationwide]
search_region = 'usa'
seller_location = []
delivery_method = 'shipping'
[item.default_item]
search_phrases = 'local item for default market "facebook"'
[item.rare_item1]
marketplace = 'nationwide'
search_phrases = 'rare item1'
[item.rare_item2]
marketplace = 'nationwide'
search_phrases = 'rare item2'
```
If no `marketplace` is defined for an item, it will use the first defined marketplace, which is `houston` in this example.
### First and subsequent searches
A list of two values can be specified for options `rating`, `availability`, `date_listed`, and `delivery_method`, with the first one used for the first search, and second one used for the rest of searches. This allows the use of different search strategies for first and subsequent searches. For example, an initial more lenient search for all listings followed by searches for only new listings can be specified as
```
rating = [2, 4]
availability = ["all", "in"]
date_listed = ["all", "last 24 hours"]
```
### Showing statistics
_ai-marketplace-monitor_ shows statistics such as the number of pages searched, number of listings examined and excluded, number of matching lists found and number of users notified when you exit the program. If you would like to see the statistics during monitoring, press `Esc` and wait till the current search to end.
Counters are persistent across program runs. If you would like to reset the counters, use
```
ai-marketplace-monitor --clear-cache counters
```
### Self-hosted Ollama Model
If you have access to a decent machine and prefer not to pay for AI services from OpenAI or other vendors. You can opt to install Ollama locally and access it using the `provider = "ollama"`. If you have ollama on your local host, you can use
```
[ai.ollama]
base_url = "http://localhost:11434/v1"
model = "deepseek-r1:14b"
timeout = 120
```
Note that
1. Depending on your hardware configuration, you can choose any of the models listed [here](https://ollama.com/search). The default model is `deepseek-r1:14b` becaue it appears to work better than `llama-3.1:8b`.
2. You need to `pull` the model before you can use it.
### Cache Management
_ai-marketplace-monitor_ caches listing details, ai inquiries, and user notifications to avoid repeated queries to marketplaces, AI services, and repeated notification. If for any reason you would like to clear the cache, you can use commands such as
```
ai-marketplace-monitor --clear-cache listing-details
```
to clear the cache. The following cache types are supported
- `listing-details`
- `ai-inquiries`
- `user-notification`
- `counters`
`--clear-cache all` is also possible but not recommended.
### Support for different layouts of facebook listings
Facebook marketplace supports a wide variety of products and use different layouts for them. _ai_marketplace_monitor_ can extract description from common listings such as household items and automobiles, but you may encounter items that this program cannot handle.
Although I certainly do not have the bandwidth to support all possible layouts, I have listed detailed steps on how to debug and resolve the issue on [issue 29](https://github.com/BoPeng/ai-marketplace-monitor/issues/29).
### Searching Anonymously with a Proxy Server
You can search Facebook Marketplace anonymously by disabling login,
- Do not provide a `username` or `password` in the `facebook` section
- (optional) Set `login_wait_time = 0` to stop waiting for login
- (optional) Use the `--headless` command line option to run `ai-marketplace-monitor` without a browser window.
If you would like to use a proxy server, you can
- Sign up for a VPN or proxy service.
- Configure the proxy settings in the `monitor` section of your configuration file as follows
```toml
[monitor]
proxy_server = '${PROXY_SERVER}'
proxy_username = '${PROXY_USERNAME}'
proxy_password = '${PROXY_PASSWORD}'
```
Replace `${PROXY_SERVER}`, `${PROXY_USERNAME}`, and `${PROXY_PASSWORD}` with your proxy service details, or setting the corresponding environment variables.
## Contributing
Contributions are welcome! Here are some ways you can contribute:
- 🐛 Report bugs and issues
- 💡 Suggest new features
- 🔧 Submit pull requests
- 📚 Improve documentation
- 🏪 Add support for new marketplaces
- 🌍 Add support for new regions and languages
- 🤖 Add support for new AI providers
- 📱 Add new notification methods
Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a Pull Request.
## License
This project is licensed under the **Affero General Public License (AGPL)**. For the full terms and conditions, please refer to the official [GNU AGPL v3](https://www.gnu.org/licenses/agpl-3.0.en.html).
## Support
We provide multiple ways to access support and contribute to AI Marketplace Monitor:
- 📖 [Documentation](https://github.com/BoPeng/ai-marketplace-monitor/blob/main/docs/README.md) Explore comprehensive guides and instructions.
- 🤝 [Discussions](https://github.com/BoPeng/ai-marketplace-monitor/discussions): Connect with the community, ask questions, and exchange ideas.
- 🐛 [Issues](https://github.com/BoPeng/ai-marketplace-monitor/issues): Report bugs or suggest new features to help improve the project.
- 💖 [Become a sponsor](https://github.com/sponsors/BoPeng): Support the development and maintenance of this tool. Any contribution, no matter how small, is deeply appreciated.
- 💰 [Donate via PayPal](https://www.paypal.com/donate/?hosted_button_id=3WT5JPQ2793BN): Prefer private support? Consider donating via PayPal.
**Important Note:**
Due to time constraints, answering individual inquiries about _AI Marketplace Monitor_ on a one-on-one basis is not scalable. While I enjoy engaging on platforms like Reddit, GitHub, and email, I am generally unable to respond to personal emails or direct messages unless:
- You are a sponsor or donor.
- Your inquiry is related to business opportunities.
I greatly appreciate your understanding. To help expedite responses, please remember to mention your **sponsor or donation status** when contacting me.
## Credits
- Some of the code was copied from [facebook-marketplace-scraper](https://github.com/passivebot/facebook-marketplace-scraper).
- Region definitions were copied from [facebook-marketplace-nationwide](https://github.com/gmoz22/facebook-marketplace-nationwide/), which is released under an MIT license as of Jan 2025.
- This package was created with [Cookiecutter](https://github.com/cookiecutter/cookiecutter) and the [cookiecutter-modern-pypackage](https://github.com/fedejaure/cookiecutter-modern-pypackage) project template.

29
SECURITY.md Normal file
View File

@@ -0,0 +1,29 @@
# Security Policy
We takes the security of our software products seriously.
If you believe you have found a security vulnerability, please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Report security vulnerabilities by emailing the lead maintainer at email.
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
## Preferred Languages
We prefer all communications to be in English.

10
codecov.yml Normal file
View File

@@ -0,0 +1,10 @@
coverage:
status:
project:
default:
target: "100"
patch:
default:
target: "100"
comment:
require_changes: true

150
conftest.py Normal file
View File

@@ -0,0 +1,150 @@
import shutil
import tempfile
from typing import Callable, Generator
import pytest
from diskcache import Cache
from pytest import TempPathFactory
import ai_marketplace_monitor
from ai_marketplace_monitor.ai import (
AIResponse, # type: ignore
OllamaBackend,
OllamaConfig,
)
from ai_marketplace_monitor.facebook import FacebookItemConfig, FacebookMarketplaceConfig
from ai_marketplace_monitor.listing import Listing
from ai_marketplace_monitor.user import User, UserConfig
@pytest.fixture
def version() -> Generator[str, None, None]:
"""Sample pytest fixture."""
yield ai_marketplace_monitor.__version__
@pytest.fixture
def listing() -> Listing:
return Listing(
marketplace="facebook",
name="test",
id="111",
title="dddd",
image="",
price="$10",
post_url="https://www.facebook.com/marketplace/item/1234567890",
location="houston, tx",
seller="some guy",
condition="New",
description="something good",
)
@pytest.fixture
def marketplace_config() -> FacebookMarketplaceConfig:
return FacebookMarketplaceConfig(
name="facebook",
username="XXXXXXXX",
password="XXXXXXXX",
login_wait_time=10,
seller_locations=["city"],
search_city=["houston"],
availability=["all"],
condition=["new", "used_good"],
date_listed=[7],
delivery_method=["local_pick_up"],
exclude_sellers=["seller"],
max_search_interval=1000,
search_interval=12,
notify=["user1"],
radius=[100],
search_region=["usa"],
)
@pytest.fixture
def item_config() -> FacebookItemConfig:
return FacebookItemConfig(
name="test",
description="long description",
enabled=True,
antikeywords=["exclude1", "exclude2"],
keywords=["include1", "include2"],
search_phrases=["search word one"],
marketplace="facebook",
search_city=["houston"],
# the following are common options
seller_locations=["city"],
condition=["new", "used_good"],
date_listed=[7],
ai=["openai"],
availability=["out", "all"],
delivery_method=["local_pick_up"],
exclude_sellers=["seller"],
max_price=300,
rating=[4],
max_search_interval=1000,
search_interval=12,
min_price=200,
notify=["user1"],
radius=[100],
search_region=["usa"],
)
@pytest.fixture
def ollama_config() -> OllamaConfig:
return OllamaConfig(
name="ollama",
api_key="ollama",
provider="ollama",
base_url="http://localhost:11434/v1",
model="llama3.1:8b",
max_retries=10,
)
@pytest.fixture(scope="session")
def config_file(tmp_path_factory: TempPathFactory) -> Callable:
def generate_config_file(content: str) -> str:
fn = tmp_path_factory.mktemp("config") / "test.toml"
with open(fn, "w") as f:
f.write(content)
return str(fn)
return generate_config_file
@pytest.fixture
def temp_cache() -> Generator[Cache, None, None]:
temp_dir = tempfile.mkdtemp()
cache = Cache(temp_dir)
yield cache
cache.close()
shutil.rmtree(temp_dir)
@pytest.fixture
def user_config() -> UserConfig:
return UserConfig(
name="test",
pushbullet_token="whatever",
max_retries=1,
retry_delay=1,
remind=True,
)
@pytest.fixture
def user(user_config: UserConfig) -> User:
return User(user_config)
@pytest.fixture
def ollama(ollama_config: OllamaConfig) -> User:
return OllamaBackend(ollama_config)
@pytest.fixture
def ai_response() -> AIResponse:
return AIResponse(score=4, comment="good")

BIN
docs/AIMM_dark.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

BIN
docs/AIMM_light.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

BIN
docs/AIMM_neutral.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

325
docs/README.md Normal file
View File

@@ -0,0 +1,325 @@
# Configuration Guide
**Table of content:**
- [AI Services](#ai-services)
- [Marketplaces](#marketplaces)
- [Users](#users)
- [Notification](#notification)
- [Email notification](#email-notification)
- [Items to search](#items-to-search)
- [Common item and marketplace options](#common-item-and-marketplace-options)
- [Regions](#regions)
- [Translators](#translators)
- [Monitor Configuration](#monitor-configuration)
- [Additional options](#additional-options)
The AI Marketplace Monitor uses [TOML](https://toml.io/en/) configuration files to control its behavior. The system will always check for a configuration file at `~/.ai-marketplace-monitor/config.toml`. You can specify additional configuration files using the `--config` option.
To avoid including sensitive information directly in the configuration file, all options that accept a string or a list of string can be specified using the `${ENV_VAR}` format. For example
```toml
[marketplace.facebook]
password = '${FACEBOOK_PASSWORD}'
[user.me]
email = ['${EMAIL_1}', '${EMAIL_2}']
pushbullet_token = '${PUSBULLET_TOKEN}'
```
_AI Marketplace Monitor_ will retrieve the value from the corresponding environment variable and raise an error if the environment variable does not exist.
Here is a complete list of options that are acceptable by the program. [`example_config.toml`](example_config.toml) provides an example with many of the options.
### AI Services
One of more sections to list the AI agent that can be used to judge if listings match your selection criteria. The options should have header such as `[ai.openai]` or `[ai.deepseek]`, and have the following keys:
| Option | Requirement | DataType | Description |
| ------------- | ----------- | -------- | ---------------------------------------------------------- |
| `provider` | Optional | String | Name of the AI service provider. |
| `api-key` | Optional | String | A program token to access the RESTful API. |
| `base_url` | Optional | String | URL for the RESTful API |
| `model` | Optional | String | Language model to be used. |
| `max_retries` | Optional | Integer | Max retry attempts if connection fails. Default to 10. |
| `timeout` | Optional | Integer | Timeout (in seconds) waiting for response from AI service. |
Note that:
1. `provider` can be [OpenAI](https://openai.com/),
[DeepSeek](https://www.deepseek.com/), or [Ollama](https://ollama.com/). The name of the ai service will be used if this option is not specified so `OpenAI` will be used for section `ai.openai`.
2. [OpenAI](https://openai.com/) and [DeepSeek](https://www.deepseek.com/) models sets default `base_url` and `model` for these providers.
3. Ollama models require `base_url`. A default model is set to `deepseek-r1:14b`, which seems to be good enough for this application. You can of course try [other models](https://ollama.com/library) by setting the `model` option.
4. Although only three providers are supported, you can use any other service provider with `OpenAI`-compatible API using customized `base_url`, `model`, and `api-key`.
5. You can use option `ai` to list the AI services for particular marketplaces or items.
A typical section for OpenAI looks like
```toml
[ai.openai]
api_key = 'sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
```
### Marketplaces
One or more sections `marketplace.name` show the options for interacting with various marketplaces.
| Option | Requirement | DataType | Description |
| ------------------ | ----------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `market_type` | Optional | String | The supported marketplace. Currently, only `facebook` is supported. |
| `username` | Optional | String | Username can be entered manually or kept in the config file. |
| `password` | Optional | String | Password can be entered manually or kept in the config file. |
| `login_wait_time` | Optional | Integer | Time (in seconds) to wait before searching to allow enough time to enter CAPTCHA. Defaults to 60. |
| `language` | Optional | String | Language for webpages |
| **Common options** | | | Options listed in the [Common options](#common-options) section below that provide default values for all items. |
1. Multiple marketplaces with different `name`s can be specified for different `item`s (see [Multiple marketplaces](../README.md#multiple-marketplaces)). However, because the default `marketplace` for all items are `facebook`, it is easiest to define a default marketplace called `marketplace.facebook`.
2. If `language="LAN"` is specified, it must match to one of `translation` sections, defined by yourself or in the system configuration file. The system will try exact match (e.g. `es` to `es` or `zh_CN` to `zh_CN`), then partial match (e.g. `es` to `es_CO` or `es_CO` to `es`).
3. Please see [Support for non-English languages](../README.md#support-for-non-english-languages) on how to set this option and define your own translations.
### Users
One or more `user.username` sections can be defined in the configuration. The `username` one of the usernames listed in the `notify` option of `marketplace` or `item`. Each `user` section accepts the following options
| Option | Requirement | DataType | Description |
| ------------- | ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `notify_with` | Optional | String/List | Specifies one or more notification methods to be used for this user. If left unspecified, all available notification methods will be used. |
| `remind` | Optional | String | Enables repeated notifications for the user after a specified duration (e.g., 3 days) if a listing remains active. By default, users are notified only once. |
Note that
1. **Default Notification Behavior**: If the `notify_with` option is not specified, the system will use all available notification methods for the user.
2. **Inline Notification Settings**: Notification settings can be defined directly under the user section. Any settings described in the [Notification](#notification) section can be applied to a user's configuration.
3. **Repeated Notifications**: The `remind` option allows users to receive repeated notifications after a specified time interval. If not set, users will only be notified once about a listing.
### Notification
_AI Marketplace Monitor_ supports various notification methods, allowing you to configure notifications in a flexible way. You can define notification settings directly within the `user` sections or create dedicated `notification.NAME` sections and reference them using the `notify_with` option. This provides flexibility for single-user setups or shared configurations across multiple users.
#### Direct Notification Settings in User Sections
Define notification details directly within the user section. This approach is ideal for single-user configurations.
```toml
[user.me]
pushbullet_token = "xxxxxxxxxxxxxxxx"
email = 'myemail@gmail.com'
smtp_password = 'abcdefghijklmnop'
```
#### Shared Notification Settings in Dedicated Sections
Define notification methods in their own `notification.NAME` sections and reference them using the notify_with option. This approach is better for sharing settings across multiple users.
```toml
[user.me]
email = 'myemail@gmail.com'
notify_with = ['gmail', 'pushbullet']
[user.other]
email = 'other.email@gmail.com'
notify_with = ['gmail']
[notification.gmail]
smtp_password = 'abcdefghijklmnop'
[notification.pushbullet]
pushbullet_token = "xxxxxxxxxxxxxxxx"
```
Note that:
1. Under the hood, _AI Marketplace Monitor_ merges all notification options into the user section. This allows you to share partial settings across users (e.g. `smtp_password`) while customizing specific details (e.g. `email`).
2. If `notify_with` is not specified, the system will automatically include all notification settings for the user, so the `notify_with` option for `user.me` could be ignored.
3. AI Marketplace Monitor does not support multiple notifications of the same type for a single user. For example, the following configuration is not supported:
```toml
[user.me]
notify_with = ['pushbullet1', 'pushbullet2']
```
If you need to send notifications through multiple instances of the same type (e.g., multiple Pushbullet tokens), you must create separate users for each instance. For example:
```toml
[user.me]
notify_with = 'pushbullet1'
[user.other]
notify_with = 'pushbullet2'
[notification.pushbullet1]
pushbullet_token = "xxxxxxxxxxxxxxxx"
[notification.pushbullet2]
pushbullet_token = "yyyyyyyyyyyyyyyy"
```
#### Common Notification settings
| Option | Requirement | DataType | Description |
| ------------- | ----------- | -------- | ----------------------------------------------------------------- |
| `max_retries` | Optional | Integer | Number of attempts to retry a notification. Defaults to `5`. |
| `retry_delay` | Optional | Integer | Time in seconds to wait between retry attempts. Defaults to `60`. |
These settings are shared across all notification methods. For example, if you are notifying with `notify_with=['gmail', 'pushbullet']`, the same `max_retries` and `retry_delay` will apply to both methods.
#### Pushbullet notification
| Option | Requirement | DataType | Description |
| ------------------------- | ----------- | -------- | ----------------------------- |
| `pushbullet_token` | Optional | String | Token for user. |
| `pushbullet_proxy_type` | Optional | String | HTTP proxy type, e.g. `https` |
| `pushbullet_proxy_server` | Optional | String | HTTP proxy server URL |
Please refer to [PushBullet documentation](https://github.com/richard-better/pushbullet.py/blob/master/readme-old.md) for details on the use of a proxy server for pushbullet.
#### Pushover notification
| Option | Requirement | DataType | Description |
| -------------------- | ----------- | -------- | ------------------- |
| `pushover_user_id` | Optional | String | Pushover user key. |
| `pushover_api_token` | Optional | String | Pushover API Token. |
#### Pushover notification
| Option | Requirement | DataType | Description |
| ---------------- | ----------- | -------- | ------------------------------------------------- |
| `ntfy_server` | Optional | String | ntfy server, default to `https://ntfy.sh` |
| `ntfy_topic` | Optional | String | A unique topic to receive your notification. |
| `message_format` | Optional | String | Format notification as `plain_text` or `markdown` |
- According to [ntfy documentation](https://docs.ntfy.sh/publish/#markdown-formatting), markdown format is supported only by web app. Therefore, `message_format` is by default set to `plain_text`.
### Email notification
| Option | Requirement | DataType | Description |
| --------------- | ----------- | ----------- | ------------------------------------------------------- |
| `email` | Optional | String/List | One or more email addresses for email notifications |
| `smtp_username` | Optional | String | SMTP username. |
| `smtp_password` | Required | String | A password or passcode for the SMTP server. |
| `smtp_server` | Optional | String | SMTP server, usually guessed from sender email address. |
| `smtp_port` | Optional | Integer | SMTP port, default to `587` |
Note that
1. We provide default `smtp_server` and `smtp_port` values for popular SMTP service providers.
2. `smtp_username` is assumed to be the first `email`.
See [Setting up email notification](../README.md#setting-up-email-notification) for details on how to set up email notification.
### Items to search
One or more `item.item_name` where `item_name` is the name of the item.
| Option | Requirement | DataType | Description |
| ------------------ | ----------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `search_phrases` | Required | String/List | One or more strings for searching the item. |
| `description` | Optional | String | A longer description of the item that better describes your requirements (e.g., manufacture, condition, location, seller reputation, shipping options). Only used if AI assistance is enabled. |
| `keywords` | Optional | String/List | Excludes listings whose titles and description do not contain any of the keywords. |
| `antikeywords` | Optional | String/List | Excludes listings whose titles or descriptions contain any of the specified keywords. |
| `marketplace` | Optional | String | Name of the marketplace, default to `facebook` that points to a `marketplace.facebook` sectiion. |
| **Common options** | | | Options listed below. These options, if specified in the item section, will override options in the marketplace section. |
Marketplaces may return listings that are completely unrelated to search search_phrases, but can also
return related items under different names. To select the right items, you can
1. Use `keywords` to keep only items with certain words in the title. For example, you can set `keywords = ['gopro', 'go pro']` when you search for `search_phrases = 'gopro'`.
2. Use `antikeywords` to narrow down the search. For example, setting `antikeywords=['HERO 4']` will exclude items with `HERO 4` or `hero 4`in the title or description.
3. The `keywords` and `antikeywords` options allows the specification of multiple keywords with a `OR` relationship, but it also allows complex `AND`, `OR` and `NOT` logics. See [Advanced Keyword-based filters](../README.md#advanced-keyword-based-filters) for details.
4. It is usually more effective to write a longer `description` and let the AI know what exactly you want. This will make sure that you will not get a drone when you are looking for a `DJI` camera. It is still a good idea to pre-filter listings using non-AI criteria to reduce the cost of AI services.
### Common item and marketplace options
The following options that can specified for both `marketplace` sections and `item` sections. Values in the `item` section will override value in corresponding marketplace if specified in both places.
| `Parameter` | Required/Optional | Datatype | Description |
| --------------------- | ----------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `availability` | Optional | String/List | Shows output with `in` (in stock), `out` (out of stock), or `all` (both). |
| `condition` | Optional | String/List | One or more of `new`, `used_like_new`, `used_good`, and `used_fair`. |
| `date_listed` | Optional | String/Integer/List | One of `all`, `last 24 hours`, `last 7 days`, `last 30 days`, or `0`, `1`, `7`, and `30`. |
| `delivery_method` | Optional | String/List | One of `all`, `local_pick_up`, and `shipping`. |
| `exclude_sellers` | Optional | String/List | Exclude certain sellers by their names (not username). |
| `max_price` | Optional | Integer | Maximum price. |
| `max_search_interval` | Optional | String | Maximum interval in seconds between searches. If specified, a random time will be chosen between `search_interval` and `max_search_interval`. |
| `min_price` | Optional | Integer | Minimum price. |
| `notify` | Optional | String/List | Users who should be notified. |
| `ai` | Optional | String/List | AI services to use, default to all specified services. `ai=[]` will disable ai. |
| `city_name` | Optional | String/List | Corresponding name of `search_city`. |
| `radius` | Optional | Integer/List | Radius of search, can be a list if multiple `search_city` are specified. |
| `prompt` | Optional | String | Prompt to AI service that will replace the default prompt |
| `extra_prompt` | Optional | String | Additional prompt that will be inserted between regular and rating prompt |
| `ranking_prompt` | Optional | String | Ranking prompt that instruct how AI rates the listings |
| `rating` | Optional | Integer/List | Notify users with listings with rating at or higher than specified rating. |
| `search_city` | Required | String/List | One or more search cities, obtained from the URL of your search query. Required for marketplace or item if `search_region` is unspecified. |
| `search_interval` | Optional | String | Minimal interval between searches, should be specified in formats such as `1d`, `5h`, or `1h 30m`. |
| `search_region` | Optional | String/List | Search over multiple locations to cover an entire region. `regions` should be one or more pre-defined regions or regions defined in the configuration file. |
| `seller_locations` | Optional | String/List | Only allow searched items from these locations. |
| `start_at` | Optional | String/List | Time to start the search. Overrides `search_interval`. |
Note that
1. `search_city` can be found from the URL that facebook uses to search your region. For example, if the URL for your facebook search is `https://www.facebook.com/marketplace/sanfrancisco/search?query=go%20pro%2011%20deal%20site`, the `search_city` is `sanfrancisco`. This name is not necessarily the name of your city, especially for non-US cities, and you can search multiple cities or an entire region. See [Searching multiple cities and regions](../README.md#searching-multiple-cities-and-regions) for details.
2. If `notify` is not specified for both `item` and `marketplace`, all listed users will be notified.
3. `prompt`, `extra_prompt`, `rating_prompt`, and `rating` are used to adjust how to interact with an AI service. See [Adjust prompt and notification level](../README.md#adjust-prompt-and-notification-level) for details.
4. `start_at` supports one or more of the following values: <br> - `HH:MM:SS` or `HH:MM` for every day at `HH:MM:SS` or `HH:MM:00` <br> - `*:MM:SS` or `*:MM` for every hour at `MM:SS` or `MM:00` <br> - `*:*:SS` for every minute at `SS`.
5. A list of two values can be specified for options `rating`, `availability`, `delivery_method`, and `date_listed`. See [First and subsequent searches](../README.md#first-and-subsequent-searches) for details.
### Regions
One or more sections of `[region.region_name]`, which defines regions to search. Multiple searches will be performed for multiple cities to cover entire regions.
| Parameter | Required/Optional | Data Type | Description |
| ------------- | ----------------- | ------------ | --------------------------------------------------------------------------- |
| `search_city` | Required | String/List | One or more cities with names used by Facebook. |
| `full_name` | Optional | String | A display name for the region. |
| `radius` | Optional | Integer/List | Recommended `805` for regions using kms, and `500` for regions using miles. |
| `city_name` | Optional | String/List | Corresponding names for `search_city`. |
Note that
1. `radius` has a default value of `500` (miles). You can specify different `radius` for different `search_city`.
2. Options `full_name` and `city_name` are for documentation and logging purposes only.
### Translators
A translator contains a list of word mappings that translate English words to corresponding words in another language. They are used by _AI Marketplace Monitor_ to extract information from webpages in non-English languages.
This section currently accept the following values for Facebook Marketplace.
| Parameter | Required/Optional | Data Type | Description |
| --------------------------------- | ----------------- | --------- | ---------------------------------------------------------- |
| `locale` | Required | String | locale of the translation |
| `Collection of Marketplace items` | Optional | String | The "arial-label" for search results. |
| `Condition` | Optional | String | Subtitle "condition" of an listing item. |
| `Description` | Optional | String | Title "description" for a rental item. |
| `Details` | Optional | String | Subtitle "Details" of an listing item. |
| `Location is approximate` | Optional | String | The word below listing location. |
| `About this vehicle` | Optional | String | The "About this vehicle" section of an automobile listing. |
| `Seller's description` | Optional | String | The "Seller's description" of an automobile listing. |
Note that not all words needs to be translated (the English version will be used if unspecified), and _AI Marketplace Monitor_ may be able to extract information using language-independent methods.
Please see [Support for non-English languages](../README.md#support-for-non-english-languages)
### Monitor Configuration
The optional `monitor` section allows you to define system configurations for the _AI Marketplace Monitor_. It supports options for sending your queries through one or more proxy servers, which can hide your IP address and reduce the chances of your IP being blocked.
| Option | Requirement | DataType | Description |
| ---------------- | ----------- | ----------- | ---------------------------------------- |
| `proxy_server` | Optional | String/List | URL for one or more proxy servers. |
| `proxy_bypass` | Optional | String | Comma-separated domains to bypass proxy. |
| `proxy_username` | Optional | String | username for the proxy. |
| `proxy_password` | Optional | String | password for the proxy. |
- If multiple `proxy_server` URLs are specified as a list, a random one will be chosen each time. However, the proxy will not change while the _AI Marketplace Monitor_ is running.
### Additional options
All sections, namely `ai`, `marketplace`, `user`, `smtp`, and `region`, accepts an option `enabled`, which, if set to `false` will disable the corresponding AI service,
marketplace, SMTP server, and stop notifying corresponding user. This option works like a `comment` statement that comments out the entire sections, which allowing the
sections to be referred from elsewhere (e.g. `notify` a disable user is allowed but notification will not be sent.)
| Parameter | Required/Optional | Data Type | Description |
| --------- | ----------------- | --------- | ------------------------------------------------------ |
| `enabled` | Optional | Boolean | Disable corresponding configuration if set to `false`. |

1
docs/_static/custom.css vendored Normal file
View File

@@ -0,0 +1 @@
.logo a { overflow-wrap: normal }

1
docs/changelog.md Symbolic link
View File

@@ -0,0 +1 @@
../CHANGELOG.md

73
docs/conf.py Normal file
View File

@@ -0,0 +1,73 @@
"""Sphinx configuration."""
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
import ai_marketplace_monitor
# -- Project information -----------------------------------------------------
# General information about the project.
project = "ai-marketplace-monitor"
copyright = "2025, Bo Peng" # noqa: A001
author = "Bo Peng"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = ai_marketplace_monitor.__version__
# The full version, including alpha/beta/rc tags.
release = ai_marketplace_monitor.__version__
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
"sphinx.ext.napoleon",
"recommonmark",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"github_user": "BoPeng",
"github_repo": "ai-marketplace-monitor",
"github_banner": True,
"show_related": False,
"fixed_sidebar": True,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

60
docs/example_config.toml Normal file
View File

@@ -0,0 +1,60 @@
#
# AI
#
[ai.openai]
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
model = "gpt-4o"
#
# Marketplace
#
[marketplace.facebook]
search_city = 'city'
username = 'username'
password = 'password'
login_wait_time = 60
search_interval = '30m'
max_search_interval = '1h'
seller_locations = ['city', 'surrounding city']
notify = 'user1'
exclude_sellers = []
#
# Users and Notifications
#
[user.user1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
email = 'myself@gmail.com'
notify_with = ['gmail', 'pushover']
[user.user2]
email = 'user2@gmail.com'
notify_with = 'gmail'
[notification.pushover]
pushover_user_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
pushover_api_token = 'someone@gmail.com'
[notification.gmail]
smtp_username = 'myself@gmail.com'
smtp_password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
#
# Items to search
#
[item.name1]
search_phrases = 'search word one'
search_region = 'usa'
search_interval = '1d'
delivery_method = 'shipping'
seller_locations = []
[item.name2]
search_phrases = ['search word one', 'search word two']
description = "it should be from manufacture, the seller should not offer shipping."
keywords = ['search word']
antikeywords = ['exclude word one', 'exclude word two']
notify = 'user2'
search_city = 'another city'
seller_locations = ['another city', 'surrounding city']
exclude_sellers = []

22
docs/index.rst Normal file
View File

@@ -0,0 +1,22 @@
Welcome to AI Marketplace Monitor's documentation!
===========================================================
.. toctree::
:maxdepth: 2
readme
installation
usage
modules
changelog
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. toctree::
:hidden:
License <license>

23
docs/installation.rst Normal file
View File

@@ -0,0 +1,23 @@
.. highlight:: shell
============
Installation
============
Stable release
--------------
To install ai-marketplace-monitor, run this command in your terminal:
.. code-block:: console
$ pip install ai-marketplace-monitor
This is the preferred method to install ai-marketplace-monitor, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/

1
docs/license.rst Symbolic link
View File

@@ -0,0 +1 @@
../LICENSE.rst

9
docs/minimal_config.toml Normal file
View File

@@ -0,0 +1,9 @@
[marketplace.facebook]
username = 'username@gmail.com'
search_city = 'houston'
[item.name1]
search_phrases = 'search word one'
[user.user1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

2
docs/requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
sphinx==8.2.3
recommonmark==0.7.1

BIN
docs/search_in_action.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

7
docs/usage.rst Normal file
View File

@@ -0,0 +1,7 @@
=====
Usage
=====
To use ai-marketplace-monitor in a project::
import ai_marketplace_monitor

52
noxfile.py Normal file
View File

@@ -0,0 +1,52 @@
"""Nox sessions."""
import platform
import nox
from nox_poetry import Session, session
nox.options.sessions = ["tests", "mypy"]
python_versions = ["3.10", "3.11", "3.12"]
@session(python=python_versions)
def tests(session: Session) -> None:
"""Run the test suite."""
session.install(".")
session.install(
"invoke", "pytest", "xdoctest", "coverage[toml]", "pytest-cov", "pytest-playwright"
)
try:
session.run(
"inv",
"tests",
env={
"COVERAGE_FILE": f".coverage.{platform.system()}.{platform.python_version()}",
},
)
finally:
if session.interactive:
session.notify("coverage")
@session(python=python_versions)
def coverage(session: Session) -> None:
"""Produce the coverage report."""
args = session.posargs if session.posargs and len(session._runner.manifest) == 1 else []
session.install("invoke", "coverage[toml]")
session.run("inv", "coverage", *args)
@session(python=python_versions)
def mypy(session: Session) -> None:
"""Type-check using mypy."""
session.install(".")
session.install("invoke", "mypy")
session.run("inv", "mypy")
@session(python="3.12")
def security(session: Session) -> None:
"""Scan dependencies for insecure packages."""
session.install("invoke", "safety")
session.run("inv", "security")

2716
poetry.lock generated Normal file
View File

File diff suppressed because it is too large Load Diff

BIN
program.prof Normal file
View File

Binary file not shown.

204
pyproject.toml Normal file
View File

@@ -0,0 +1,204 @@
[tool.poetry]
name = "ai-marketplace-monitor"
version = "0.9.1"
description = "An AI-based tool for monitoring facebook marketplace"
authors = ["Bo Peng <ben.bob@gmail.com>"]
readme = "README.md"
homepage = "https://github.com/BoPeng/ai-marketplace-monitor"
repository = "https://github.com/BoPeng/ai-marketplace-monitor"
documentation = "https://ai-marketplace-monitor.readthedocs.io"
keywords = ["ai-marketplace-monitor"]
classifiers = [
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
[tool.poetry.urls]
"Bug Tracker" = "https://github.com/BoPeng/ai-marketplace-monitor/issues"
[tool.poetry.scripts]
ai-marketplace-monitor = 'ai_marketplace_monitor.cli:app'
[tool.poetry.dependencies]
python = ">=3.10"
typer = { extras = ["all"], version = "^0.15.1" }
playwright = ">=1.41.0"
rich = ">=13.7.0"
"pushbullet.py" = ">=0.12.0"
diskcache = ">=5.6.3"
watchdog = ">=4.0.0"
openai = ">=1.24.0"
parsedatetime = ">=2.5"
humanize = ">=4.0.0"
schedule = ">=1.2.2"
inflect = ">=7.0.0"
pynput = ">=1.7.0"
pillow = ">=10.0.0"
jinja2 = ">=3.0.0"
pyparsing = ">=3.1.0"
requests = ">=2.30.0"
tomli = { version = "2.2.1", markers = "python_version < '3.11'" }
[tool.poetry.group.dev.dependencies]
pre-commit = "^4.0.1"
invoke = "^2.2.0"
bump2version = "^1.0.1"
watchdog = { version = "^6.0.0", extras = ["watchmedo"] }
[tool.poetry.group.test.dependencies]
pytest = "^8.3.3"
xdoctest = "^1.2.0"
coverage = { version = "^7.6.7", extras = ["toml"] }
pytest-cov = "^6.0.0"
pytest-playwright = "^0.7.0"
[tool.poetry.group.linters.dependencies]
isort = ">=5.13.2,<7.0.0"
black = ">=24.10,<26.0"
ruff = "^0.9.2"
[tool.poetry.group.security.dependencies]
safety = "^3.2.11"
[tool.poetry.group.typing.dependencies]
mypy = "^1.13.0"
[tool.poetry.group.docs.dependencies]
sphinx = "^8.1.3"
recommonmark = "^0.7.1"
[tool.coverage.paths]
source = ["src", "*/site-packages"]
[tool.coverage.run]
branch = true
source = ["ai_marketplace_monitor"]
[tool.coverage.report]
fail_under = 100
exclude_lines = [
"pragma: no cover",
"def __repr__",
"if self.debug",
"if settings.DEBUG:",
"raise AssertionError",
"raise NotImplementedError",
"if 0:",
"if __name__ == __main__:",
]
show_missing = true
[tool.coverage.html]
directory = "htmlcov"
[tool.ruff]
target-version = "py39"
output-format = "full"
line-length = 99
fix = true
extend-exclude = ["docs/*"]
[tool.ruff.lint]
ignore = [
"ANN202", # **kwargs: Any
"ANN401",
"ANN002",
"ANN003",
"E722",
"G004",
"S311",
"B017",
"S106",
"G003",
"S101", # use of assert
"BLE001", # blank exception
"C901", # too complex (function name too long etc)
"D100", # docstring
"D101", # docstring
"D102", # docstring
"D103", # docstring
"D107", # docstring
"D415", # docstring
"ERA001", # commented code
"S108", # use of /tmp
"S603", # subprocess.run security
"S607", # subprocess.run with relative path
"E501", # line too long
"S112", # logging try/except/continue
]
select = [
"E",
"F",
"W", # flake8
"C", # mccabe
"I", # isort
"N", # pep8-naming
"D", # flake8-docstrings
"ANN", # flake8-annotations
"S", # flake8-bandit
"BLE", # flake8-blind-except
"B", # flake8-bugbear
"A", # flake8-builtins
"G", # flake8-logging-format
"ERA", # eradicate
"ISC", # flake8-implicit-str-concat
"RUF", # Ruff-specific rules
]
unfixable = [
"ERA", # Don't remove commented-out code
]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"]
[tool.ruff.lint.mccabe]
max-complexity = 10
[tool.ruff.lint.isort]
known-first-party = ["ai_marketplace_monitor"]
[tool.ruff.lint.pydocstyle]
convention = "google"
[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
line_length = 99
known_third_party = ["invoke", "nox", "nox_poetry"]
[tool.black]
line-length = 99
target-version = ["py39"]
[tool.mypy]
warn_return_any = false
warn_unused_configs = true
[[tool.mypy.overrides]]
module = ["pytest.*", "invoke.*", "nox.*", "nox_poetry.*"]
allow_redefinition = false
check_untyped_defs = true
ignore_errors = false
ignore_missing_imports = true
implicit_reexport = true
local_partial_types = true
strict_optional = true
strict_equality = true
no_implicit_optional = true
warn_unused_ignores = true
warn_unreachable = true
warn_no_return = true
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"

View File

@@ -0,0 +1,5 @@
"""Top-level package for ai-marketplace-monitor."""
__author__ = """Bo Peng"""
__email__ = "ben.bob@gmail.com"
__version__ = "0.9.1"

View File

@@ -0,0 +1,364 @@
import re
import time
from dataclasses import asdict, dataclass, field
from enum import Enum
from logging import Logger
from typing import Any, ClassVar, Generic, Optional, Type, TypeVar
from diskcache import Cache # type: ignore
from openai import OpenAI # type: ignore
from rich.pretty import pretty_repr
from .listing import Listing
from .marketplace import TItemConfig, TMarketplaceConfig
from .utils import BaseConfig, CacheType, CounterItem, cache, counter, hilight
class AIServiceProvider(Enum):
OPENAI = "OpenAI"
DEEPSEEK = "DeepSeek"
OLLAMA = "Ollama"
@dataclass
class AIResponse:
score: int
comment: str
name: str = ""
NOT_EVALUATED: ClassVar = "Not evaluated by AI"
@property
def conclusion(self: "AIResponse") -> str:
return {
1: "No match",
2: "Potential match",
3: "Poor match",
4: "Good match",
5: "Great deal",
}[self.score]
@property
def style(self: "AIResponse") -> str:
if self.comment == self.NOT_EVALUATED:
return "dim"
if self.score < 3:
return "fail"
if self.score > 3:
return "succ"
return "name"
@property
def stars(self: "AIResponse") -> str:
full_stars = self.score
empty_stars = 5 - full_stars
return (
'<span style="color: #FFD700; font-size: 20px;">★</span>' * full_stars
+ '<span style="color: #D3D3D3; font-size: 20px;">☆</span>' * empty_stars
)
@classmethod
def from_cache(
cls: Type["AIResponse"],
listing: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
local_cache: Cache | None = None,
) -> Optional["AIResponse"]:
res = (cache if local_cache is None else local_cache).get(
(CacheType.AI_INQUIRY.value, item_config.hash, marketplace_config.hash, listing.hash)
)
if res is None:
return None
return AIResponse(**res)
def to_cache(
self: "AIResponse",
listing: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
local_cache: Cache | None = None,
) -> None:
(cache if local_cache is None else local_cache).set(
(CacheType.AI_INQUIRY.value, item_config.hash, marketplace_config.hash, listing.hash),
asdict(self),
tag=CacheType.AI_INQUIRY.value,
)
@dataclass
class AIConfig(BaseConfig):
# this argument is required
api_key: str | None = None
provider: str | None = None
model: str | None = None
base_url: str | None = None
max_retries: int = 10
timeout: int | None = None
def handle_provider(self: "AIConfig") -> None:
if self.provider is None:
return
if self.provider.lower() not in [x.value.lower() for x in AIServiceProvider]:
raise ValueError(
f"""AIConfig requires a valid service provider. Valid providers are {hilight(", ".join([x.value for x in AIServiceProvider]))}"""
)
def handle_api_key(self: "AIConfig") -> None:
if self.api_key is None:
return
if not isinstance(self.api_key, str):
raise ValueError("AIConfig requires a string api_key.")
self.api_key = self.api_key.strip()
def handle_max_retries(self: "AIConfig") -> None:
if not isinstance(self.max_retries, int) or self.max_retries < 0:
raise ValueError("AIConfig requires a positive integer max_retries.")
def handle_timeout(self: "AIConfig") -> None:
if self.timeout is None:
return
if not isinstance(self.timeout, int) or self.timeout < 0:
raise ValueError("AIConfig requires a positive integer timeout.")
@dataclass
class OpenAIConfig(AIConfig):
def handle_api_key(self: "OpenAIConfig") -> None:
if self.api_key is None:
raise ValueError("OpenAI requires a string api_key.")
@dataclass
class DeekSeekConfig(OpenAIConfig):
pass
@dataclass
class OllamaConfig(OpenAIConfig):
api_key: str | None = field(default="ollama") # required but not used.
def handle_base_url(self: "OllamaConfig") -> None:
if self.base_url is None:
raise ValueError("Ollama requires a string base_url.")
def handle_model(self: "OllamaConfig") -> None:
if self.model is None:
raise ValueError("Ollama requires a string model.")
TAIConfig = TypeVar("TAIConfig", bound=AIConfig)
class AIBackend(Generic[TAIConfig]):
def __init__(self: "AIBackend", config: AIConfig, logger: Logger | None = None) -> None:
self.config = config
self.logger = logger
self.client: OpenAI | None = None
@classmethod
def get_config(cls: Type["AIBackend"], **kwargs: Any) -> TAIConfig:
raise NotImplementedError("get_config method must be implemented by subclasses.")
def connect(self: "AIBackend") -> None:
raise NotImplementedError("Connect method must be implemented by subclasses.")
def get_prompt(
self: "AIBackend",
listing: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
) -> str:
prompt = (
f"""A user wants to buy a {item_config.name} from Facebook Marketplace. """
f"""Search phrases: "{'" and "'.join(item_config.search_phrases)}", """
)
if item_config.description:
prompt += f"""Description: "{item_config.description}", """
#
max_price = item_config.max_price or 0
min_price = item_config.min_price or 0
if max_price and min_price:
prompt += f"""Price range: {min_price} to {max_price}. """
elif max_price:
prompt += f"""Max price {max_price}. """
elif min_price:
prompt += f"""Min price {min_price}. """
#
if item_config.antikeywords:
prompt += f"""Exclude keywords "{'" and "'.join(item_config.antikeywords)}" in title or description."""
#
prompt += (
f"""\n\nThe user found a listing titled "{listing.title}" in {listing.condition} condition, """
f"""priced at {listing.price}, located in {listing.location}, """
f"""posted at {listing.post_url} with description "{listing.description}"\n\n"""
)
# prompt
if item_config.prompt is not None:
prompt += item_config.prompt
elif marketplace_config.prompt is not None:
prompt += marketplace_config.prompt
else:
prompt += (
"Evaluate how well this listing matches the user's criteria. Assess the description, MSRP, model year, "
"condition, and seller's credibility."
)
# extra_prompt
prompt += "\n"
if item_config.extra_prompt is not None:
prompt += f"\n{item_config.extra_prompt.strip()}\n"
elif marketplace_config.extra_prompt is not None:
prompt += f"\n{marketplace_config.extra_prompt.strip()}\n"
# rating_prompt
if item_config.rating_prompt is not None:
prompt += f"\n{item_config.rating_prompt.strip()}\n"
elif marketplace_config.rating_prompt is not None:
prompt += f"\n{marketplace_config.rating_prompt.strip()}\n"
else:
prompt += (
"\nRate from 1 to 5 based on the following: \n"
"1 - No match: Missing key details, wrong category/brand, or suspicious activity (e.g., external links).\n"
"2 - Potential match: Lacks essential info (e.g., condition, brand, or model); needs clarification.\n"
"3 - Poor match: Some mismatches or missing details; acceptable but not ideal.\n"
"4 - Good match: Mostly meets criteria with clear, relevant details.\n"
"5 - Great deal: Fully matches criteria, with excellent condition or price.\n"
"Conclude with:\n"
'"Rating <1-5>: <summary>"\n'
"where <1-5> is the rating and <summary> is a brief recommendation (max 30 words)."
)
if self.logger:
self.logger.debug(f"""{hilight("[AI-Prompt]", "info")} {prompt}""")
return prompt
def evaluate(
self: "AIBackend",
listing: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
) -> AIResponse:
raise NotImplementedError("Confirm method must be implemented by subclasses.")
class OpenAIBackend(AIBackend):
default_model = "gpt-4o"
# the default is f"https://api.openai.com/v1"
base_url: str | None = None
@classmethod
def get_config(cls: Type["OpenAIBackend"], **kwargs: Any) -> OpenAIConfig:
return OpenAIConfig(**kwargs)
def connect(self: "OpenAIBackend") -> None:
if self.client is None:
self.client = OpenAI(
api_key=self.config.api_key,
base_url=self.config.base_url or self.base_url,
timeout=self.config.timeout,
)
if self.logger:
self.logger.info(f"""{hilight("[AI]", "name")} {self.config.name} connected.""")
def evaluate(
self: "OpenAIBackend",
listing: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
) -> AIResponse:
# ask openai to confirm the item is correct
counter.increment(CounterItem.AI_QUERY, item_config.name)
prompt = self.get_prompt(listing, item_config, marketplace_config)
res: AIResponse | None = AIResponse.from_cache(listing, item_config, marketplace_config)
if res is not None:
if self.logger:
self.logger.info(
f"""{hilight("[AI]", res.style)} {self.config.name} previously concluded {hilight(f"{res.conclusion} ({res.score}): {res.comment}", res.style)} for listing {hilight(listing.title)}."""
)
return res
self.connect()
retries = 0
while retries < self.config.max_retries:
self.connect()
assert self.client is not None
try:
response = self.client.chat.completions.create(
model=self.config.model or self.default_model,
messages=[
{
"role": "system",
"content": "You are a helpful assistant that can confirm if a user's search criteria matches the item he is interested in.",
},
{"role": "user", "content": prompt},
],
stream=False,
)
break
except KeyboardInterrupt:
raise
except Exception as e:
if self.logger:
self.logger.error(
f"""{hilight("[AI-Error]", "fail")} {self.config.name} failed to evaluate {hilight(listing.title)}: {e}"""
)
retries += 1
# try to initiate a connection
self.client = None
time.sleep(5)
# check if the response is yes
if self.logger:
self.logger.debug(f"""{hilight("[AI-Response]", "info")} {pretty_repr(response)}""")
answer = response.choices[0].message.content or ""
if (
answer is None
or not answer.strip()
or re.search(r"Rating[^1-5]*[1-5]", answer, re.DOTALL) is None
):
counter.increment(CounterItem.FAILED_AI_QUERY, item_config.name)
raise ValueError(f"Empty or invalid response from {self.config.name}: {response}")
lines = answer.split("\n")
# if any of the lines contains "Rating: ", extract the rating from it.
score: int = 1
comment = ""
rating_line = None
for idx, line in enumerate(lines):
matched = re.match(r".*Rating[^1-5]*([1-5])[:\s]*(.*)", line)
if matched:
score = int(matched.group(1))
comment = matched.group(2).strip()
rating_line = idx
continue
if rating_line is not None:
# if the AI puts comment after Rating, we need to include them
comment += " " + line
# if the AI puts the rating at the end, let us try to use the line before the Rating line
if len(comment.strip()) < 5 and rating_line is not None and rating_line > 0:
comment = lines[rating_line - 1]
# remove multiple spaces, take first 30 words
comment = " ".join([x for x in comment.split() if x.strip()]).strip()
res = AIResponse(name=self.config.name, score=score, comment=comment)
res.to_cache(listing, item_config, marketplace_config)
counter.increment(CounterItem.NEW_AI_QUERY, item_config.name)
return res
class DeepSeekBackend(OpenAIBackend):
default_model = "deepseek-chat"
base_url = "https://api.deepseek.com"
@classmethod
def get_config(cls: Type["DeepSeekBackend"], **kwargs: Any) -> DeekSeekConfig:
return DeekSeekConfig(**kwargs)
class OllamaBackend(OpenAIBackend):
default_model = "deepseek-r1:14b"
@classmethod
def get_config(cls: Type["OllamaBackend"], **kwargs: Any) -> OllamaConfig:
return OllamaConfig(**kwargs)

View File

@@ -0,0 +1,161 @@
"""Console script for ai-marketplace-monitor."""
import logging
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Annotated, List, Optional
import rich
import typer
from rich.logging import RichHandler
from . import __version__
from .utils import CacheType, amm_home, cache, counter, hilight
app = typer.Typer()
def version_callback(value: bool) -> None:
"""Callback function for the --version option.
Parameters:
- value: The value provided for the --version option.
Raises:
- typer.Exit: Raises an Exit exception if the --version option is provided,
printing the Awesome CLI version and exiting the program.
"""
if value:
typer.echo(f"AI Marketplace Monitor, version {__version__}")
raise typer.Exit()
@app.command()
def main(
config_files: Annotated[
List[Path] | None,
typer.Option(
"-r",
"--config",
help="Path to one or more configuration files in TOML format. `~/.ai-marketplace-monitor/config.toml will always be read.",
),
] = None,
headless: Annotated[
Optional[bool],
typer.Option("--headless", help="If set to true, will not show the browser window."),
] = False,
clear_cache: Annotated[
Optional[str],
typer.Option(
"--clear-cache",
help=(
"Remove all or selected category of cached items and treat all queries as new. "
f"""Allowed cache types are {", ".join([x.value for x in CacheType])} and all """
),
),
] = None,
verbose: Annotated[
Optional[bool],
typer.Option("--verbose", "-v", help="If set to true, will show debug messages."),
] = False,
items: Annotated[
List[str] | None,
typer.Option(
"--check",
help="""Check one or more cached items by their id or URL,
and list why the item was accepted or denied.""",
),
] = None,
for_item: Annotated[
Optional[str],
typer.Option(
"--for",
help="Item to check for URLs specified --check. You will be prmopted for each URL if unspecified and there are multiple items to search.",
),
] = None,
version: Annotated[
Optional[bool], typer.Option("--version", callback=version_callback, is_eager=True)
] = None,
) -> None:
"""Console script for AI Marketplace Monitor."""
logging.basicConfig(
level="DEBUG",
# format="%(name)s %(message)s",
format="%(message)s",
handlers=[
RichHandler(
markup=True,
rich_tracebacks=True,
show_path=False if verbose is None else verbose,
level="DEBUG" if verbose else "INFO",
),
RotatingFileHandler(
amm_home / "ai-marketplace-monitor.log",
encoding="utf-8",
maxBytes=1024 * 1024,
backupCount=5,
),
],
)
# remove logging from other packages.
for logger_name in (
"asyncio",
"openai._base_client",
"httpcore.connection",
"httpcore.http11",
"httpx",
):
logging.getLogger(logger_name).setLevel(logging.ERROR)
logger = logging.getLogger("monitor")
logger.info(
f"""{hilight("[VERSION]", "info")} AI Marketplace Monitor, version {hilight(__version__, "name")}"""
)
if clear_cache is not None:
if clear_cache == "all":
cache.clear()
elif clear_cache in [x.value for x in CacheType]:
cache.evict(tag=clear_cache)
else:
logger.error(
f"""{hilight("[Clear Cache]", "fail")} {clear_cache} is not a valid cache type. Allowed cache types are {", ".join([x.value for x in CacheType])} and all """
)
sys.exit(1)
logger.info(f"""{hilight("[Clear Cache]", "succ")} Cache cleared.""")
sys.exit(0)
# make --version a bit faster by lazy loading of MarketplaceMonitor
from .monitor import MarketplaceMonitor
if items is not None:
try:
monitor = MarketplaceMonitor(config_files, headless, logger)
monitor.check_items(items, for_item)
except Exception as e:
logger.error(f"""{hilight("[Check]", "fail")} {e}""")
raise
finally:
monitor.stop_monitor()
sys.exit(0)
try:
monitor = MarketplaceMonitor(config_files, headless, logger)
monitor.start_monitor()
except KeyboardInterrupt:
rich.print("Exiting...")
sys.exit(0)
except Exception as e:
logger.error(f"""{hilight("[Monitor]", "fail")} {e}""")
raise
sys.exit(1)
finally:
monitor.stop_monitor()
rich.print(counter)
if __name__ == "__main__":
app() # pragma: no cover

View File

@@ -0,0 +1,301 @@
import sys
from dataclasses import dataclass, field
from enum import Enum
from itertools import chain
from logging import Logger
from pathlib import Path
from typing import Any, Dict, Generic, List
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
from .ai import DeepSeekBackend, OllamaBackend, OpenAIBackend, TAIConfig
from .facebook import FacebookMarketplace
from .marketplace import TItemConfig, TMarketplaceConfig
from .notification import NotificationConfig
from .region import RegionConfig
from .user import User, UserConfig
from .utils import MonitorConfig, Translator, hilight, merge_dicts
supported_marketplaces = {"facebook": FacebookMarketplace}
supported_ai_backends = {
"deepseek": DeepSeekBackend,
"openai": OpenAIBackend,
"ollama": OllamaBackend,
}
class ConfigItem(Enum):
MONITOR = "monitor"
MARKETPLACE = "marketplace"
USER = "user"
ITEM = "item"
AI = "ai"
REGION = "region"
NOTIFICATION = "notification"
TRANSLATION = "translation"
@dataclass
class Config(Generic[TAIConfig, TItemConfig, TMarketplaceConfig]):
monitor: MonitorConfig = field(init=False)
ai: Dict[str, TAIConfig] = field(init=False)
user: Dict[str, UserConfig] = field(init=False)
notification: Dict[str, NotificationConfig] = field(init=False)
marketplace: Dict[str, TMarketplaceConfig] = field(init=False)
item: Dict[str, TItemConfig] = field(init=False)
translator: Dict[str, Translator] = field(init=False)
region: Dict[str, RegionConfig] = field(init=False)
def __init__(self: "Config", config_files: List[Path], logger: Logger | None = None) -> None:
configs = []
system_config = Path(__file__).parent / "config.toml"
for config_file in [system_config, *config_files]:
try:
if logger:
logger.debug(
f"""{hilight("[Monitor]", "succ")} config file {hilight(str(config_file))}"""
)
with open(config_file, "rb") as f:
configs.append(tomllib.load(f))
except tomllib.TOMLDecodeError as e:
raise ValueError(f"Error parsing config file {config_file}: {e}") from e
#
# merge the list of configs into a single dictionary, including dictionaries in the values
config = merge_dicts(configs)
self.validate_sections(config)
self.get_translator_config(config)
self.get_monitor_config(config)
self.get_ai_config(config)
self.get_notification_config(config)
self.get_marketplace_config(config)
self.get_user_config(config)
self.get_region_config(config)
self.get_item_config(config)
self.validate_users()
self.validate_ais()
self.expand_notifications(logger)
self.expand_regions()
self.validate_items()
def get_translator_config(self: "Config", config: Dict[str, Any]) -> None:
if not isinstance(config.get("translation", {}), dict):
raise ValueError("translation section must be a dictionary.")
self.translator = {}
for key, value in config.get("translation", {}).items():
if "locale" not in value:
raise ValueError(f"Translation section {hilight(key)} must contain a locale.")
self.translator[key] = Translator(
locale=value["locale"],
dictionary={k: v for k, v in value.items() if k != "locale"},
)
def get_monitor_config(self: "Config", config: Dict[str, Any]) -> None:
self.monitor = MonitorConfig(name="monitor", **config.get("monitor", {}))
def get_ai_config(self: "Config", config: Dict[str, Any]) -> None:
# convert ai config to AIConfig objects
if not isinstance(config.get("ai", {}), dict):
raise ValueError("ai section must be a dictionary.")
self.ai = {}
for key, value in config.get("ai", {}).items():
try:
backend_class = supported_ai_backends[value.get("provider", key).lower()]
except KeyboardInterrupt:
raise
except Exception as e:
raise ValueError(
f"Config file contains an unsupported AI backend {key} in the ai section."
) from e
self.ai[key] = backend_class.get_config(name=key, **value)
def get_notification_config(self: "Config", config: Dict[str, Any]) -> None:
if not isinstance(config.get("notification", {}), dict):
raise ValueError("notification section must be a dictionary.")
self.notification: Dict[str, NotificationConfig] = {}
for key, value in config.get("notification", {}).items():
cfg = NotificationConfig.get_config(name=key, **value)
if cfg is None:
raise ValueError(
f"Unable to determine notification type for notification section {key}"
)
else:
self.notification[key] = cfg
def get_marketplace_config(self: "Config", config: Dict[str, Any]) -> None:
# check for required fields in each marketplace
self.marketplace = {}
for marketplace_name, marketplace_config in config["marketplace"].items():
market_type = marketplace_config.get("market_type", "facebook")
if market_type not in supported_marketplaces:
raise ValueError(
f"Marketplace {hilight(market_type)} is not supported. Supported marketplaces are: {supported_marketplaces.keys()}"
)
marketplace_class = supported_marketplaces[market_type]
self.marketplace[marketplace_name] = marketplace_class.get_config(
name=marketplace_name, **marketplace_config
)
lan = self.marketplace[marketplace_name].language
if lan is None:
continue
# no exact match is required
if lan.split("_")[0] not in {
x.split("_")[0] for x in config[ConfigItem.TRANSLATION.value].keys()
}:
raise ValueError(f"Translation for language {lan} is not supported.")
def get_user_config(self: "Config", config: Dict[str, Any]) -> None:
# check for required fields in each user
self.user: Dict[str, UserConfig] = {}
for user_name, user_config in config["user"].items():
self.user[user_name] = User.get_config(name=user_name, **user_config)
def get_region_config(self: "Config", config: Dict[str, Any]) -> None:
# check for required fields in each user
self.region: Dict[str, RegionConfig] = {}
for region_name, region_config in config.get("region", {}).items():
self.region[region_name] = RegionConfig(name=region_name, **region_config)
def get_item_config(self: "Config", config: Dict[str, Any]) -> None:
# check for required fields in each user
self.item = {}
for item_name, item_config in config["item"].items():
# if marketplace is specified, it must exist
if "marketplace" in item_config:
if item_config["marketplace"] not in config["marketplace"]:
raise ValueError(
f"Item {hilight(item_name)} specifies a marketplace that does not exist."
)
for marketplace_name, markerplace_config in config["marketplace"].items():
marketplace_class = supported_marketplaces[
markerplace_config.get("market_type", "facebook")
]
if (
"marketplace" not in item_config
or item_config["marketplace"] == marketplace_name
):
# use the first available marketplace
self.item[item_name] = marketplace_class.get_item_config(
name=item_name,
marketplace=marketplace_name,
**{x: y for x, y in item_config.items() if x != "marketplace"},
)
break
def validate_sections(self: "Config", config: Dict[str, Any]) -> None:
# check for required sections
for required_section in ["marketplace", "user", "item"]:
if required_section not in config:
raise ValueError(f"Config file does not contain a {required_section} section.")
# check allowed keys in config
for key in config:
if key not in [x.value for x in ConfigItem]:
raise ValueError(f"Config file contains an invalid section {key}.")
def validate_users(self: "Config") -> None:
"""Check if notified users exists"""
# if user is specified in other section, they must exist
for config in chain(self.marketplace.values(), self.item.values()):
for user in config.notify or []:
if user not in self.user:
raise ValueError(
f"User {hilight(user)} specified in {hilight(config.name)} does not exist."
)
def validate_ais(self: "Config") -> None:
# if ai is specified in other section, they must exist
for config in chain(self.marketplace.values(), self.item.values()):
for ai in config.ai or []:
if ai not in self.ai:
raise ValueError(
f"AI {hilight(config.ai)} specified in {hilight(config.name)} does not exist."
)
def expand_notifications(self: "Config", logger: Logger | None = None) -> None:
for config in self.user.values():
for notification_name in (
config.notify_with if config.notify_with is not None else self.notification.keys()
):
notification_types = set()
if notification_name not in self.notification:
raise ValueError(
f"User {hilight(config.name)} specifies an undefined notification method {notification_name}."
)
notification_config = self.notification[notification_name]
#
if notification_config.enabled is False:
continue
# add values of notification_config to user config
if notification_config.__class__.__name__ in notification_types:
if logger:
logger.warning(
f"Ignore additional notification {hilight(notification_name)} with type {notification_config.__class__.__name__} for user {config.name}."
)
continue
else:
notification_types.add(notification_config.__class__.__name__)
for key, value in notification_config.__dict__.items():
# name is the notification name and should not override username
if key not in ("type", "name") and value is not None:
if getattr(config, key) is not None:
if logger:
logger.warning(
f"Overriding {hilight(key)} for user {config.name} with value {value} from notification {hilight(notification_name)}."
)
setattr(config, key, value)
def expand_regions(self: "Config") -> None:
# if region is specified in other section, they must exist
for config in chain(self.marketplace.values(), self.item.values()):
if config.search_region is None:
continue
config.city_name = []
config.search_city = []
config.radius = []
for region in config.search_region:
region_config: RegionConfig = self.region[region]
if region not in self.region:
raise ValueError(
f"Region {hilight(region)} specified in {hilight(config.name)} does not exist."
)
if region_config.enabled is False:
continue
# avoid duplicated addition of search_city
for search_city, city_name, radius in zip(
region_config.search_city or [],
region_config.city_name or [],
region_config.radius or [],
):
if search_city not in config.search_city:
config.search_city.append(search_city)
config.city_name.append(city_name)
config.radius.append(radius)
def validate_items(self: "Config") -> None:
# if item is specified in other section, they must exist
for marketplace_config in self.marketplace.values():
if marketplace_config.enabled is False:
continue
for item_config in self.item.values():
if item_config.enabled is False:
continue
if (
item_config.marketplace is None
or item_config.marketplace == marketplace_config.name
):
if not item_config.search_city and not marketplace_config.search_city:
raise ValueError(
f"No search_city or search_region is specified for {item_config.name} or market {marketplace_config.name}"
)

View File

@@ -0,0 +1,321 @@
#
# Region definitions.
# - full_name and city_name are for readability/booktracking purpose only
# - different radius can be used for different search_city. In this case
# radius should an array with the same length as search_city
#
# Usage
# - ·search_city` will be ignored if `search_region` is specified.
# - under the hood search_city is replaced by `search_city` of the regions
#
[region.usa]
full_name = "USA (without AK or HI)"
radius = 500
city_name = [
"Portland, OR",
"Los Angeles, CA",
"Durango, CO",
"Broadus, MT",
"Fort Worth, TX",
"Boscobel, WI",
"Fitzgerald, GA",
"Oneonta, NY",
]
search_city = [
"portland",
"la",
"108129565875623",
"109613652398861",
"114148045261892",
"106171882747436",
"112442175434378",
"113333232014461",
]
[region.usa_full]
full_name = "USA"
radius = 500
city_name = [
"Portland, OR",
"Los Angeles, CA",
"Durango, CO",
"Broadus, MT",
"Fort Worth, TX",
"Boscobel, WI",
"Fitzgerald, GA",
"Oneonta, NY",
"McGrath, AK",
"Prudhoe Bay, AK",
"Unalaska, AK",
"Elfin Cove, AK",
"Honolulu, HI",
]
search_city = [
"portland",
"la",
"108129565875623",
"109613652398861",
"114148045261892",
"106171882747436",
"112442175434378",
"113333232014461",
"108203532540672",
"171705676191734",
"103760199662259",
"196626670491979",
"110444738976181",
]
[region.can]
full_name = "Canada"
radius = 805
city_name = [
"Saint Quentin, NB",
"Baysville, ON",
"Compeer, AB",
"One Hundred Mile House, BC",
"Moosehorn, MB",
"Skibi Lake, ON",
"Yellowknife, NT",
"White Horse, YK",
"Channel-Port aux Basques, NL",
]
search_city = [
"108562712499750",
"183509305085293",
"112682018747951",
"111922062167097",
"112583085425676",
"362073744288039",
"114459998571182",
"115392538472860",
"115477851802820",
]
[region.mex]
full_name = "Mexico"
radius = 805
city_name = [
"Irapuato,Guanajuato ",
"Chapala, Jalisco",
"Creel, Chihuahua",
"Monclova, Coahuila",
"Campeche, Campeche",
"Cabo San Lucas, Baja California",
"Tehuantepec, Oaxaca",
]
search_city = [
"108476082510080",
"106142666084683",
"110176719011514",
"110799538947338",
"619367721515573",
"154130198035072",
"116186601728289",
]
[region.bra]
full_name = "Brazil"
radius = 805
city_name = [
"Betim, Minas Gerais",
"Ibaiti, Paraná",
"Montes Claros de Goiás, Goiás",
"Alto Da Várzea, Ceara",
"Várzea Nova, Bahia",
"Salinas, Minas Gerais",
"Piquiá, Amazonas",
"Bom Jardim, Para",
"Salto do Jacuí, Rio Grande Do Sud",
"Altamira do Maranhão, Maranhão",
"Brasnorte, Mato Grosso",
"Corguinho, Mato Grosso Do Sul",
"Dianópolis, Tocantins",
"Japurá, Amazonas",
"Barraca Da Bôca, Amapa",
"Pôrto Velho, Rondônia",
"Feijó, Acre",
"Vista Alegre, Roraima",
]
search_city = [
"241025963776891",
"107813919248792",
"182609075084572",
"115057491845194",
"400163803477498",
"630835887017960",
"111605828861709",
"112619282090096",
"110549925683118",
"112596635420890",
"173196699369921",
"108281459194195",
"113373648672696",
"107544435935385",
"117344181609620",
"108549759176811",
"103727253000065",
"117248258288799",
]
[region.arg]
full_name = "Argentina"
radius = 805
city_name = [
"Pehuajó, Buenos Aires",
"Ulapes, La Rioja",
"Mburucuyá, Corrientes",
"Rosario de la Frontera, Salta",
"La Reforma, La Pampa",
"Paso de Indios, Chubut",
"Rio Gallegos, Santa Cruz",
]
search_city = [
"112089622140241",
"107413102628881",
"103767409662395",
"108630072495327",
"106494259383808",
"105646196135882",
"300807386607332",
]
[region.aus]
full_name = "Australia"
radius = 805
city_name = [
"Tamworth, NSW",
"Deniliquin, NSW",
"Oakden Hills, SA",
"Warralakin, WA",
"Yeppoon, QLD",
"Hobart, TAS",
"Darwin, NT",
"Carnarvon, WA",
"Port Hedland, WA",
"Port Douglas, QLD",
"Cloncurry, QLD",
"Alice Springs, NT",
"Quilpie, QLD",
]
search_city = [
"112577755420955",
"104020242968596",
"277036799317188",
"106555549377269",
"108131009215930",
"111652435519898",
"109437725742749",
"103825936322408",
"248019175333793",
"106373139394499",
"112359378775421",
"107929299235881",
"109465839072367",
]
[region.aus_miles]
full_name = "Australia"
radius = 500
city_name = [
"Warburton, Western Australia",
"Mount Magnet, Western Australia",
"Coober Pedy, South Australia",
"Melbourne, Victoria, Australia",
"Tooraweenah",
"Clermont, Queensland",
"Daly Waters, Northern Territory",
"Broome, Western Australia",
]
search_city = [
"112262705457494",
"105508376148373",
"107723845924377",
"melbourne",
"107928752568747",
"105632482805073",
"108276829196663",
"112099285474124",
]
[region.nzl]
full_name = "New Zealand"
radius = 805
city_name = ["Hamilton", "Lake Tekapo"]
search_city = ["104080336295923", "106528236047934"]
[region.ind]
full_name = "India"
radius = 805
city_name = [
"Sanquelim, Goa",
"Sangrur, Punjab",
"Kolkata, West Bengal",
"Himatnagar, Gujarat",
"Allahabad, Uttar Pradesh",
"Bhamragarh, Maharashtra",
"Salem, Tamil Nadu",
]
search_city = [
"104029036299831",
"109148435777996",
"108212225873404",
"112269678784935",
"2099665383411187",
"115852108431709",
"1410397895862431",
]
[region.gbr]
full_name = "United Kingdom"
radius = 805
city_name = ["Manchester", "Kirkwall"]
search_city = ["114629675219759", "107972512564724"]
[region.fra]
full_name = "France"
radius = 805
city_name = ["Chartres", "Montpellier"]
search_city = ["115700691777803", "115100621840245"]
[region.spa]
full_name = "Spain"
radius = 805
city_name = ["Plasencia", "Valencia"]
search_city = ["108336475863182", "2404588816444858"]
#
# Translation for different languages
#
[translation.es]
locale = "Spanish"
'Collection of Marketplace items' = 'Colección de artículos de Marketplace'
'Condition' = 'Estado'
'Description' = 'Descripción'
'Details' = 'Detalles'
'Location is approximate' = 'La ubicación es aproximada'
"About this vehicle" = 'Descripción del vendedor'
"Seller's description" = 'Información sobre este vehículo'
[translation.zh]
locale = "Chinese"
'Collection of Marketplace items' = 'Marketplace 商品收藏夹'
'Condition' = '商品状况'
'Description' = '描述'
'Details' = '详细信息'
'Location is approximate' = '我们只提供大概位置'
"About this vehicle" = "车辆信息"
"Seller's description" = "卖家描述"

View File

@@ -0,0 +1,223 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style type="text/css">
/* Base */
body {
margin: 0;
padding: 0;
min-width: 100%;
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
background-color: #FAFAFA;
color: #222222;
}
/* Layout */
.wrapper {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.header {
background-color: #2C5364;
padding: 20px;
text-align: center;
}
.content {
background-color: #FFFFFF;
padding: 20px;
}
.footer {
background-color: #F5F5F5;
padding: 20px;
text-align: center;
font-size: 12px;
color: #666666;
}
/* Tables */
.listing-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.listing-table td {
padding: 12px;
border-bottom: 1px solid #EEEEEE;
}
/* Typography */
h1 {
color: #FFFFFF;
font-size: 24px;
margin: 0;
}
h2 {
color: #2C5364;
font-size: 20px;
margin: 0 0 20px 0;
}
/* Images */
.listing-image {
max-width: 100%;
height: auto;
margin: 10px 0;
}
/* Status Tags */
.status-tag {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
}
.current-price {
font-weight: bold;
margin-right: 8px;
}
.original-price {
color: #666;
font-size: 0.9em;
}
.original-price del {
text-decoration: line-through;
}
.status-new { background-color: #4CAF50; color: white; }
.status-updated { background-color: #2196F3; color: white; }
.status-discounted { background-color: #FF9800; color: white; }
.status-expired { background-color: #F44336; color: white; }
.status-sent { background-color: #9E9E9E; color: white; }
</style>
</head>
<body>
<div class="wrapper">
<!-- Header -->
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="header">
<h1>AI Marketplace Monitor</h1>
</td>
</tr>
</table>
<!-- Content -->
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="content">
<h2>Latest {{ item_name }} Listings</h2>
<table class="listing-table" cellpadding="0" cellspacing="0" border="0">
{% for listing, rating, ns in listings %}
<tr>
<td style="padding: 20px;">
<!-- Title with status tag -->
<div style="margin-bottom: 15px;">
<h3 style="color: #2C5364; font-size: 18px; font-weight: bold; margin: 0; display: inline;">
{{ listing.title }}
</h3>
{% if ns == NotificationStatus.NOT_NOTIFIED %}
<span class="status-tag status-new">NEW</span>
{% elif ns == NotificationStatus.LISTING_CHANGED %}
<span class="status-tag status-updated">UPDATED</span>
{% elif ns == NotificationStatus.LISTING_DISCOUNTED %}
<span class="status-tag status-discounted">DISCOUNTED</span>
{% elif ns == NotificationStatus.EXPIRED %}
<span class="status-tag status-expired">REVISITABLE</span>
{% elif ns == NotificationStatus.NOTIFIED and force %}
<span class="status-tag status-sent">REVISITABLE</span>
{% endif %}
</div>
<!-- Info rows -->
<div style="color: #666666; margin-bottom: 10px;">
<span style="font-weight: bold; color: #333333;">Price:</span>
{% if '|' in listing.price %}
{% set prices = listing.price.split('|') %}
<span class="current-price">{{ prices[0].strip() }}</span>
<span class="original-price"><del>{{ prices[1].strip() }}</del></span>
{% else %}
{{ listing.price }}
{% endif %}
</div>
<div style="color: #666666; margin-bottom: 15px;">
<span style="font-weight: bold; color: #333333;">Location:</span> {{ listing.location }}
</div>
<!-- Description -->
{% if listing.description %}
<div style="color: #444444; margin: 12px 0; line-height: 1.6; font-size: 14px; white-space: pre-line;">
{{ listing.description }}
</div>
{% endif %}
<!-- AI Rating -->
{% if rating.comment != rating.NOT_EVALUATED %}
<div style="background-color: #F8F9FA; padding: 12px; border-radius: 4px; margin: 15px 0;">
<div style="margin-bottom: 5px;">
<span style="font-weight: bold; color: #333333;">AI Rating:</span>
{{ rating.stars }}
</div>
<div style="color: #666666;">
<em>{{ rating.comment }}</em>
</div>
</div>
{% else %}
<div style="background-color: #F8F9FA; padding: 12px; border-radius: 4px; margin: 15px 0;">
<div style="color: #666666;">
<em>This listing has not been evaluated by AI service for relevance.</em>
</div>
</div>
{% endif %}
<!-- Image -->
{% if listing.image and (listing.image|hash in valid_image_hashes) %}
<img src="cid:image_{{ listing.image|hash }}"
alt="{{ listing.title }}"
class="listing-image">
{% endif %}
<!-- View Listing Button -->
<p style="margin: 10px 0;">
<a href="{{ listing.post_url.split('?')[0] }}"
style="background-color: #2C5364; color: white; padding: 10px 20px;
text-decoration: none; border-radius: 4px; display: inline-block;">
View Listing
</a>
</p>
</td>
</tr>
{% endfor %}
</table>
</td>
</tr>
</table>
<!-- Footer -->
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="footer">
<p>This is an automated message from <a href="https://github.com/BoPeng/ai-marketplace-monitor">AI Marketplace Monitor</a></p>
<p>
Brought to you by <a href="https://www.linkedin.com/in/bo-peng-53668026/">Bo Peng</a> from <a href="https://bioworkflows.com/">BioWorkflows.com</a><br>
To stop this email, contact the sender
</p>
</td>
</tr>
</table>
</div>
</body>
</html>

View File

@@ -0,0 +1,337 @@
import smtplib
import ssl
import time
from dataclasses import dataclass
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from logging import Logger
from pathlib import Path
from typing import ClassVar, List, Tuple
import inflect
from jinja2 import Environment, FileSystemLoader, select_autoescape
from .ai import AIResponse # type: ignore
from .listing import Listing
from .notification import NotificationConfig, NotificationStatus
from .utils import fetch_with_retry, hilight, resize_image_data
@dataclass
class EmailNotificationConfig(NotificationConfig):
required_fields: ClassVar[List[str]] = ["email", "smtp_password"]
email: List[str] | None = None
smtp_server: str | None = None
smtp_port: int | None = None
smtp_username: str | None = None
smtp_password: str | None = None
smtp_from: str | None = None
def handle_email(self: "EmailNotificationConfig") -> None:
if self.email is None:
return
if isinstance(self.email, str):
self.email = [self.email]
if not isinstance(self.email, list) or not all(
(isinstance(x, str) and "@" in x and "." in x.split("@")[1]) for x in self.email
):
raise ValueError(
f"Item {hilight(self.name)} email must be a string or list of string."
)
def handle_smtp_server(self: "EmailNotificationConfig") -> None:
if self.smtp_server is None:
return
if not isinstance(self.smtp_server, str):
raise ValueError("user requires a string smtp_server.")
self.smtp_server = self.smtp_server.strip()
def handle_smtp_port(self: "EmailNotificationConfig") -> None:
if self.smtp_port is None:
return
if not isinstance(self.smtp_port, int):
raise ValueError("user requires an integer smtp_port.")
if self.smtp_port < 1 or self.smtp_port > 65535:
raise ValueError("user requires an integer smtp_port between 1 and 65535.")
def handle_smtp_username(self: "EmailNotificationConfig") -> None:
if self.smtp_username is None:
return
# smtp_username should be a string
if not isinstance(self.smtp_username, str) or not self.smtp_username:
raise ValueError("A non-empty value is requires for option smtp_username.")
self.smtp_username = self.smtp_username.strip()
def handle_smtp_password(self: "EmailNotificationConfig") -> None:
if self.smtp_password is None:
return
# smtp_password should be a string
if not isinstance(self.smtp_password, str) or not self.smtp_password:
raise ValueError("A non-empty value is is required for option smtp_password.")
self.smtp_password = self.smtp_password.strip()
def handle_smtp_from(self: "EmailNotificationConfig") -> None:
if self.smtp_from is None:
return
# smtp_from should be a string
if not isinstance(self.smtp_from, str):
raise ValueError("user requires a string smtp_from.")
self.smtp_from = self.smtp_from.strip()
def get_title(
self: "EmailNotificationConfig",
listings: List[Listing],
notification_status: List[NotificationStatus],
force: bool = False,
) -> str:
p = inflect.engine()
n_new = len([x for x in notification_status if x == NotificationStatus.NOT_NOTIFIED])
n_notified = len([x for x in notification_status if x == NotificationStatus.NOTIFIED])
n_expired = len([x for x in notification_status if x == NotificationStatus.EXPIRED])
n_updated = len(
[x for x in notification_status if x == NotificationStatus.LISTING_CHANGED]
)
n_discounted = len(
[x for x in notification_status if x == NotificationStatus.LISTING_DISCOUNTED]
)
title = "Found "
cnts = []
if n_new > 0:
cnts.append(f"{n_new} new ")
if n_updated > 0:
cnts.append(f"{n_updated} updated ")
if n_discounted > 0:
cnts.append(f"{n_discounted} discounted ")
if n_expired > 0 or (force and n_notified > 0):
cnts.append(f"{n_expired + (n_notified if force else 0)} revisitable ")
if len(cnts) > 1:
cnts[-1] = f"and {cnts[-1]}"
elif len(cnts) == 0:
# no new items
return ""
title += " ".join(cnts)
title += f"{listings[0].name} {p.plural_noun('listing', len(listings)-(0 if force else n_notified))} from {listings[0].marketplace}"
return title
def get_text_message(
self: "EmailNotificationConfig",
listings: List[Listing],
ratings: List[AIResponse],
notification_status: List[NotificationStatus],
force: bool = False,
logger: Logger | None = None,
) -> str:
messages = []
for listing, rating, ns in zip(listings, ratings, notification_status):
prefix = ""
if ns == NotificationStatus.NOTIFIED:
if force:
prefix = "[NOTIFIED] "
else:
continue
if ns == NotificationStatus.EXPIRED:
prefix = "[REMINDER] "
elif ns == NotificationStatus.LISTING_CHANGED:
prefix = "[lISTING UPDATED] "
elif ns == NotificationStatus.LISTING_DISCOUNTED:
prefix = "[lISTING DISCOUNTED] "
messages.append(
(
f"{prefix}{listing.title}\n{listing.price}, {listing.location}\n"
f"{listing.post_url.split('?')[0]}"
)
if rating.comment == AIResponse.NOT_EVALUATED
else (
f"{prefix} [{rating.conclusion} ({rating.score})] {listing.title}\n"
f"{listing.price}, {listing.location}\n"
f"{listing.post_url.split('?')[0]}\n"
f"AI: {rating.comment}"
)
)
message = "\n\n".join(messages)
return message
def get_html_message(
self: "EmailNotificationConfig",
listings: List[Listing],
ratings: List[AIResponse],
notification_status: List[NotificationStatus],
force: bool = False,
logger: Logger | None = None,
) -> Tuple[str, list[Tuple[bytes, str, str]]]: # Return HTML and image data
template_dir = Path(__file__).parent
# Set up Jinja2 environment
env = Environment(
loader=FileSystemLoader(template_dir), autoescape=select_autoescape(["html", "xml"])
)
# Add custom filter for hashing
env.filters["hash"] = hash
# Load template
template = env.get_template("email.html.j2")
# Prepare images list for attachments
images = []
valid_image_hashes = set() # Track which images were successfully processed
# Process images first
for listing in listings:
if listing.image:
result = fetch_with_retry(listing.image, logger=logger)
if result:
image_data, content_type = result
image_data = resize_image_data(image_data)
if image_data and len(image_data) <= 1024 * 1024:
image_hash = hash(listing.image)
images.append((image_data, content_type, f"image_{image_hash}"))
valid_image_hashes.add(image_hash) # Track valid image
else:
if logger:
logger.debug(f"Image too large: {len(image_data)} bytes, skipped.")
else:
if logger:
logger.debug(f"Failed to fetch image: {listing.image}")
# Render template
html = template.render(
listings=zip(listings, ratings, notification_status),
force=force,
item_name=listings[0].name.capitalize(),
NotificationStatus=NotificationStatus, # Pass enum for comparison
valid_image_hashes=valid_image_hashes, # Pass set of valid image hashes
)
return html, images
def notify(
self: "EmailNotificationConfig",
listings: List[Listing],
ratings: List[AIResponse],
notification_status: List[NotificationStatus],
force: bool = False,
logger: Logger | None = None,
) -> bool:
if not self._has_required_fields():
return False
title = self.get_title(listings, notification_status, force=force)
if not title:
if logger:
logger.debug("No new listings. No email sent.")
return False
message = self.get_text_message(
listings, ratings, notification_status, force, logger=logger
)
html_message, images = self.get_html_message(
listings, ratings, notification_status, force, logger=logger
)
return self.send_email_message(title, message, html_message, images, logger=logger)
def send_email_message(
self: "EmailNotificationConfig",
title: str,
message: str,
html: str,
images: List[Tuple[bytes, str, str]],
logger: Logger | None = None,
) -> bool:
if not self.email:
if logger:
logger.debug("No recipients specified. No email sent.")
return False
sender = self.smtp_from or self.smtp_username or self.email[0]
if self.smtp_server:
smtp_server = self.smtp_server
else:
smtp_server = f"""smtp.{sender.split("@")[1]}"""
# s.starttls()
msg = MIMEMultipart("related")
msg["Subject"] = title
# can use the humanized version of self.name as well
msg["From"] = formataddr(("AI Marketplace Monitor", sender))
msg["To"] = ", ".join(self.email)
# Create alternative part
alt_part = MIMEMultipart("alternative")
msg.attach(alt_part)
alt_part.attach(MIMEText(message, "plain"))
alt_part.attach(MIMEText(html, "html")) # HTML part last = preferred
# Attach images
for image_data, _, cid in images:
image = MIMEImage(image_data)
image.add_header("Content-ID", f"<{cid}>")
image.add_header("Content-Disposition", "inline")
msg.attach(image)
for attempt in range(self.max_retries):
try:
smtp_port = self.smtp_port or 587
smtp_username = self.smtp_username or sender
if not smtp_username:
if logger:
logger.error("No smtp username.")
return False
smtp_password = self.smtp_password
if not smtp_password:
if logger:
logger.error("No smtp password.")
return False
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
# smtp.set_debuglevel(1)
smtp.ehlo() # Can be omitted
smtp.starttls(context=context)
smtp.ehlo() # Can be omitted
try:
smtp.login(smtp_username, smtp_password)
except KeyboardInterrupt:
raise
except Exception as e:
if logger:
logger.error(
f"Failed to login to smtp server {smtp_server}:{smtp_port} with username {smtp_username}: {e}"
)
return False
smtp.send_message(msg)
if logger:
logger.info(
f"""{hilight("[Notify]", "succ")} Sent {self.name} an email with title {hilight(title)}"""
)
return True
except KeyboardInterrupt:
raise
except Exception as e:
if logger:
logger.debug(
f"""{hilight("[Notify]", "fail")} Attempt {attempt + 1} failed: {e}"""
)
if attempt < self.max_retries - 1:
if logger:
logger.debug(
f"""{hilight("[Notify]", "fail")} Retrying in {self.retry_delay} seconds..."""
)
time.sleep(self.retry_delay)
else:
if logger:
logger.error(
f"""{hilight("[Notify]", "fail")} Max retries reached. Failed to push note to {self.name}."""
)
return False
return False

View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
from dataclasses import asdict, dataclass
from typing import Optional, Tuple, Type
from diskcache import Cache # type: ignore
from .utils import CacheType, cache, hash_dict
@dataclass
class Listing:
marketplace: str
name: str
# unique identification
id: str
title: str
image: str
price: str
post_url: str
location: str
seller: str
condition: str
description: str
@property
def content(self: "Listing") -> Tuple[str, str, str]:
return (self.title, self.description, self.price)
@property
def hash(self: "Listing") -> str:
# we need to normalize post_url before hashing because post_url will be different
# each time from a search page. We also does not count image
return hash_dict(
{
x: (y.split("?")[0] if x == "post_url" else y)
for x, y in asdict(self).items()
if x != "image"
}
)
@classmethod
def from_cache(
cls: Type["Listing"],
post_url: str,
local_cache: Cache | None = None,
) -> Optional["Listing"]:
try:
# details could be a different datatype, miss some key etc.
# and we have recently changed to save Listing as a dictionary
return cls(
**(cache if local_cache is None else local_cache).get(
(CacheType.LISTING_DETAILS.value, post_url.split("?")[0])
)
)
except KeyboardInterrupt:
raise
except Exception:
return None
def to_cache(
self: "Listing",
post_url: str,
local_cache: Cache | None = None,
) -> None:
(cache if local_cache is None else local_cache).set(
(CacheType.LISTING_DETAILS.value, post_url.split("?")[0]),
asdict(self),
tag=CacheType.LISTING_DETAILS.value,
)

View File

@@ -0,0 +1,483 @@
import time
from dataclasses import dataclass, field
from enum import Enum
from logging import Logger
from typing import Any, Callable, Generator, Generic, List, Type, TypeVar
from playwright.sync_api import Browser, ElementHandle, Locator, Page # type: ignore
from .listing import Listing
from .utils import BaseConfig, KeyboardMonitor, Translator, convert_to_seconds, hilight
class MarketPlace(Enum):
FACEBOOK = "facebook"
@dataclass
class MarketItemCommonConfig(BaseConfig):
"""Item options that can be specified in market (non-marketplace specifc)
This class defines and processes options that can be specified
in both marketplace and item sections, generic to all marketplaces
"""
ai: List[str] | None = None
exclude_sellers: List[str] | None = None
notify: List[str] | None = None
search_city: List[str] | None = None
city_name: List[str] | None = None
# radius must be processed after search_city
radius: List[int] | None = None
search_interval: int | None = None
max_search_interval: int | None = None
start_at: List[str] | None = None
search_region: List[str] | None = None
max_price: int | None = None
min_price: int | None = None
rating: List[int] | None = None
prompt: str | None = None
extra_prompt: str | None = None
rating_prompt: str | None = None
def handle_ai(self: "MarketItemCommonConfig") -> None:
if self.ai is None:
return
if isinstance(self.ai, str):
self.ai = [self.ai]
if not all(isinstance(x, str) for x in self.ai):
raise ValueError(f"Item {hilight(self.name)} ai must be a string or list.")
def handle_exclude_sellers(self: "MarketItemCommonConfig") -> None:
if self.exclude_sellers is None:
return
if isinstance(self.exclude_sellers, str):
self.exclude_sellers = [self.exclude_sellers]
if not isinstance(self.exclude_sellers, list) or not all(
isinstance(x, str) for x in self.exclude_sellers
):
raise ValueError(f"Item {hilight(self.name)} exclude_sellers must be a list.")
def handle_max_search_interval(self: "MarketItemCommonConfig") -> None:
if self.max_search_interval is None:
return
if isinstance(self.max_search_interval, str):
try:
self.max_search_interval = convert_to_seconds(self.max_search_interval)
except Exception as e:
raise ValueError(
f"Marketplace {self.name} max_search_interval {self.max_search_interval} is not recognized."
) from e
if not isinstance(self.max_search_interval, int) or self.max_search_interval < 1:
raise ValueError(
f"Item {hilight(self.name)} max_search_interval must be at least 1 second."
)
def handle_notify(self: "MarketItemCommonConfig") -> None:
if self.notify is None:
return
if isinstance(self.notify, str):
self.notify = [self.notify]
if not all(isinstance(x, str) for x in self.notify):
raise ValueError(
f"Item {hilight(self.name)} notify must be a string or list of string."
)
def handle_radius(self: "MarketItemCommonConfig") -> None:
if self.radius is None:
return
if self.search_city is None:
raise ValueError(
f"Item {hilight(self.name)} radius must be None if search_city is None."
)
if isinstance(self.radius, int):
self.radius = [self.radius]
if not all(isinstance(x, int) for x in self.radius):
raise ValueError(
f"Item {hilight(self.name)} radius must be one or a list of integers."
)
if len(self.radius) != len(self.search_city):
raise ValueError(
f"Item {hilight(self.name)} radius must be the same length as search_city."
)
def handle_search_city(self: "MarketItemCommonConfig") -> None:
if self.search_city is None:
return
if isinstance(self.search_city, str):
self.search_city = [self.search_city]
if not isinstance(self.search_city, list) or not all(
isinstance(x, str) for x in self.search_city
):
raise ValueError(
f"Item {hilight(self.name)} search_city must be a string or list of string."
)
def handle_city_name(self: "MarketItemCommonConfig") -> None:
if self.city_name is None:
if self.search_city is None:
return
self.city_name = [x.capitalize() for x in self.search_city]
return
if self.search_city is None:
raise ValueError(
f"Item {hilight(self.name)} city_name must be None if search_city is None."
)
if isinstance(self.city_name, str):
self.city_name = [self.city_name]
# check if city_name is a list of strings
if not isinstance(self.city_name, list) or not all(
isinstance(x, str) for x in self.city_name
):
raise ValueError(f"Region {self.name} city_name must be a list of strings.")
if len(self.city_name) != len(self.search_city):
raise ValueError(
f"Region {self.name} city_name ({self.city_name}) must be the same length as search_city ({self.search_city})."
)
def handle_search_interval(self: "MarketItemCommonConfig") -> None:
if self.search_interval is None:
return
if isinstance(self.search_interval, str):
try:
self.search_interval = convert_to_seconds(self.search_interval)
except Exception as e:
raise ValueError(
f"Marketplace {self.name} search_interval {self.search_interval} is not recognized."
) from e
if not isinstance(self.search_interval, int) or self.search_interval < 1:
raise ValueError(
f"Item {hilight(self.name)} search_interval must be at least 1 second."
)
def handle_search_region(self: "MarketItemCommonConfig") -> None:
if self.search_region is None:
return
if isinstance(self.search_region, str):
self.search_region = [self.search_region]
if not isinstance(self.search_region, list) or not all(
isinstance(x, str) for x in self.search_region
):
raise ValueError(
f"Item {hilight(self.name)} search_region must be one or a list of string."
)
def handle_max_price(self: "MarketItemCommonConfig") -> None:
if self.max_price is None:
return
if not isinstance(self.max_price, int):
raise ValueError(f"Item {hilight(self.name)} max_price must be an integer.")
def handle_min_price(self: "MarketItemCommonConfig") -> None:
if self.min_price is None:
return
if not isinstance(self.min_price, int):
raise ValueError(f"Item {hilight(self.name)} min_price must be an integer.")
def handle_start_at(self: "MarketItemCommonConfig") -> None:
if self.start_at is None:
return
if isinstance(self.start_at, str):
self.start_at = [self.start_at]
if not isinstance(self.start_at, list) or not all(
isinstance(x, str) for x in self.start_at
):
raise ValueError(
f"Item {hilight(self.name)} start_at must be a string or list of string."
)
# start_at should be in one of the format of
# HH:MM:SS, HH:MM, *:MM:SS, or *:MM, or *:*:SS
# where HH, MM, SS are hour, minutes and seconds
# and * can be any number
# if not, raise ValueError
for val in self.start_at:
if (
val.count(":") not in (1, 2)
or val.count("*") == 3
or not all(x == "*" or (x.isdigit() and len(x) == 2) for x in val.split(":"))
):
raise ValueError(f"Item {hilight(self.name)} start_at {val} is not recognized.")
#
acceptable = False
for pattern in ["%H:%M:%S", "%H:%M", "*:%M:%S", "*:%M", "*:*:%S"]:
try:
time.strptime(val, pattern)
acceptable = True
break
except ValueError:
pass
if not acceptable:
raise ValueError(f"Item {hilight(self.name)} start_at {val} is not recognized.")
def handle_rating(self: "MarketItemCommonConfig") -> None:
if self.rating is None:
return
if isinstance(self.rating, int):
self.rating = [self.rating]
if not all(isinstance(x, int) and x >= 1 and x <= 5 for x in self.rating):
raise ValueError(
f"Item {hilight(self.name)} rating must be one or a list of integers between 1 and 5 inclusive."
)
def handle_prompt(self: "MarketItemCommonConfig") -> None:
if self.prompt is None:
return
if not isinstance(self.prompt, str):
raise ValueError(f"Item {hilight(self.name)} requires a string prompt, if specified.")
def handle_extra_prompt(self: "MarketItemCommonConfig") -> None:
if self.extra_prompt is None:
return
if not isinstance(self.extra_prompt, str):
raise ValueError(
f"Item {hilight(self.name)} requires a string extra_prompt, if specified."
)
def handle_rating_prompt(self: "MarketItemCommonConfig") -> None:
if self.rating_prompt is None:
return
if not isinstance(self.rating_prompt, str):
raise ValueError(
f"Item {hilight(self.name)} requires a string rating_prompt, if specified."
)
@dataclass
class MarketplaceConfig(MarketItemCommonConfig):
"""Generic marketplace config"""
# name of market, right now facebook is the only supported one
market_type: str | None = MarketPlace.FACEBOOK.value
language: str | None = None
def handle_market_type(self: "MarketplaceConfig") -> None:
if self.market_type is None:
return
if not isinstance(self.market_type, str):
raise ValueError(f"Marketplace {hilight(self.market_type)} market must be a string.")
if self.market_type.lower() != MarketPlace.FACEBOOK.value:
raise ValueError(
f"Marketplace {hilight(self.market_type)} market must be {MarketPlace.FACEBOOK.value}."
)
def handle_language(self: "MarketplaceConfig") -> None:
if self.language is None:
return
if not isinstance(self.language, str):
raise ValueError(
f"Marketplace {hilight(self.market_type)} language, if specified, must be a string."
)
@dataclass
class ItemConfig(MarketItemCommonConfig):
"""This class defined options that can only be specified for items."""
# the number of times that this item has been searched
searched_count: int = 0
# keywords is required, all others are optional
search_phrases: List[str] = field(default_factory=list)
keywords: List[str] | None = None
antikeywords: List[str] | None = None
description: str | None = None
marketplace: str | None = None
def handle_search_phrases(self: "ItemConfig") -> None:
if isinstance(self.search_phrases, str):
self.search_phrases = [self.search_phrases]
if not isinstance(self.search_phrases, list) or not all(
isinstance(x, str) for x in self.search_phrases
):
raise ValueError(f"Item {hilight(self.name)} search_phrases must be a list.")
if len(self.search_phrases) == 0:
raise ValueError(f"Item {hilight(self.name)} search_phrases list is empty.")
def handle_antikeywords(self: "ItemConfig") -> None:
if self.antikeywords is None:
return
if isinstance(self.antikeywords, str):
self.antikeywords = [self.antikeywords]
if not isinstance(self.antikeywords, list) or not all(
isinstance(x, str) for x in self.antikeywords
):
raise ValueError(f"Item {hilight(self.name)} antikeywords must be a list of strings.")
def handle_keywords(self: "ItemConfig") -> None:
if self.keywords is None:
return
if isinstance(self.keywords, str):
self.keywords = [self.keywords]
if not isinstance(self.keywords, list) or not all(
isinstance(x, str) for x in self.keywords
):
raise ValueError(f"Item {hilight(self.name)} keywords must be a list.")
def handle_description(self: "ItemConfig") -> None:
if self.description is None:
return
if not isinstance(self.description, str):
raise ValueError(f"Item {hilight(self.name)} description must be a string.")
TMarketplaceConfig = TypeVar("TMarketplaceConfig", bound=MarketplaceConfig)
TItemConfig = TypeVar("TItemConfig", bound=ItemConfig)
class Marketplace(Generic[TMarketplaceConfig, TItemConfig]):
def __init__(
self: "Marketplace",
name: str,
browser: Browser | None,
keyboard_monitor: KeyboardMonitor | None = None,
logger: Logger | None = None,
) -> None:
self.name = name
self.browser = browser
self.keyboard_monitor = keyboard_monitor
self.translator = Translator()
self.logger = logger
self.page: Page | None = None
@classmethod
def get_config(cls: Type["Marketplace"], **kwargs: Any) -> TMarketplaceConfig:
raise NotImplementedError("get_config method must be implemented by subclasses.")
@classmethod
def get_item_config(cls: Type["Marketplace"], **kwargs: Any) -> TItemConfig:
raise NotImplementedError("get_config method must be implemented by subclasses.")
def configure(
self: "Marketplace", config: TMarketplaceConfig, translator: Translator | None = None
) -> None:
self.config = config
if translator is not None:
self.translator = translator
def set_browser(self: "Marketplace", browser: Browser | None = None) -> None:
if browser is not None:
self.browser = browser
self.page = None
def stop(self: "Marketplace") -> None:
if self.browser is not None:
# stop closing the browser since Ctrl-C will kill playwright,
# leaving browser in a dysfunctional status.
# see
# https://github.com/microsoft/playwright-python/issues/1170
# for details.
# self.browser.close()
self.browser = None
self.page = None
def goto_url(self: "Marketplace", url: str, attempt: int = 0) -> None:
try:
assert self.page is not None
if self.logger:
self.logger.debug(f'{hilight("[Retrieve]", "info")} Navigating to {url}')
self.page.goto(url, timeout=0)
self.page.wait_for_load_state("domcontentloaded")
except KeyboardInterrupt:
raise
except Exception as e:
if attempt == 10:
raise RuntimeError(f"Failed to navigate to {url} after 10 attempts. {e}") from e
time.sleep(5)
self.goto_url(url, attempt + 1)
def search(self: "Marketplace", item: TItemConfig) -> Generator[Listing, None, None]:
raise NotImplementedError("Search method must be implemented by subclasses.")
class WebPage:
def __init__(
self: "WebPage",
page: Page,
translator: Translator | None = None,
logger: Logger | None = None,
) -> None:
self.page = page
self.translator: Translator = Translator() if translator is None else translator
self.logger = logger
def _parent_with_cond(
self: "WebPage",
element: Locator | ElementHandle | None,
cond: Callable,
ret: Callable | int,
) -> str:
"""Finding a parent element
Starting from `element`, finding its parents, until `cond` matches, then return the `ret`th children,
or a callable.
"""
if element is None:
return ""
# get up at the DOM level, testing the children elements with cond,
# apply the res callable to return a string
parent: ElementHandle | None = (
element.element_handle() if isinstance(element, Locator) else element
)
# look for parent of approximate_element until it has two children and the first child is the heading
while parent:
children = parent.query_selector_all(":scope > *")
if cond(children):
if isinstance(ret, int):
return children[ret].text_content() or self.translator("**unspecified**")
else:
return ret(children)
parent = parent.query_selector("xpath=..")
raise ValueError("Could not find parent element with condition.")
def _children_with_cond(
self: "WebPage",
element: Locator | ElementHandle | None,
cond: Callable,
ret: Callable | int,
) -> str:
if element is None:
return ""
# Getting the children of an element, test condition, return the `index` or apply res
# on the children element if the condition is met. Otherwise locate the first child and repeat the process.
child: ElementHandle | None = (
element.element_handle() if isinstance(element, Locator) else element
)
# look for parent of approximate_element until it has two children and the first child is the heading
while child:
children = child.query_selector_all(":scope > *")
if cond(children):
if isinstance(ret, int):
return children[ret].text_content() or self.translator("**unspecified**")
return ret(children)
if not children:
raise ValueError("Could not find child element with condition.")
# or we could use query_selector("./*[1]")
child = children[0]
raise ValueError("Could not find child element with condition.")

View File

@@ -0,0 +1,666 @@
import sys
import time
from logging import Logger
from pathlib import Path
from typing import ClassVar, List
import humanize
import inflect
import rich
import schedule # type: ignore
from playwright.sync_api import Browser, Playwright, sync_playwright
from rich.pretty import pretty_repr
from rich.prompt import Prompt
from .ai import AIBackend, AIResponse
from .config import Config, supported_ai_backends, supported_marketplaces
from .listing import Listing
from .marketplace import Marketplace, TItemConfig, TMarketplaceConfig
from .notification import NotificationStatus
from .user import User
from .utils import (
CounterItem,
KeyboardMonitor,
SleepStatus,
Translator,
amm_home,
cache,
calculate_file_hash,
counter,
doze,
hilight,
)
class MarketplaceMonitor:
active_marketplaces: ClassVar = {}
def __init__(
self: "MarketplaceMonitor",
config_files: List[Path] | None,
headless: bool | None,
logger: Logger | None,
) -> None:
for file_path in config_files or []:
if not file_path.exists():
raise FileNotFoundError(f"Config file {file_path} not found.")
default_config = amm_home / "config.toml"
self.config_files = ([default_config] if default_config.exists() else []) + (
[x.expanduser().resolve() for x in config_files or []]
)
#
self.config: Config | None = None
self.config_hash: str | None = None
self.headless = headless
self.ai_agents: List[AIBackend] = []
self.keyboard_monitor: KeyboardMonitor | None = None
self.playwright: Playwright = sync_playwright().start()
self.browser: Browser | None = None
self.logger = logger
def load_config_file(self: "MarketplaceMonitor") -> Config:
"""Load the configuration file."""
last_invalid_hash = None
while True:
new_file_hash = calculate_file_hash(self.config_files)
config_changed = self.config_hash is None or new_file_hash != self.config_hash
if not config_changed:
assert self.config is not None
return self.config
try:
# if the config file is ok, break
assert self.logger is not None
self.config = Config(self.config_files, self.logger)
self.config_hash = new_file_hash
# self.logger.debug(self.config)
assert self.config is not None
return self.config
except KeyboardInterrupt:
raise
except Exception as e:
if last_invalid_hash != new_file_hash:
last_invalid_hash = new_file_hash
if self.logger:
self.logger.error(
f"""{hilight("[Config]", "fail")} Error parsing:\n\n{hilight(str(e), "fail")}\n\nPlease fix the configuration and I will try again as soon as you are done."""
)
doze(60, self.config_files, self.keyboard_monitor)
continue
def load_ai_agents(self: "MarketplaceMonitor") -> None:
"""Load the AI agent."""
assert self.config is not None
for ai_config in (self.config.ai or {}).values():
if ai_config.enabled is False:
continue
if (
ai_config.provider is not None
and ai_config.provider.lower() in supported_ai_backends
):
ai_class = supported_ai_backends[ai_config.provider.lower()]
elif ai_config.name.lower() in supported_ai_backends:
ai_class = supported_ai_backends[ai_config.name.lower()]
else:
if self.logger:
self.logger.error(
f"""{hilight("[Config]", "fail")} Cannot determine an AI service provider from service name or provider."""
)
continue
try:
self.ai_agents.append(ai_class(config=ai_config, logger=self.logger))
# self.ai_agents[-1].connect()
# self.logger.info(
# f"""{hilight("[AI]", "succ")} Connected to {hilight(ai_config.name)}"""
# )
except KeyboardInterrupt:
raise
except Exception as e:
if self.logger:
self.logger.error(
f"""{hilight("[AI]", "fail")} Failed to connect to {hilight(ai_config.name, "fail")}: {e}"""
)
continue
def search_item(
self: "MarketplaceMonitor",
marketplace_config: TMarketplaceConfig,
marketplace: Marketplace,
item_config: TItemConfig,
) -> None:
"""Search for an item on the marketplace."""
new_listings: List[Listing] = []
listing_ratings = []
# users to notify is determined from item, then marketplace, then all users
assert self.config is not None
users_to_notify = (
item_config.notify or marketplace_config.notify or list(self.config.user.keys())
)
for listing in marketplace.search(item_config):
# duplicated ID should not happen, but sellers could repost the same listing,
# potentially under different seller names
if listing.id in [x.id for x in new_listings] or listing.content in [
x.content for x in new_listings
]:
if self.logger:
self.logger.debug(f"Found duplicated result for {listing}")
continue
# if everyone has been notified
if all(
User(self.config.user[user], self.logger).notification_status(listing)
== NotificationStatus.NOTIFIED
for user in users_to_notify
):
if self.logger:
self.logger.info(
f"""{hilight("[Skip]", "info")} Already sent notification for item {hilight(listing.title)}, skipping."""
)
continue
# for x in self.find_new_items(found_items)
res = self.evaluate_by_ai(
listing, item_config=item_config, marketplace_config=marketplace_config
)
if self.logger:
if res.comment == AIResponse.NOT_EVALUATED:
if res.name:
self.logger.info(
f"""{hilight("[AI]", res.style)} {res.name or "AI"} did not evaluate {hilight(listing.title)}."""
)
else:
self.logger.info(
f"""{hilight("[AI]", res.style)} No AI available to evaluate {hilight(listing.title)}."""
)
else:
self.logger.info(
f"""{hilight("[AI]", res.style)} {res.name or "AI"} concludes {hilight(f"{res.conclusion} ({res.score}): {res.comment}", res.style)} for listing {hilight(listing.title)}."""
)
if item_config.rating:
acceptable_rating = item_config.rating[
0 if item_config.searched_count == 0 else -1
]
elif marketplace_config.rating:
acceptable_rating = marketplace_config.rating[
0 if item_config.searched_count == 0 else -1
]
else:
acceptable_rating = 3
if res.score < acceptable_rating:
if self.logger:
self.logger.info(
f"""{hilight("[Skip]", "fail")} Rating {hilight(f"{res.conclusion} ({res.score})")} for {listing.title} is below threshold {acceptable_rating}."""
)
counter.increment(CounterItem.EXCLUDED_LISTING, item_config.name)
continue
new_listings.append(listing)
listing_ratings.append(res)
p = inflect.engine()
if self.logger:
self.logger.info(
f"""{hilight("[Search]", "succ" if len(new_listings) > 0 else "fail")} {hilight(str(len(new_listings)))} new {p.plural_noun("listing", len(new_listings))} for {item_config.name} {p.plural_verb("is", len(new_listings))} found."""
)
if new_listings:
counter.increment(
CounterItem.NEW_VALIDATED_LISTING, item_config.name, len(new_listings)
)
for user in users_to_notify:
User(self.config.user[user], logger=self.logger).notify(
new_listings, listing_ratings, item_config
)
time.sleep(5)
def _select_translator(
self: "MarketplaceMonitor", language: str | None = None
) -> Translator | None:
"""Select the language for the marketplace."""
# self.config.translator.get(marketplace_config.language, None)
assert self.config is not None
if not language:
return None
if language in self.config.translator:
return self.config.translator[language]
# if there is no exact match, we are going to match the language code
# e.g. 'en' to 'en_US'
if "_" in language:
# if a more general languge exists?
if language.split("_")[0] in self.config.translator:
translator = self.config.translator[language.split("_")[0]]
if self.logger:
self.logger.info(
f"""{hilight("[Translator]", "info")} Using language {language.split("_")[0]} (locale {translator.locale}) for {language} translation."""
)
return translator
# if not, we are going to match the language code
# e.g. 'en' to 'en_US'
for name, translator in self.config.translator.items():
if name.startswith(language.split("_")[0] + "_"):
if self.logger:
self.logger.info(
f"""{hilight("[Translator]", "info")} Using language {name} (locale {translator.locale}) for {language} translation."""
)
return translator
# if there is no match, we are going to match the language code
# e.g. 'en' to 'en_US'
for name, translator in self.config.translator.items():
if name.startswith(language + "_"):
if self.logger:
self.logger.info(
f"""{hilight("[Translator]", "info")} Using language {name} (locale {translator.locale}) for {language} translation."""
)
return translator
raise RuntimeError(f"Cannot find translator for language {language}.")
def schedule_jobs(self: "MarketplaceMonitor") -> None:
"""Schedule jobs to run periodically."""
# we reload the config file each time when a scan action is completed
# this allows users to add/remove products dynamically.
self.load_config_file()
self.load_ai_agents()
assert self.config is not None
for marketplace_config in self.config.marketplace.values():
if marketplace_config.enabled is False:
continue
marketplace_class = supported_marketplaces[marketplace_config.name]
if marketplace_config.name in self.active_marketplaces:
marketplace = self.active_marketplaces[marketplace_config.name]
else:
marketplace = marketplace_class(
marketplace_config.name, self.browser, self.keyboard_monitor, self.logger
)
self.active_marketplaces[marketplace_config.name] = marketplace
# Configure might have been changed
marketplace.configure(
marketplace_config,
translator=self._select_translator(marketplace_config.language),
)
for item_config in self.config.item.values():
if item_config.enabled is False:
continue
if (
item_config.marketplace is None
or item_config.marketplace == marketplace_config.name
):
# wait for some time before next search
# interval (in minutes) can be defined both for the marketplace
# if there is any configuration file change, stop sleeping and search again
scheduled = None
start_at_list = item_config.start_at or marketplace_config.start_at
if start_at_list is not None and start_at_list:
for start_at in start_at_list:
if start_at.startswith("*:*:"):
# '*:*:12' to ':12'
if self.logger:
self.logger.info(
f"""{hilight("[Schedule]", "info")} Scheduling to search for {item_config.name} every minute at {start_at[3:]}s"""
)
scheduled = schedule.every().minute.at(start_at[3:])
elif start_at.startswith("*:"):
# '*:12:12' or '*:12'
if self.logger:
self.logger.info(
f"""{hilight("[Schedule]", "info")} Scheduling to search for {item_config.name} every hour at {start_at[1:]}m"""
)
scheduled = schedule.every().hour.at(
start_at[1:] if start_at.count(":") == 1 else start_at[2:]
)
else:
# '12:12:12' or '12:12'
if self.logger:
self.logger.info(
f"""{hilight("[Schedule]", "ss")} Scheduling to search for {item_config.name} every day at {start_at}"""
)
scheduled = schedule.every().day.at(start_at)
else:
search_interval = max(
item_config.search_interval
or marketplace_config.search_interval
or 30 * 60,
1,
)
max_search_interval = max(
item_config.max_search_interval
or marketplace_config.max_search_interval
or 60 * 60,
search_interval,
)
if self.logger:
self.logger.info(
f"""{hilight("[Schedule]", "info")} Scheduling to search for {item_config.name} every {humanize.naturaldelta(search_interval)} {'' if search_interval == max_search_interval else f'to {humanize.naturaldelta(max_search_interval)}'}"""
)
scheduled = schedule.every(search_interval).to(max_search_interval).seconds
if scheduled is None:
raise ValueError(
f"Cannot determine a schedule for {item_config.name} from configuration file."
)
scheduled.do(
self.search_item,
marketplace_config,
marketplace,
item_config,
).tag(item_config.name)
def handle_pause(self: "MarketplaceMonitor") -> None:
"""Handle interruption signal."""
if self.keyboard_monitor is None or not self.keyboard_monitor.is_paused():
return
rich.print(counter)
if not self.keyboard_monitor.confirm():
return
# now we should go to an interactive session
while True:
while True:
url = (
Prompt.ask(
f"""\nEnter an {hilight("ID")} or a {hilight("URL")} to check, or {hilight("exit")}."""
)
.strip("\x1b")
.strip()
)
if not url.isnumeric() and not url.startswith("https://"):
if url.endswith("exit"):
url = "exit"
break
if url:
print(f'Invalid input "{url}". Please try again.')
else:
break
if url == "exit":
break
try:
self.check_items([url], for_item=None)
except KeyboardInterrupt:
raise
except Exception as e:
if self.logger:
self.logger.debug(f"Failed to check item {url}: {e}")
def start_monitor(self: "MarketplaceMonitor") -> None:
"""Main function to monitor the marketplace."""
# start a browser with playwright, cannot use with statement since the jobs will be
# executed outside of the scope by schedule job runner
self.keyboard_monitor = KeyboardMonitor()
self.keyboard_monitor.start()
# Open a new browser page.
self.load_config_file()
assert self.config is not None
self.browser = self.playwright.chromium.launch(
headless=self.headless, proxy=self.config.monitor.get_proxy_options()
)
#
assert self.browser is not None
while True:
self.handle_pause()
self.schedule_jobs()
if not schedule.get_jobs():
# this actually should not happen because at least one item is required for the configuration file
if self.logger:
self.logger.error(
"No search job is defined. Please add search items to your config file."
)
self.handle_pause()
if doze(60, self.config_files, self.keyboard_monitor) == SleepStatus.BY_KEYBOARD:
self.keyboard_monitor.set_paused(True)
continue
# run all jobs at the first time, then on their own schedule
# we could have used schedule.run_all() but we would like to check if
# configuration file has been changed, if so, clear all jobs and restart
for job in schedule.get_jobs():
job.run()
self.handle_pause()
# if configuration file has been changed, clear all scheduled jobs and restart
new_file_hash = calculate_file_hash(self.config_files)
assert self.config_hash is not None
if new_file_hash != self.config_hash:
if self.logger:
self.logger.info(
f"""{hilight("[Config]", "info")} Config file changed, restarting monitor."""
)
schedule.clear()
break
if not schedule.get_jobs():
continue
# subsequent runs will be scheduled runs
while True:
next_job: schedule.Job | None = None
for job in schedule.jobs:
if job.next_run is None:
continue
if next_job is None or (
next_job.next_run and next_job.next_run > job.next_run
):
next_job = job
if next_job is None:
# no more job
if self.logger:
self.logger.warning(
f"""{hilight("[Schedule]", "fail")} No more active search job."""
)
sys.exit(0)
# assert next_job is not None
assert next_job.next_run is not None
idle_seconds = schedule.idle_seconds() or 0
if idle_seconds > 60:
# the sleep time might not be enough, causing this message
# to be sent repeatedly. Having a idle_seconds > 60 helps
# to reduce the frequency of this message.
if self.logger:
self.logger.info(
f"""{hilight("[Schedule]", "info")} Next job to search {hilight(str(next(iter(next_job.tags))))} scheduled to run in {humanize.naturaldelta(idle_seconds)} at {next_job.next_run.strftime("%Y-%m-%d %H:%M:%S")}"""
)
# sleep at most 1 hr, and print updated "next job" message
res = doze(
min(max(5, int(idle_seconds)), 60 * 60),
self.config_files,
self.keyboard_monitor,
)
if res == SleepStatus.BY_FILE_CHANGE:
# if configuration file has been changed, clear all scheduled jobs and restart
new_file_hash = calculate_file_hash(self.config_files)
assert self.config_hash is not None
if new_file_hash != self.config_hash:
if self.logger:
self.logger.info(
f"""{hilight("[Config]", "info")} Config file changed, restarting monitor."""
)
schedule.clear()
break
elif res == SleepStatus.BY_KEYBOARD:
self.keyboard_monitor.set_paused(True)
self.handle_pause()
schedule.run_pending()
def stop_monitor(self: "MarketplaceMonitor") -> None:
"""Stop the monitor."""
for marketplace in self.active_marketplaces.values():
marketplace.stop()
self.playwright.stop()
if self.keyboard_monitor:
self.keyboard_monitor.stop()
cache.close()
def check_items(
self: "MarketplaceMonitor", items: List[str] | None = None, for_item: str | None = None
) -> None:
"""Main function to monitor the marketplace."""
# we reload the config file each time when a scan action is completed
# this allows users to add/remove products dynamically.
self.load_config_file()
if for_item is not None:
assert self.config is not None
if for_item not in self.config.item:
raise ValueError(
f"Item {for_item} not found in config, available items are {', '.join(self.config.item.keys())}."
)
self.load_ai_agents()
post_urls = []
for post_url in items or []:
if post_url.isnumeric():
post_url = f"https://www.facebook.com/marketplace/item/{post_url}/"
if not post_url.startswith("https://www.facebook.com/marketplace/item"):
raise ValueError(f"URL {post_url} is not a valid Facebook Marketplace URL.")
post_urls.append(post_url)
if not post_urls:
raise ValueError("No URLs to check.")
# Open a new browser page.
for post_url in post_urls or []:
# check if item in config
assert self.config is not None
# which marketplace to check it?
for marketplace_config in self.config.marketplace.values():
if marketplace_config.enabled is False:
continue
marketplace_class = supported_marketplaces[marketplace_config.name]
if marketplace_config.name in self.active_marketplaces:
marketplace = self.active_marketplaces[marketplace_config.name]
else:
marketplace = marketplace_class(
marketplace_config.name, None, None, self.logger
)
self.active_marketplaces[marketplace_config.name] = marketplace
# Configure might have been changed
marketplace.configure(
marketplace_config,
translator=self._select_translator(marketplace_config.language),
)
# do we need a browser?
if Listing.from_cache(post_url) is None:
if self.browser is None:
if self.logger:
self.logger.info(
f"""{hilight("[Search]", "info")} Starting a browser because the item was not checked before."""
)
self.browser = self.playwright.chromium.launch(
headless=self.headless, proxy=self.config.monitor.get_proxy_options()
)
marketplace.set_browser(self.browser)
# ignore enabled
if for_item is None:
# get by asking user
name = None
item_names = list(self.config.item.keys())
if len(item_names) > 1:
name = Prompt.ask(
f"""Enter name of {hilight("search item")}""", choices=item_names
)
item_config = self.config.item[name or item_names[0]]
else:
item_config = self.config.item[for_item]
# do not search, get the item details directly
listing: Listing = marketplace.get_listing_details(post_url, item_config)
if self.logger:
self.logger.info(
f"""{hilight("[Retrieve]", "succ")} Details of the item is found: {pretty_repr(listing)}"""
)
if self.logger:
self.logger.info(
f"""{hilight("[Search]", "succ")} Checking {post_url} for item {item_config.name} with configuration {pretty_repr(item_config)}"""
)
marketplace.check_listing(listing, item_config)
rating = self.evaluate_by_ai(
listing, item_config=item_config, marketplace_config=marketplace_config
)
if self.logger:
if rating.comment == AIResponse.NOT_EVALUATED:
if rating.name:
self.logger.info(
f"""{hilight("[AI]", rating.style)} {rating.name or "AI"} did not evaluate {hilight(listing.title)}."""
)
else:
self.logger.info(
f"""{hilight("[AI]", rating.style)} No AI available to evaluate {hilight(listing.title)}."""
)
else:
self.logger.info(
f"""{hilight("[AI]", rating.style)} {rating.name or "AI"} concludes {hilight(f"{rating.conclusion} ({rating.score}): {rating.comment}", rating.style)} for listing {hilight(listing.title)}."""
)
# notification status?
users_to_notify = (
item_config.notify
or marketplace_config.notify
or list(self.config.user.keys())
)
# for notification usages
listing.name = item_config.name
for user in users_to_notify:
ns = User(self.config.user[user], self.logger).notification_status(listing)
if self.logger:
if ns == NotificationStatus.NOTIFIED:
self.logger.info(
f"""{hilight("[Notify]", "succ")} Notified {user} about {post_url}."""
)
elif ns == NotificationStatus.EXPIRED:
self.logger.info(
f"""{hilight("[Notify]", "info")} Already notified {user} about {post_url}. The notification is ow expired."""
)
elif ns == NotificationStatus.LISTING_CHANGED:
self.logger.info(
f"""{hilight("[Notify]", "info")} Already notified {user} about {post_url}, but the listing is now changed."""
)
elif ns == NotificationStatus.LISTING_DISCOUNTED:
self.logger.info(
f"""{hilight("[Notify]", "info")} Already notified {user} about {post_url}, but the listing is now discounted."""
)
else:
self.logger.info(
f"""{hilight("[Notify]", "info")} Not notified {user} about {post_url} yet."""
)
# testing notification
# User(self.config.user[user], logger=self.logger).notify(
# [listing], [rating], item_config, force=True
# )
def evaluate_by_ai(
self: "MarketplaceMonitor",
item: Listing,
item_config: TItemConfig,
marketplace_config: TMarketplaceConfig,
) -> AIResponse:
if item_config.ai is not None:
ai_agents = item_config.ai
elif marketplace_config.ai is not None:
ai_agents = marketplace_config.ai
else:
ai_agents = None
#
for agent in self.ai_agents:
if ai_agents is not None and agent.config.name not in ai_agents:
continue
try:
return agent.evaluate(item, item_config, marketplace_config)
except KeyboardInterrupt:
raise
except Exception as e:
if self.logger:
self.logger.error(
f"""{hilight("[AI]", "fail")} Failed to get an answer from {agent.config.name}: {e}"""
)
continue
return AIResponse(5, AIResponse.NOT_EVALUATED)

View File

@@ -0,0 +1,200 @@
import time
from collections import defaultdict
from dataclasses import dataclass, fields
from enum import Enum
from logging import Logger
from typing import Any, ClassVar, DefaultDict, List, Optional, Tuple, Type
import inflect
from .ai import AIResponse # type: ignore
from .listing import Listing
from .utils import BaseConfig, hilight
class NotificationStatus(Enum):
NOT_NOTIFIED = 0
EXPIRED = 1
NOTIFIED = 2
LISTING_CHANGED = 3
LISTING_DISCOUNTED = 4
@dataclass
class NotificationConfig(BaseConfig):
required_fields: ClassVar[List[str]] = []
max_retries: int = 5
retry_delay: int = 60
def handle_max_retries(self: "NotificationConfig") -> None:
if not isinstance(self.max_retries, int):
raise ValueError("max_retries must be an integer.")
def handle_retry_delay(self: "NotificationConfig") -> None:
if not isinstance(self.retry_delay, int):
raise ValueError("retry_delay must be an integer.")
def _has_required_fields(self: "NotificationConfig") -> bool:
return all(getattr(self, field, None) is not None for field in self.required_fields)
@classmethod
def get_config(
cls: Type["NotificationConfig"], **kwargs: Any
) -> Optional["NotificationConfig"]:
"""Get the specific subclass name from the specified keys, for validation purposes"""
for subclass in cls.__subclasses__():
acceptable_keys = {field.name for field in fields(subclass)}
if all(name in acceptable_keys for name in kwargs.keys()):
return subclass(**{k: v for k, v in kwargs.items() if k != "type"})
res = subclass.get_config(**kwargs)
if res is not None:
return res
return None
@classmethod
def notify_all(
cls: type["NotificationConfig"], config: "NotificationConfig", *args, **kwargs: Any
) -> bool:
"""Call the notify method of all subclasses"""
succ = []
for subclass in cls.__subclasses__():
if hasattr(subclass, "notify") and subclass.__name__ not in [
"UserConfig",
"PushNotificationConfig",
]:
succ.append(subclass.notify(config, *args, **kwargs))
# subclases
succ.append(subclass.notify_all(config, *args, **kwargs))
return any(succ)
def send_message_with_retry(
self: "NotificationConfig",
title: str,
message: str,
logger: Logger | None = None,
) -> bool:
if not self._has_required_fields():
return False
for attempt in range(self.max_retries):
try:
res = self.send_message(title=title, message=message, logger=logger)
if logger:
logger.info(
f"""{hilight("[Notify]", "succ")} Sent {self.name} a message with title {hilight(title)}"""
)
return res
except KeyboardInterrupt:
raise
except Exception as e:
if logger:
logger.debug(
f"""{hilight("[Notify]", "fail")} Attempt {attempt + 1} failed: {e}"""
)
if attempt < self.max_retries - 1:
if logger:
logger.debug(
f"""{hilight("[Notify]", "fail")} Retrying in {self.retry_delay} seconds..."""
)
time.sleep(self.retry_delay)
else:
if logger:
logger.error(
f"""{hilight("[Notify]", "fail")} Max retries reached. Failed to push note to {self.name}."""
)
return False
return False
def send_message(
self: "NotificationConfig",
title: str,
message: str,
logger: Logger | None = None,
) -> bool:
raise NotImplementedError("send_message needs to be defined.")
@dataclass
class PushNotificationConfig(NotificationConfig):
message_format: str | None = None
def handle_message_format(self: "PushNotificationConfig") -> None:
if self.message_format is None:
self.message_format = "plain_text"
if self.message_format not in ["plain_text", "markdown"]:
raise ValueError("message_format must be 'plain_text' or 'markdown'.")
def notify(
self: "PushNotificationConfig",
listings: List[Listing],
ratings: List[AIResponse],
notification_status: List[NotificationStatus],
force: bool = False,
logger: Logger | None = None,
) -> bool:
if not self._has_required_fields():
return False
#
# we send listings with different status with different messages
msgs: DefaultDict[NotificationStatus, List[Tuple[Listing, str]]] = defaultdict(list)
p = inflect.engine()
for listing, rating, ns in zip(listings, ratings, notification_status):
if ns == NotificationStatus.NOTIFIED and not force:
continue
msg = (
(
(
f"{listing.title}\n{listing.price}, {listing.location}\n"
f"{listing.post_url.split('?')[0]}"
)
if rating.comment == AIResponse.NOT_EVALUATED
else (
f"[{rating.conclusion} ({rating.score})] {listing.title}\n"
f"{listing.price}, {listing.location}\n"
f"{listing.post_url.split('?')[0]}\n"
f"AI: {rating.comment}"
)
)
if self.message_format == "plain_text"
else (
(
f"[**{listing.title}**]({listing.post_url.split('?')[0]})\n"
f"{listing.price}, {listing.location}\n"
f"{listing.description}"
)
if rating.comment == AIResponse.NOT_EVALUATED
else (
f"[{rating.conclusion} ({rating.score})] "
f"[**{listing.title}**]({listing.post_url.split('?')[0]})\n"
f"{listing.price}, {listing.location}\n"
f"{listing.description}\n"
f"**AI**: {rating.comment}"
)
)
)
msgs[ns].append((listing, msg))
if not msgs:
if logger:
logger.debug("No new listings to notify.")
return False
for ns, listing_msg in msgs.items():
if ns == NotificationStatus.NOT_NOTIFIED:
title = f"Found {len(listing_msg)} new {p.plural_noun(listing.name, len(listing_msg))} from {listing.marketplace}"
elif ns == NotificationStatus.EXPIRED:
title = f"Another look at {len(listing_msg)} {p.plural_noun(listing.name, len(listing_msg))} from {listing.marketplace}"
elif ns == NotificationStatus.LISTING_CHANGED:
title = f"Found {len(listing_msg)} updated {p.plural_noun(listing.name, len(listing_msg))} from {listing.marketplace}"
elif ns == NotificationStatus.LISTING_DISCOUNTED:
title = f"Found {len(listing_msg)} discounted {p.plural_noun(listing.name, len(listing_msg))} from {listing.marketplace}"
else:
title = f"Resend {len(listing_msg)} {p.plural_noun(listing.name, len(listing_msg))} from {listing.marketplace}"
message = "\n\n".join([x[1] for x in listing_msg])
#
if not self.send_message_with_retry(title, message, logger=logger):
return False
return True

View File

@@ -0,0 +1,62 @@
from dataclasses import dataclass
from logging import Logger
from typing import ClassVar, List
import requests # type: ignore
from .notification import PushNotificationConfig
from .utils import hilight
@dataclass
class NtfyNotificationConfig(PushNotificationConfig):
required_fields: ClassVar[List[str]] = ["ntfy_server", "ntfy_topic"]
message_format: str | None = None
ntfy_server: str | None = None
ntfy_topic: str | None = None
def handle_ntfy_server(self: "NtfyNotificationConfig") -> None:
if self.ntfy_server is None:
return
if not isinstance(self.ntfy_server, str) or not self.ntfy_server:
raise ValueError("An non-empty ntfy_server is needed.")
if not self.ntfy_server.startswith("https://") and not self.ntfy_server.startswith(
"http://"
):
raise ValueError("ntfy_server must start with https:// or http://")
def handle_ntfy_topic(self: "NtfyNotificationConfig") -> None:
if self.ntfy_topic is None:
return
if not isinstance(self.ntfy_topic, str) or not self.ntfy_topic:
raise ValueError("user requires an non-empty ntfy_topic.")
self.ntfy_topic = self.ntfy_topic.strip()
def send_message(
self: "NtfyNotificationConfig",
title: str,
message: str,
logger: Logger | None = None,
) -> bool:
msg = f"{message}\n\nSent by https://github.com/BoPeng/ai-marketplace-monitor"
assert self.ntfy_server is not None
assert self.ntfy_topic is not None
requests.post(
f'{self.ntfy_server.rstrip("/")}/{self.ntfy_topic}',
msg,
headers={
"Title": title,
"Markdown": "yes" if self.message_format == "markdown" else "no",
},
timeout=10,
)
if logger:
logger.info(
f"""{hilight("[Notify]", "succ")} Sent {self.name} a message {hilight(msg)}"""
)
return True

View File

@@ -0,0 +1,74 @@
from dataclasses import dataclass
from logging import Logger
from typing import ClassVar, List
from pushbullet import Pushbullet # type: ignore
from .notification import PushNotificationConfig
from .utils import hilight
@dataclass
class PushbulletNotificationConfig(PushNotificationConfig):
required_fields: ClassVar[List[str]] = ["pushbullet_token"]
pushbullet_token: str | None = None
pushbullet_proxy_type: str | None = None
pushbullet_proxy_server: str | None = None
def handle_pushbullet_token(self: "PushbulletNotificationConfig") -> None:
if self.pushbullet_token is None:
return
if not isinstance(self.pushbullet_token, str) or not self.pushbullet_token:
raise ValueError("An non-empty pushbullet_token is needed.")
self.pushbullet_token = self.pushbullet_token.strip()
def handle_pushbullet_proxy_type(self: "PushbulletNotificationConfig") -> None:
if self.pushbullet_proxy_type is None:
return
if not isinstance(self.pushbullet_proxy_type, str) or not self.pushbullet_proxy_type:
raise ValueError("user requires an non-empty pushbullet_proxy_type.")
self.pushbullet_proxy_type = self.pushbullet_proxy_type.strip()
def handle_pushbullet_proxy_server(self: "PushbulletNotificationConfig") -> None:
# pushbullet_proxy_server and pushbullet_proxy_type are both required to be set
# if either of them is set, then both of them must be set
if self.pushbullet_proxy_type is None and self.pushbullet_proxy_server is not None:
raise ValueError(
"user requires an non-empty pushbullet_proxy_type when pushbullet_proxy_server is set."
)
# if pushbullet_proxy_type is set, then pushbullet_proxy_server must be set
if self.pushbullet_proxy_type is not None and self.pushbullet_proxy_server is None:
raise ValueError(
"user requires an non-empty pushbullet_proxy_server when pushbullet_proxy_type is set."
)
if self.pushbullet_proxy_server is None:
return
if not isinstance(self.pushbullet_proxy_server, str) or not self.pushbullet_proxy_server:
raise ValueError("user requires an non-empty pushbullet_proxy_server.")
self.pushbullet_proxy_server = self.pushbullet_proxy_server.strip()
def send_message(
self: "PushbulletNotificationConfig",
title: str,
message: str,
logger: Logger | None = None,
) -> bool:
pb = Pushbullet(
self.pushbullet_token,
proxy=(
{self.pushbullet_proxy_type: self.pushbullet_proxy_server}
if self.pushbullet_proxy_server and self.pushbullet_proxy_type
else None
),
)
pb.push_note(
title, message + "\n\nSent by https://github.com/BoPeng/ai-marketplace-monitor"
)
if logger:
logger.info(
f"""{hilight("[Notify]", "succ")} Sent {self.name} a message with title {hilight(title)}"""
)
return True

View File

@@ -0,0 +1,64 @@
import http.client
import json
import urllib
from dataclasses import dataclass
from logging import Logger
from typing import ClassVar, List
from .notification import PushNotificationConfig
from .utils import hilight
@dataclass
class PushoverNotificationConfig(PushNotificationConfig):
required_fields: ClassVar[List[str]] = ["pushover_user_id", "pushover_api_token"]
pushover_user_id: str | None = None
pushover_api_token: str | None = None
def handle_pushover_user_id(self: "PushoverNotificationConfig") -> None:
if self.pushover_user_id is None:
return
if not isinstance(self.pushover_user_id, str) or not self.pushover_user_id:
raise ValueError("An non-empty pushover_user_id is needed.")
self.pushover_user_id = self.pushover_user_id.strip()
def handle_pushover_api_token(self: "PushoverNotificationConfig") -> None:
if self.pushover_api_token is None:
return
if not isinstance(self.pushover_api_token, str) or not self.pushover_api_token:
raise ValueError("user requires an non-empty pushover_api_token.")
self.pushover_api_token = self.pushover_api_token.strip()
def send_message(
self: "PushoverNotificationConfig",
title: str,
message: str,
logger: Logger | None = None,
) -> bool:
msg = f"{title}\n\n{message}\n\nSent by https://github.com/BoPeng/ai-marketplace-monitor"
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request(
"POST",
"/1/messages.json",
urllib.parse.urlencode(
{
"token": self.pushover_api_token,
"user": self.pushover_user_id,
"message": msg,
}
),
{"Content-type": "application/x-www-form-urlencoded"},
)
output = conn.getresponse().read().decode("utf-8")
data = json.loads(output)
if data["status"] != 1:
raise RuntimeError(output)
else:
if logger:
logger.info(
f"""{hilight("[Notify]", "succ")} Sent {self.name} a message {hilight(msg)}"""
)
return True

View File

View File

@@ -0,0 +1,57 @@
from dataclasses import dataclass, field
from typing import List
from .utils import BaseConfig
@dataclass
class RegionConfig(BaseConfig):
search_city: List[str] = field(default_factory=list)
full_name: str = ""
radius: List[int] = field(default_factory=list)
city_name: List[str] = field(default_factory=list)
def handle_search_city(self: "RegionConfig") -> None:
if isinstance(self.search_city, str):
self.search_city = [self.search_city]
# check if search_city is a list of strings
if not isinstance(self.search_city, list) or not all(
isinstance(x, str) for x in self.search_city
):
raise ValueError(f"Region {self.name} search_city must be a list of strings.")
def handle_radius(self: "RegionConfig") -> None:
if isinstance(self.radius, int):
self.radius = [self.radius]
elif not self.radius:
self.radius = [500] * len(self.search_city)
elif len(self.radius) != len(self.search_city):
raise ValueError(
f"Region {self.name} radius {self.radius} must be an integer or a list of integers with the same length as search_city {self.search_city}."
)
else:
for radius in self.radius:
if not isinstance(radius, int):
raise ValueError(
f"Region {self.name} radius must be an integer or a list of integers with the same length as search_city."
)
def handle_city_name(self: "RegionConfig") -> None:
if isinstance(self.city_name, str):
self.city_name = [self.city_name]
if not self.city_name:
if not self.search_city:
return
self.city_name = [x.capitalize() for x in self.search_city]
return
# check if city_name is a list of strings
if not isinstance(self.city_name, list) or not all(
isinstance(x, str) for x in self.city_name
):
raise ValueError(f"Region {self.name} city_name must be a list of strings.")
if len(self.city_name) != len(self.search_city):
raise ValueError(
f"Region {self.name} city_name {self.city_name} must be the same length as search_city {self.search_city}."
)

View File

@@ -0,0 +1,193 @@
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from logging import Logger
from typing import Any, List, Tuple, Type
from diskcache import Cache # type: ignore
from .ai import AIResponse # type: ignore
from .email_notify import EmailNotificationConfig
from .listing import Listing
from .marketplace import TItemConfig
from .notification import NotificationConfig, NotificationStatus
from .ntfy import NtfyNotificationConfig
from .pushbullet import PushbulletNotificationConfig
from .pushover import PushoverNotificationConfig
from .utils import CacheType, CounterItem, cache, convert_to_seconds, counter, hilight
@dataclass
class UserConfig(
EmailNotificationConfig,
PushbulletNotificationConfig,
PushoverNotificationConfig,
NtfyNotificationConfig,
):
"""UserConfiguration
Derive from EmailNotificationConfig, PushbulletNotificationConfig allows
the user config class to use settings from both classes.
It is possible to dynamically added these classes as parent class
of UserConfig, but it is troublesome to make sure that these classes
are imported.
"""
notify_with: List[str] | None = None
remind: int | None = None
def handle_remind(self: "UserConfig") -> None:
if self.remind is None:
return
if self.remind is False:
self.remind = None
return
if self.remind is True:
# if set to true but no specific time, set to 1 day
self.remind = 60 * 60 * 24
return
if isinstance(self.remind, str):
try:
self.remind = convert_to_seconds(self.remind)
if self.remind < 60 * 60:
raise ValueError(f"Item {hilight(self.name)} remind must be at least 1 hour.")
except KeyboardInterrupt:
raise
except Exception as e:
raise ValueError(
f"Item {hilight(self.name)} remind {self.remind} is not recognized."
) from e
if not isinstance(self.remind, int):
raise ValueError(
f"Item {hilight(self.name)} remind must be an time (e.g. 1 day) or false."
)
def handle_notify_with(self: "UserConfig") -> None:
if self.notify_with is None:
return
if isinstance(self.notify_with, str):
self.notify_with = [self.notify_with]
if not isinstance(self.notify_with, list) or not all(
isinstance(x, str) for x in self.notify_with
):
raise ValueError(
f"Item {hilight(self.name)} notify_with must be a list of notification section values."
)
class User:
def __init__(self: "User", config: UserConfig, logger: Logger | None = None) -> None:
self.name = config.name
self.config = config
self.logger = logger
@classmethod
def get_config(cls: Type["User"], **kwargs: Any) -> UserConfig:
return UserConfig(**kwargs)
def notified_key(self: "User", listing: Listing) -> Tuple[str, str, str, str]:
return (CacheType.USER_NOTIFIED.value, listing.marketplace, listing.id, self.name)
def to_cache(self: "User", listing: Listing, local_cache: Cache | None = None) -> None:
(cache if local_cache is None else local_cache).set(
self.notified_key(listing),
(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), listing.hash, listing.price),
tag=CacheType.USER_NOTIFIED.value,
)
def _is_discounted(self: "User", old_price: str | None, new_price: str | None) -> bool:
def to_price(price_str: str | None):
if not price_str or price_str == "**unspecified**":
# invalid price is "very expensive", the new one might be cheaper.
return 999999999
matched = re.match(r"(\D*)\d+", price_str)
if matched:
currency = matched.group(1).strip()
price_str = price_str.replace(currency, "")
try:
return float(price_str.replace(",", "").replace(" ", ""))
except:
return 999999999
return to_price(old_price) > to_price(new_price)
def notification_status(
self: "User", listing: Listing, local_cache: Cache | None = None
) -> NotificationStatus:
notified = (cache if local_cache is None else local_cache).get(self.notified_key(listing))
# not notified before, or saved information is of old type
if notified is None:
return NotificationStatus.NOT_NOTIFIED
if isinstance(notified, str):
# old style cache
notification_date, listing_hash, listing_price = notified, None, None
else:
assert isinstance(notified, tuple)
if len(notified) == 2:
notification_date, listing_hash, listing_price = (*notified, None)
else:
notification_date, listing_hash, listing_price = notified
if listing_price is not None and self._is_discounted(listing_price, listing.price):
return NotificationStatus.LISTING_DISCOUNTED
# if listing_hash is not None, we need to check if the listing is still valid
if listing_hash is not None and listing_hash != listing.hash:
return NotificationStatus.LISTING_CHANGED
# notified before and remind is None, so one notification will remain valid forever
if self.config.remind is None:
return NotificationStatus.NOTIFIED
# if remind is not None, we need to check the time
expired = datetime.strptime(notification_date, "%Y-%m-%d %H:%M:%S") + timedelta(
seconds=self.config.remind
)
# if expired is in the future, user is already notified.
return (
NotificationStatus.NOTIFIED if expired > datetime.now() else NotificationStatus.EXPIRED
)
def time_since_notification(
self: "User", listing: Listing, local_cache: Cache | None = None
) -> int:
key = self.notified_key(listing)
notified = (cache if local_cache is None else local_cache).get(key)
if notified is None:
return -1
notification_date = notified if isinstance(notified, str) else notified[0]
return (datetime.now() - datetime.strptime(notification_date, "%Y-%m-%d %H:%M:%S")).seconds
def notify(
self: "User",
listings: List[Listing],
ratings: List[AIResponse],
item_config: TItemConfig,
local_cache: Cache | None = None,
force: bool = False,
) -> None:
if self.config.enabled is False:
if self.logger:
self.logger.info(
f"""{hilight("[Notify]", "skip")} User {hilight(self.name)} is disabled."""
)
return
statuses = [self.notification_status(listing, local_cache) for listing in listings]
if NotificationConfig.notify_all(
self.config, listings, ratings, statuses, force=force, logger=self.logger
):
counter.increment(CounterItem.NOTIFICATIONS_SENT, item_config.name)
for listing, ns in zip(listings, statuses):
if force or ns != NotificationStatus.NOTIFIED:
self.to_cache(listing, local_cache=local_cache)

View File

@@ -0,0 +1,609 @@
import copy
import hashlib
import json
import os
import random
import re
import time
from dataclasses import asdict, dataclass, fields
from enum import Enum
from logging import Logger
from pathlib import Path
from typing import Any, Dict, List, Tuple, TypeVar
import parsedatetime # type: ignore
import requests # type: ignore
import rich
from diskcache import Cache # type: ignore
from playwright.sync_api import ProxySettings
from pyparsing import (
CharsNotIn,
Keyword,
ParserElement,
ParseResults,
Word,
alphanums,
infix_notation,
opAssoc,
)
from requests.exceptions import RequestException, Timeout # type: ignore
from rich.pretty import pretty_repr
try:
from pynput import keyboard # type: ignore
pynput_installed = True
except ImportError:
# some platforms are not supported
pynput_installed = False
import io
import rich.pretty
from PIL import Image
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
# home directory for all settings and caches
amm_home = Path.home() / ".ai-marketplace-monitor"
amm_home.mkdir(parents=True, exist_ok=True)
cache = Cache(amm_home)
TConfigType = TypeVar("TConfigType", bound="BaseConfig")
class SleepStatus(Enum):
NOT_DISRUPTED = 0
BY_KEYBOARD = 1
BY_FILE_CHANGE = 2
class CacheType(Enum):
LISTING_DETAILS = "listing-details"
AI_INQUIRY = "ai-inquiries"
USER_NOTIFIED = "user-notifications"
COUNTERS = "counters"
class CounterItem(Enum):
SEARCH_PERFORMED = "Search performed"
LISTING_EXAMINED = "Total listing examined"
LISTING_QUERY = "New listing fetched"
EXCLUDED_LISTING = "Listing excluded"
NEW_VALIDATED_LISTING = "New validated listing"
AI_QUERY = "Total AI Queries"
NEW_AI_QUERY = "New AI Queries"
FAILED_AI_QUERY = "Failed AI Queries)"
NOTIFICATIONS_SENT = "Notifications sent"
REMINDERS_SENT = "Reminders sent"
class KeyboardMonitor:
confirm_character = "c"
def __init__(self: "KeyboardMonitor") -> None:
self._paused: bool = False
self._listener: keyboard.Listener | None = None
self._sleeping: bool = False
self._confirmed: bool | None = None
def start(self: "KeyboardMonitor") -> None:
if pynput_installed:
self._listener = keyboard.Listener(on_press=self.handle_key_press)
self._listener.start() # start to listen on a separate thread
def stop(self: "KeyboardMonitor") -> None:
if self._listener:
self._listener.stop() # stop the listener
def start_sleeping(self: "KeyboardMonitor") -> None:
self._sleeping = True
def confirm(self: "KeyboardMonitor", msg: str | None = None) -> bool:
self._confirmed = False
rich.print(
msg
or f"Press {hilight(self.confirm_character)} to enter interactive mode in 10 seconds: ",
end="",
flush=True,
)
try:
count = 0
while self._confirmed is False:
time.sleep(0.1)
if self._confirmed:
return True
count += 1
# wait a total of 10s
if count > 100:
break
return self._confirmed
finally:
# whether or not confirm is successful, reset paused and confirmed flag
self._paused = False
self._confirmed = None
def is_sleeping(self: "KeyboardMonitor") -> bool:
return self._sleeping
def is_paused(self: "KeyboardMonitor") -> bool:
return self._paused
def is_confirmed(self: "KeyboardMonitor") -> bool:
return self._confirmed is True
def set_paused(self: "KeyboardMonitor", paused: bool = True) -> None:
self._paused = paused
if pynput_installed:
def handle_key_press(
self: "KeyboardMonitor", key: keyboard.Key | keyboard.KeyCode | None
) -> None:
# is sleeping, wake up
if self._sleeping:
if key == keyboard.Key.esc:
self._sleeping = False
return
# if waiting for confirmation, set confirm
if self._confirmed is False:
if getattr(key, "char", "") == self.confirm_character:
self._confirmed = True
return
# if being paused
if self.is_paused():
if key == keyboard.Key.esc:
print("Still searching ... will pause as soon as I am done.")
return
if key == keyboard.Key.esc:
print("Pausing search ...")
self._paused = True
class Counter:
def increment(self: "Counter", counter_key: CounterItem, item_name: str, by: int = 1) -> None:
key = (CacheType.COUNTERS.value, counter_key.value, item_name)
try:
cache.incr(key, by, default=None)
except KeyError:
# if key does not exist, set it to by, and set tag
cache.set(key, by, tag=CacheType.COUNTERS.value)
def __str__(self: "Counter") -> str:
"""Return pretty form of all non-zero counters"""
# this is super inefficient. Thankfully we are not calling this often.
# See https://github.com/grantjenks/python-diskcache/issues/341
# for details
counters = {
key: cache.get(key) for key in cache.iterkeys() if key[0] == CacheType.COUNTERS.value
}
item_names = {x[2] for x in counters.keys()}
cnts = {}
for item_name in item_names:
# per-item statistics
cnts[item_name] = {
x.value: counters.get((CacheType.COUNTERS.value, x.value, item_name), 0)
for x in CounterItem
if counters.get((CacheType.COUNTERS.value, x.value, item_name), 0)
}
# total statistics
cnts["Total"] = {
x.value: sum(
counters.get((CacheType.COUNTERS.value, x.value, item_name), 0)
for item_name in item_names
)
for x in CounterItem
if sum(
counters.get((CacheType.COUNTERS.value, x.value, item_name), 0)
for item_name in item_names
)
}
return pretty_repr(cnts)
counter = Counter()
def hash_dict(obj: Dict[str, Any]) -> str:
"""Hash a dictionary to a string."""
dict_string = json.dumps(obj).encode("utf-8")
return hashlib.sha256(dict_string).hexdigest()
@dataclass
class BaseConfig:
name: str
enabled: bool | None = None
def __post_init__(self: "BaseConfig") -> None:
"""Handle all methods that start with 'handle_' in the dataclass."""
for f in fields(self):
# test the type of field f, if it is a string or a list of string
# try to expand the string with environment variables
fvalue = getattr(self, f.name)
if isinstance(fvalue, str):
setattr(self, f.name, self._value_from_environ(fvalue))
elif isinstance(fvalue, list) and all(isinstance(x, str) for x in fvalue):
setattr(self, f.name, [self._value_from_environ(x) for x in fvalue])
handle_method = getattr(self, f"handle_{f.name}", None)
if handle_method:
handle_method()
def _value_from_environ(self: "BaseConfig", key: str) -> str:
"""Replace key with value from an environment variable if it has a format of ${KEY}"""
if not isinstance(key, str) or not key.startswith("${") or not key.endswith("}"):
return key
if key[2:-1] not in os.environ:
raise ValueError(f"Environment variable {key[2:-1]} not set")
return os.environ[key[2:-1]]
def handle_enabled(self: "BaseConfig") -> None:
if self.enabled is None:
return
if not isinstance(self.enabled, bool):
raise ValueError(f"Item {hilight(self.name)} enabled must be a boolean.")
@property
def hash(self: "BaseConfig") -> str:
return hash_dict(asdict(self))
@dataclass
class MonitorConfig(BaseConfig):
proxy_server: List[str] | None = None
proxy_bypass: str | None = None
proxy_username: str | None = None
proxy_password: str | None = None
def handle_proxy_server(self: "MonitorConfig") -> None:
if self.proxy_server is None:
return
if isinstance(self.proxy_server, str):
self.proxy_server = [self.proxy_server]
if not all(isinstance(x, str) for x in self.proxy_server):
raise ValueError(f"Item {hilight(self.name)} proxy_server must be a string.")
if not all(x.startswith("http://") or x.startswith("https://") for x in self.proxy_server):
raise ValueError(
f"Item {hilight(self.name)} proxy_server must start with http:// or https://"
)
def handle_proxy_bypass(self: "MonitorConfig") -> None:
if self.proxy_bypass is None:
return
if not isinstance(self.proxy_bypass, str):
raise ValueError(f"Item {hilight(self.name)} proxy_bypass must be a string.")
def handle_proxy_username(self: "MonitorConfig") -> None:
if self.proxy_username is None:
return
if not isinstance(self.proxy_username, str):
raise ValueError(f"Item {hilight(self.name)} proxy_username must be a string.")
def handle_proxy_password(self: "MonitorConfig") -> None:
if self.proxy_password is None:
return
if not isinstance(self.proxy_password, str):
raise ValueError(f"Item {hilight(self.name)} proxy_password must be a string.")
def get_proxy_options(self: "MonitorConfig") -> ProxySettings | None:
if not self.proxy_server:
return None
res = ProxySettings(server=random.choice(self.proxy_server))
if self.proxy_username and self.proxy_password:
res["username"] = self.proxy_username
res["password"] = self.proxy_password
if self.proxy_bypass:
res["bypass"] = self.proxy_bypass
return res
def calculate_file_hash(file_paths: List[Path]) -> str:
"""Calculate the SHA-256 hash of the file content."""
hasher = hashlib.sha256()
# they should exist, just to make sure
for file_path in file_paths:
if not file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
#
with open(file_path, "rb") as file:
while chunk := file.read(8192):
hasher.update(chunk)
return hasher.hexdigest()
def merge_dicts(dicts: list) -> dict:
"""Merge a list of dictionaries into a single dictionary, including nested dictionaries.
:param dicts: A list of dictionaries to merge.
:return: A single merged dictionary.
"""
def merge(d1: dict, d2: dict) -> dict:
for key, value in d2.items():
if key in d1:
if isinstance(d1[key], dict) and isinstance(value, dict):
d1[key] = merge(d1[key], value)
elif isinstance(d1[key], list) and isinstance(value, list):
d1[key].extend(value)
else:
d1[key] = value
else:
d1[key] = value
return d1
result: Dict[str, Any] = {}
for dictionary in dicts:
result = merge(result, dictionary)
return result
def normalize_string(string: str) -> str:
"""Normalize a string by replacing multiple spaces (including space, tab, and newline) with a single space."""
return re.sub(r"\s+", " ", string).lower()
ParserElement.enable_packrat()
double_quoted_string = ('"' + CharsNotIn('"').leaveWhitespace() + '"').setParseAction(
lambda t: t[1]
) # removes quotes, keeps only the content
single_quoted_string = ("'" + CharsNotIn("'").leaveWhitespace() + "'").setParseAction(
lambda t: t[1]
) # removes quotes, keeps only the content
special_chars = "!@#$%^&*-_=+[]{}|;:'\",.<>?/\\`~"
unquoted_string = Word(alphanums + special_chars)
operand = double_quoted_string | single_quoted_string | unquoted_string
and_op = Keyword("AND")
or_op = Keyword("OR")
not_op = Keyword("NOT")
# Define the grammar for parsing
expr = infix_notation(
operand,
[
(not_op, 1, opAssoc.RIGHT),
(and_op, 2, opAssoc.LEFT),
(or_op, 2, opAssoc.LEFT),
],
)
def is_substring(
var1: str | List[str], var2: str | List[str], logger: Logger | None = None
) -> bool:
"""Check if var1 is a substring of var2, after normalizing both strings. One of them can be a list of strings.
var1: can be a single string, or a list of string, for which a condition of OR is assumed.
this program will parse var11 for "AND", "OR" and "NOT", and return the results of the
logical expression.
var2: one or more strings for testing if strings in "var1" is a substring.
"""
if isinstance(var1, list):
return any(is_substring(x, var2, logger) for x in var1)
# parse the expression
parsed = ""
try:
parsed = expr.parseString(var1, parseAll=True)[0]
except Exception:
# treat var1 as literal string for searching.
if any(x in var1 for x in (" AND ", " OR ", " NOT ", "(NOT ")) or var1.startswith("NOT "):
if logger:
logger.warning(
f"Failed to parse {var1} as a logical expression. Treating it as literal string."
)
if isinstance(var2, str):
return normalize_string(var1) in normalize_string(var2)
return any(normalize_string(var1) in normalize_string(s2) for s2 in var2)
def evaluate_expression(parsed_expression: str | ParseResults) -> bool:
if isinstance(parsed_expression, str):
if isinstance(var2, str):
return normalize_string(parsed_expression) in normalize_string(var2)
return any(normalize_string(parsed_expression) in normalize_string(s) for s in var2)
if len(parsed_expression) == 1:
return evaluate_expression(parsed_expression[0])
if parsed_expression[0] == "NOT":
return not evaluate_expression(parsed_expression[1])
if parsed_expression[-2] == "AND":
return evaluate_expression(parsed_expression[:-2]) and evaluate_expression(
parsed_expression[-1]
)
if parsed_expression[-2] == "OR":
return evaluate_expression(parsed_expression[:-2]) or evaluate_expression(
parsed_expression[-1]
)
if logger:
logger.error(f"Invalid expression: {parsed_expression}")
return False
return evaluate_expression(parsed)
class ChangeHandler(FileSystemEventHandler):
def __init__(self: "ChangeHandler", files: List[str]) -> None:
self.changed = False
self.files = files
def on_modified(self: "ChangeHandler", event: FileSystemEvent) -> None:
if not event.is_directory and event.src_path in self.files:
self.changed = True
def doze(
duration: int, files: List[Path] | None = None, keyboard_monitor: KeyboardMonitor | None = None
) -> SleepStatus:
"""Sleep for a specified duration while monitoring the change of files.
Return:
0: if doze was done naturally.
1: if doze was disrupted by keyboard
2: if doze was disrupted by file change
"""
event_handler = ChangeHandler([str(x) for x in (files or [])])
observers = []
if keyboard_monitor:
keyboard_monitor.start_sleeping()
for filename in files or []:
if not filename.exists():
raise FileNotFoundError(f"File not found: {filename}")
observer = Observer()
# we can only monitor a directory
observer.schedule(event_handler, str(filename.parent), recursive=False)
observer.start()
observers.append(observer)
start_time = time.time()
try:
while time.time() - start_time < duration:
if event_handler.changed:
return SleepStatus.BY_FILE_CHANGE
time.sleep(1)
if keyboard_monitor and not keyboard_monitor.is_sleeping():
return SleepStatus.BY_KEYBOARD
return SleepStatus.NOT_DISRUPTED
finally:
for observer in observers:
observer.stop()
observer.join()
def extract_price(price: str) -> str:
if not price or price == "**unspecified**":
return price
# extract leading non-numeric characters as currency symbol
matched = re.match(r"(\D*)\d+", price)
if matched:
currency = matched.group(1).strip()
else:
currency = "$"
matches = re.findall(currency.replace("$", r"\$") + r"[\d,]+(?:\.\d+)?", price)
if matches:
return " | ".join(matches[:2])
return price
def convert_to_seconds(time_str: str) -> int:
cal = parsedatetime.Calendar(version=parsedatetime.VERSION_CONTEXT_STYLE)
time_struct, _ = cal.parse(time_str)
return int(time.mktime(time_struct) - time.mktime(time.localtime()))
def hilight(text: str, style: str = "name") -> str:
"""Highlight the keywords in the text with the specified color."""
color = {
"name": "cyan",
"fail": "red",
"info": "blue",
"succ": "green",
"dim": "gray",
}.get(style, "blue")
return f"[{color}]{text}[/{color}]"
def fetch_with_retry(
url: str,
timeout: int = 10,
max_retries: int = 3,
backoff_factor: float = 1.5,
logger: Logger | None = None,
) -> Tuple[bytes, str] | None:
"""Fetch URL content with retry logic
Args:
url: URL to fetch
timeout: Timeout in seconds
max_retries: Maximum number of retry attempts
backoff_factor: Multiplier for exponential backoff
logger: logger object
Returns:
Tuple of (content, content_type) if successful, None if failed
"""
if logger:
logger.debug(f"Fetching {url} with timeout {timeout}s")
for attempt in range(max_retries):
try:
response = requests.get(
url, timeout=timeout, stream=True # Good practice for downloading files
)
response.raise_for_status() # Raises exception for 4XX/5XX status codes
return response.content, response.headers["Content-Type"]
except Timeout:
wait_time = backoff_factor**attempt
if logger:
logger.warning(
f"Timeout fetching {url} (attempt {attempt + 1}/{max_retries}). "
f"Waiting {wait_time:.1f}s before retry"
)
if attempt < max_retries - 1:
time.sleep(wait_time)
except RequestException as e:
if logger:
logger.error(f"Error fetching {url}: {e!s}")
return None
if logger:
logger.error(f"Failed to fetch {url} after {max_retries} attempts")
return None
def resize_image_data(image_data: bytes, max_width: int = 800, max_height: int = 600) -> bytes:
# Create image object from binary data
try:
image = Image.open(io.BytesIO(image_data))
if image.format == "GIF":
return image_data
except Exception:
# if unacceptable file format, just return
return image_data
# Calculate new dimensions maintaining aspect ratio
width, height = image.size
ratio = min(max_width / width, max_height / height)
if ratio >= 1:
return image_data
new_width = int(width * ratio)
new_height = int(height * ratio)
# Resize image
resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Convert back to bytes
buffer = io.BytesIO()
resized_image.save(buffer, format=image.format)
return buffer.getvalue()
class Translator:
def __init__(
self: "Translator", locale: str | None = None, dictionary: Dict[str, str] | None = None
) -> None:
self.locale = locale
self._dictionary: Dict[str, str] = copy.deepcopy(dictionary or {})
def __call__(self: "Translator", word: str) -> str:
"""Return translated version"""
return self._dictionary.get(word, word)

172
tasks.py Normal file
View File

@@ -0,0 +1,172 @@
"""Tasks for maintaining the project.
Execute 'invoke --list' for guidance on using Invoke
"""
import platform
import webbrowser
from pathlib import Path
from typing import Optional
from invoke import call, task
from invoke.context import Context
from invoke.runners import Result
ROOT_DIR = Path(__file__).parent
DOCS_DIR = ROOT_DIR.joinpath("docs")
DOCS_BUILD_DIR = DOCS_DIR.joinpath("_build")
DOCS_INDEX = DOCS_BUILD_DIR.joinpath("index.html")
COVERAGE_FILE = ROOT_DIR.joinpath(".coverage")
COVERAGE_DIR = ROOT_DIR.joinpath("htmlcov")
COVERAGE_REPORT = COVERAGE_DIR.joinpath("index.html")
SOURCE_DIR = ROOT_DIR.joinpath("src/ai_marketplace_monitor")
TEST_DIR = ROOT_DIR.joinpath("tests")
PYTHON_TARGETS = [
SOURCE_DIR,
TEST_DIR,
DOCS_DIR.joinpath("conf.py"),
ROOT_DIR.joinpath("noxfile.py"),
Path(__file__),
]
PYTHON_TARGETS_STR = " ".join([str(p) for p in PYTHON_TARGETS])
def _run(c: Context, command: str) -> Optional[Result]:
return c.run(command, pty=platform.system() != "Windows")
@task()
def clean_build(c: Context) -> None:
"""Clean up files from package building."""
_run(c, "rm -fr build/")
_run(c, "rm -fr dist/")
_run(c, "rm -fr .eggs/")
_run(c, "find . -name '*.egg-info' -exec rm -fr {} +")
_run(c, "find . -name '*.egg' -exec rm -f {} +")
@task()
def clean_python(c: Context) -> None:
"""Clean up python file artifacts."""
_run(c, "find . -name '*.pyc' -exec rm -f {} +")
_run(c, "find . -name '*.pyo' -exec rm -f {} +")
_run(c, "find . -name '*~' -exec rm -f {} +")
_run(c, "find . -name '__pycache__' -exec rm -fr {} +")
@task()
def clean_tests(c: Context) -> None:
"""Clean up files from testing."""
_run(c, f"rm -f {COVERAGE_FILE}")
_run(c, f"rm -fr {COVERAGE_DIR}")
_run(c, "rm -fr .pytest_cache")
@task()
def clean_docs(c: Context) -> None:
"""Clean up files from documentation builds."""
_run(c, f"rm -fr {DOCS_BUILD_DIR}")
@task(pre=[clean_build, clean_python, clean_tests, clean_docs])
def clean(c: Context) -> None:
"""Run all clean sub-tasks."""
@task()
def install_hooks(c: Context) -> None:
"""Install pre-commit hooks."""
_run(c, "poetry run pre-commit install")
@task()
def hooks(c: Context) -> None:
"""Run pre-commit hooks."""
_run(c, "poetry run pre-commit run --all-files")
@task(name="format", help={"check": "Checks if source is formatted without applying changes"})
def format_(c: Context, check: bool = False) -> None:
"""Format code."""
isort_options = ["--check-only", "--diff"] if check else []
_run(c, f"poetry run isort {' '.join(isort_options)} {PYTHON_TARGETS_STR}")
black_options = ["--diff", "--check"] if check else ["--quiet"]
_run(c, f"poetry run black {' '.join(black_options)} {PYTHON_TARGETS_STR}")
@task()
def ruff(c: Context) -> None:
"""Run ruff."""
_run(c, f"poetry run ruff check {PYTHON_TARGETS_STR}")
@task()
def security(c: Context) -> None:
"""Run security related checks."""
_run(
c,
"poetry export --with dev --format=requirements.txt --without-hashes | "
"poetry run safety check --stdin --full-report",
)
@task(pre=[ruff, security, call(format_, check=True)])
def lint(c: Context) -> None:
"""Run all linting."""
@task()
def mypy(c: Context) -> None:
"""Run mypy."""
_run(c, f"poetry run mypy {PYTHON_TARGETS_STR}")
@task()
def tests(c: Context) -> None:
"""Run tests."""
pytest_options = ["--xdoctest", "--cov", "--cov-report=", "--cov-fail-under=0"]
_run(c, f"poetry run pytest {' '.join(pytest_options)} {TEST_DIR} {SOURCE_DIR}")
@task(
help={
"fmt": "Build a local report: report, html, json, annotate, html, xml.",
"open_browser": "Open the coverage report in the web browser (requires --fmt html)",
}
)
def coverage(c: Context, fmt: str = "report", open_browser: bool = False) -> None:
"""Create coverage report."""
if any(Path().glob(".coverage.*")):
_run(c, "poetry run coverage combine")
_run(c, f"poetry run coverage {fmt} -i")
if fmt == "html" and open_browser:
webbrowser.open(COVERAGE_REPORT.as_uri())
@task(
help={
"serve": "Build the docs watching for changes",
"open_browser": "Open the docs in the web browser",
}
)
def docs(c: Context, serve: bool = False, open_browser: bool = False) -> None:
"""Build documentation."""
_run(c, f"sphinx-apidoc -o {DOCS_DIR} {SOURCE_DIR}")
build_docs = f"sphinx-build -b html {DOCS_DIR} {DOCS_BUILD_DIR}"
_run(c, build_docs)
if open_browser:
webbrowser.open(DOCS_INDEX.absolute().as_uri())
if serve:
_run(c, f"poetry run watchmedo shell-command -p '*.rst;*.md' -c '{build_docs}' -R -D .")
@task(
help={
"part": "Part of the version to be bumped.",
"dry_run": "Don't write any files, just pretend. (default: False)",
}
)
def version(c: Context, part: str, dry_run: bool = False) -> None:
"""Bump version."""
bump_options = ["--dry-run"] if dry_run else []
_run(c, f"poetry run bump2version {' '.join(bump_options)} {part}")

1
tests/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""Unit test package for ai_marketplace_monitor."""

View File

File diff suppressed because one or more lines are too long

View File

File diff suppressed because one or more lines are too long

241
tests/regular_listing.html Normal file
View File

File diff suppressed because one or more lines are too long

257
tests/rental_listing.html Normal file
View File

File diff suppressed because one or more lines are too long

151
tests/search_result_1.html Normal file
View File

File diff suppressed because one or more lines are too long

65
tests/test_ai.py Normal file
View File

@@ -0,0 +1,65 @@
import pytest
from ai_marketplace_monitor.ai import OllamaBackend, OllamaConfig
from ai_marketplace_monitor.facebook import FacebookItemConfig, FacebookMarketplaceConfig
from ai_marketplace_monitor.listing import Listing
@pytest.mark.skipif(True, reason="Condition met, skipping this test")
def test_ai(
ollama_config: OllamaConfig,
item_config: FacebookItemConfig,
marketplace_config: FacebookMarketplaceConfig,
listing: Listing,
) -> None:
ai = OllamaBackend(ollama_config)
# ai.config = ollama_config
res = ai.evaluate(listing, item_config, marketplace_config)
assert res.score >= 1 and res.score <= 5
def test_prompt(
ollama: OllamaBackend,
listing: Listing,
item_config: FacebookItemConfig,
marketplace_config: FacebookMarketplaceConfig,
) -> None:
prompt = ollama.get_prompt(listing, item_config, marketplace_config)
assert item_config.name in prompt
assert (item_config.description or "something weird") in prompt
assert str(item_config.min_price) in prompt
assert str(item_config.max_price) in prompt
assert listing.title in prompt
assert listing.condition in prompt
assert listing.price in prompt
assert listing.post_url in prompt
def test_extra_prompt(
ollama: OllamaBackend,
listing: Listing,
item_config: FacebookItemConfig,
marketplace_config: FacebookMarketplaceConfig,
) -> None:
marketplace_config.extra_prompt = "This is an extra prompt"
prompt = ollama.get_prompt(listing, item_config, marketplace_config)
assert "extra prompt" in prompt
#
item_config.extra_prompt = "This overrides marketplace prompt"
prompt = ollama.get_prompt(listing, item_config, marketplace_config)
assert "extra prompt" not in prompt
assert "overrides marketplace prompt" in prompt
#
assert "Great deal: Fully matches" in prompt
item_config.rating_prompt = "something else"
prompt = ollama.get_prompt(listing, item_config, marketplace_config)
assert "Great deal: Fully matches" not in prompt
assert "something else" in prompt
#
assert "Evaluate how well this listing" in prompt
marketplace_config.prompt = "myprompt"
prompt = ollama.get_prompt(listing, item_config, marketplace_config)
assert "Evaluate how well this listing" not in prompt
assert "myprompt" in prompt

69
tests/test_aimm.py Normal file
View File

@@ -0,0 +1,69 @@
"""Tests for `ai_marketplace_monitor` module."""
import time
from diskcache import Cache # type: ignore
from ai_marketplace_monitor.ai import AIResponse # type: ignore
from ai_marketplace_monitor.facebook import FacebookItemConfig
from ai_marketplace_monitor.listing import Listing
from ai_marketplace_monitor.notification import NotificationStatus
from ai_marketplace_monitor.user import User
def test_version(version: str) -> None:
"""Sample pytest test function with the pytest fixture as an argument."""
assert version == "0.9.1"
def test_listing_cache(temp_cache: Cache, listing: Listing) -> None:
listing.to_cache(post_url=listing.post_url, local_cache=temp_cache)
#
new_listing = Listing.from_cache(listing.post_url, local_cache=temp_cache)
for attr in (
"marketplace",
"name",
"id",
"title",
"image",
"price",
"location",
"seller",
"condition",
"description",
):
assert getattr(listing, attr) == getattr(new_listing, attr)
def test_notification_cache(temp_cache: Cache, user: User, listing: Listing) -> None:
assert (
user.notification_status(listing, local_cache=temp_cache)
== NotificationStatus.NOT_NOTIFIED
)
assert user.time_since_notification(listing, local_cache=temp_cache) == -1
user.to_cache(listing, local_cache=temp_cache)
assert user.notified_key(listing) in temp_cache
assert user.notification_status(listing, local_cache=temp_cache) == NotificationStatus.NOTIFIED
assert user.time_since_notification(listing, local_cache=temp_cache) >= 0
#
user.config.remind = 1
time.sleep(2)
assert user.notification_status(listing, local_cache=temp_cache) == NotificationStatus.EXPIRED
# change listing
listing.price = "$30000"
assert (
user.notification_status(listing, local_cache=temp_cache)
== NotificationStatus.LISTING_CHANGED
)
def test_notify_all(
user: User, item_config: FacebookItemConfig, listing: Listing, ai_response: AIResponse
) -> None:
user.notify([listing], [ai_response], item_config)

379
tests/test_cli.py Normal file
View File

@@ -0,0 +1,379 @@
"""Tests for `ai_marketplace_monitor`.cli module."""
from dataclasses import asdict
from typing import Callable, List, Tuple, Type, Union
import pytest
from pytest import TempPathFactory
from typer.testing import CliRunner
import ai_marketplace_monitor
from ai_marketplace_monitor import cli
from ai_marketplace_monitor.config import Config
runner = CliRunner()
@pytest.mark.parametrize(
"options,expected",
[
# ([], "ai_marketplace_monitor.cli.main"),
(["--help"], "Usage: "),
(
["--version"],
f"AI Marketplace Monitor, version { ai_marketplace_monitor.__version__ }\n",
),
],
)
def test_command_line_interface(options: List[str], expected: str) -> None:
"""Test the CLI."""
result = runner.invoke(cli.app, options)
assert result.exit_code == 0
assert expected in result.stdout
@pytest.fixture(scope="session")
def config_file(tmp_path_factory: TempPathFactory) -> Callable:
def generate_config_file(content: str) -> str:
fn = tmp_path_factory.mktemp("config") / "test.toml"
with open(fn, "w") as f:
f.write(content)
return str(fn)
return generate_config_file
base_marketplace_cfg = """
[marketplace.facebook]
search_city = 'dallas'
"""
full_marketplace_cfg = """
[marketplace.facebook]
login_wait_time = 50
password = "password"
search_city = ['houston']
username = "username"
# the following are common options
seller_locations = "city"
condition = ['new', 'used_good']
date_listed = 7
delivery_method = 'local_pick_up'
exclude_sellers = "seller"
ai = []
max_price = 300
min_price = 200
rating = 4
max_search_interval = 40
notify = 'user1'
radius = 100
search_interval = 10
search_region = 'usa'
"""
base_item_cfg = """
[item.name]
search_phrases = 'search word one'
"""
full_item_cfg = """
[item.name]
antikeywords = ['exclude1', 'exclude2']
description = 'long description'
enabled = true
keywords = ['exclude1', 'exclude2']
search_phrases = 'search word one'
marketplace = 'facebook'
search_city = 'houston'
# the following are common options
seller_locations = "city"
condition = ['new', 'used_good']
date_listed = 7
ai = 'openai'
availability = ['out', 'all']
delivery_method = 'local_pick_up'
exclude_sellers = "seller"
max_price = 300
rating = 4
max_search_interval = '1d'
search_interval = '12h'
min_price = 200
notify = 'user1'
radius = 100
search_region = 'usa'
"""
base_user_cfg = """
[user.user1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
"""
full_user_cfg = """
[user.user1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
remind = '1 day'
[user.user2]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
"""
base_ai_cfg = """
[ai.openai]
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
"""
full_ai_cfg = """
[ai.openai]
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
model = 'gpt'
"""
base_pushbullet_cfg = """
[notification.pushbullet1]
pushbullet_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
"""
base_pushover_cfg = """
[notification.pushover]
pushover_user_id = "xxxxxx"
pushover_api_token = "dfafdafd"
"""
base_ntfy_cfg = """
[notification.ntfy]
ntfy_server = "https://xxxxxx"
ntfy_topic = "dfafdafd"
"""
base_email_cfg = """
[notification.gmail]
smtp_password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
"""
notify_user_cfg = """
[user.user1]
notify_with = ['pushbullet1', 'gmail']
"""
notify_user_pushover_cfg = """
[user.user1]
notify_with = 'pushover'
"""
notify_user_ntfy_cfg = """
[user.user1]
notify_with = 'ntfy'
"""
monitor_cfg = """
[monitor]
proxy_server = 'https://fdaf.fadfd.com'
proxy_username = 'adfa'
proxy_password = 'fadfadf'
"""
monitor_invalid_proxy_server_cfg = """
[monitor]
proxy_server = 'fdaf.fadfd.com'
proxy_username = 'adfa'
proxy_password = 'fadfadf'
"""
licensed_monitor_cfg = """
[monitor]
proxy_server = 'https://fdaf.fadfd.com'
proxy_username = 'adfa'
proxy_password = 'fadfadf'
"""
@pytest.mark.parametrize(
"config_content,acceptable",
[
(base_marketplace_cfg, False),
(base_item_cfg, False),
(base_user_cfg, False),
(base_marketplace_cfg + base_item_cfg + base_user_cfg, True),
(base_marketplace_cfg + base_item_cfg + base_user_cfg + base_ai_cfg, True),
(full_marketplace_cfg + full_item_cfg + full_user_cfg + full_ai_cfg, True),
(base_marketplace_cfg + full_item_cfg + base_user_cfg + base_ai_cfg, True),
# notification should match
(
base_marketplace_cfg + full_item_cfg + notify_user_cfg,
False,
),
# pushbullet
(
base_marketplace_cfg
+ base_item_cfg
+ notify_user_cfg
+ base_pushbullet_cfg
+ base_email_cfg,
True,
),
(
base_marketplace_cfg
+ base_item_cfg
+ notify_user_cfg
+ base_pushbullet_cfg.replace("pushbullet1", "somethingelse")
+ base_email_cfg,
False,
),
# pushover
(
base_marketplace_cfg + base_item_cfg + notify_user_pushover_cfg + base_pushover_cfg,
True,
),
(
base_marketplace_cfg
+ base_item_cfg
+ notify_user_pushover_cfg
+ base_pushover_cfg.replace("pushover", "somethingelse"),
False,
),
# ntfy
(
base_marketplace_cfg + base_item_cfg + notify_user_ntfy_cfg + base_ntfy_cfg,
True,
),
(
base_marketplace_cfg
+ base_item_cfg
+ notify_user_ntfy_cfg
+ base_ntfy_cfg.replace("ntfy", "somethingelse"),
False,
),
# user should match
(
base_marketplace_cfg + full_item_cfg.replace("user1", "unknown_user") + base_user_cfg,
False,
),
# no additional keys
(base_marketplace_cfg + "\na=1\n" + base_item_cfg + base_user_cfg, False),
(base_marketplace_cfg + base_item_cfg + "\na=1\n" + base_user_cfg, False),
(base_marketplace_cfg + base_item_cfg + base_user_cfg + "\na=1\n", False),
(base_marketplace_cfg + base_item_cfg + base_user_cfg + monitor_cfg, False),
(base_marketplace_cfg + base_item_cfg + base_user_cfg + licensed_monitor_cfg, True),
(
base_marketplace_cfg
+ base_item_cfg
+ base_user_cfg
+ monitor_invalid_proxy_server_cfg,
False,
),
],
)
def test_config(config_file: Callable, config_content: str, acceptable: bool) -> None:
"""Test the config command."""
cfg = config_file(config_content)
key_types: dict[str, Union[Type, Tuple[Type, ...]]] = {
"seller_locations": (list, type(None)),
"ai": (list, type(None)),
"availability": (list, type(None)),
"api_key": str,
"city_name": (list, type(None)),
"condition": (list, type(None)),
"date_listed": (list, type(None)),
"delivery_method": (list, type(None)),
"description": (str, type(None)),
"enabled": (bool, type(None)),
"antikeywords": (list, type(None)),
"exclude_sellers": (list, type(None)),
"keywords": (list, type(None)),
"language": (str, type(None)),
"login_wait_time": (int, type(None)),
"marketplace": (str, type(None)),
"max_price": (int, type(None)),
"max_search_interval": (int, type(None)),
"market_type": (str, type(None)),
"min_price": (int, type(None)),
"model": (str, type(None)),
"name": (str, type(None)),
"notify": (list, type(None)),
"password": (str, type(None)),
"prompt": (str, type(None)),
"extra_prompt": (str, type(None)),
"rating_prompt": (str, type(None)),
"pushbullet_token": str,
"radius": (list, type(None)),
"rating": (list, type(None)),
"remind": (int, type(None)),
"search_city": (list, type(None)),
"search_interval": (int, type(None)),
"search_phrases": list,
"search_region": (list, type(None)),
"searched_count": int,
"start_at": (list, type(None)),
"username": (str, type(None)),
}
if acceptable:
# print(config_content)
config = Config([cfg])
# assert the types
for key, value in asdict(config.marketplace["facebook"]).items():
assert isinstance(value, key_types[key]), f"{key} must be of type {key_types[key]}"
for item_cfg in config.item.values():
for key, value in asdict(item_cfg).items():
assert isinstance(value, key_types[key]), f"{key} must be of type {key_types[key]}"
# test if all elements can be frozen
for attr in ("item", "ai", "user", "marketplae"):
for item_cfg in getattr(config, attr, {}).values():
assert item_cfg.hash
else:
with pytest.raises(Exception):
Config([cfg])
alt_marketplace_cfg = """
[marketplace.houston]
search_city = 'houston'
"""
alt_item_cfg = """
[item.whatever]
marketplace = "houston"
search_phrases = "search word two"
"""
def test_support_multiple_marketplaces(config_file: Callable) -> None:
"""Test the config command."""
cfg = config_file(
base_marketplace_cfg + alt_marketplace_cfg + alt_item_cfg + base_item_cfg + base_user_cfg
)
config = Config([cfg])
assert len(config.marketplace) == 2
assert len(config.item) == 2
assert len(config.user) == 1
assert config.item["name"].marketplace == "facebook"
assert config.item["whatever"].marketplace == "houston"
assert config.marketplace["facebook"].search_city == ["dallas"]
assert config.marketplace["houston"].search_city == ["houston"]
alt_ai_cfg = """
[ai.some_ai]
provider = 'OpenAI'
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
model = 'gpt_none'
base_url = 'http://someother.com'
"""
def test_multiplace_ai_agent(config_file: Callable) -> None:
"""Test the config command."""
cfg = config_file(
base_marketplace_cfg + base_ai_cfg + base_item_cfg + alt_ai_cfg + base_user_cfg
)
config = Config([cfg])
assert len(config.marketplace) == 1
assert len(config.ai) == 2
assert config.ai["openai"].api_key == "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
assert config.ai["some_ai"].model == "gpt_none"

79
tests/test_facebook.py Normal file
View File

@@ -0,0 +1,79 @@
import time
from pathlib import Path
import pytest
from pytest_playwright.pytest_playwright import CreateContextCallback # type: ignore
from ai_marketplace_monitor.facebook import FacebookSearchResultPage, parse_listing
def test_search_page(
new_context: CreateContextCallback, filename: str = "search_result_1.html"
) -> None:
local_file_path = Path(__file__).parent / filename
page = new_context(java_script_enabled=False).new_page()
page.goto(f"file://{local_file_path}")
for _ in range(10):
p = FacebookSearchResultPage(page)
page.wait_for_load_state("domcontentloaded")
listings = p.get_listings()
if len(listings) != 0:
break
time.sleep(1)
for idx, listing in enumerate(listings):
assert listing.marketplace == "facebook"
assert listing.id.isnumeric(), f"wrong id for listing {idx+1} with title {listing.title}"
assert listing.title, f"No title is found {idx+1} with title "
assert listing.image, f"wrong image for listing {idx+1} with title {listing.title}"
assert listing.post_url, f"wrong post_url for listing {idx+1} with title {listing.title}"
assert listing.price, f"wrong price for listing {idx+1} with title {listing.title}"
if idx == 10:
assert (
listing.location == ""
), f"listing {idx+1} with title {listing.title} has empty location"
else:
assert (
listing.location
), f"wrong location for listing {idx+1} with title {listing.title}"
assert listing.seller == "", "Seller should be empty"
assert len(listings) == 21
@pytest.mark.parametrize(
"filename,price,seller,location",
[
("regular_listing.html", "$10", "Austin Ewing", "MS"),
("rental_listing.html", "$150", "Perry Burton", "Houston, TX"),
(
"auto_with_about_and_description_listing.html",
"**unspecified**",
"Lily Ortiz",
"Houston, TX",
),
("auto_with_description_listing.html", "€6,695", "Abdel Abdel", "Bergen op Zoom, NB"),
],
)
def test_listing_page(
new_context: CreateContextCallback,
filename: str,
price: str,
seller: str,
location: str,
) -> None:
local_file_path = Path(__file__).parent / filename
page = new_context(java_script_enabled=False).new_page()
page.goto(f"file://{local_file_path}")
page.wait_for_load_state("domcontentloaded")
listing = parse_listing(page, "post_url", None)
assert listing is not None, f"Should be able to parse {filename}"
assert listing.title, f"Title of {filename} should be {listing.title}"
assert listing.price == price, f"Price of {filename} should be {listing.price}"
assert listing.location == location, f"Location of {filename} should be {listing.location}"
assert listing.seller == seller, f"Seller of {filename} should be {listing.seller}"
assert listing.image, f"Image of {filename} should not be empty"
assert listing.post_url, f"post_url of {filename} should not be empty"

44
tests/test_utils.py Normal file
View File

@@ -0,0 +1,44 @@
from typing import List
import pytest
from ai_marketplace_monitor.utils import is_substring
@pytest.mark.parametrize(
"var1,var2,res",
[
["b1", "AB1", True],
(["go pro", "gopro"], "gopro hero", True),
('"go pro" OR gopro', "gopro hero", True),
('"go pro" AND gopro', "gopro hero", False),
(["go pro", "gopro"], "something", False),
(["go pro", "gopro"], "go pro", True),
(["go pro", "gopro"], "gopro", True),
(["go pro", "gopro"], "gopro hero", True),
# literal AND works
("AND", " AND Camera", True),
('AND OR "gopro', " AND Camera", True),
('"gopro" OR "AND"', " AND Camera", True),
(['"go pro" AND 11', "gopro AND 12"], "gopro hero 12", True),
("DJI AND Drone AND NOT Camera", "dji drone", True),
("DJI AND Drone AND NOT Camera", "dji drone camera", False),
("DJI AND Drone AND NOT Camera", "dji camera", False),
("DJI AND Drone AND NOT Camera", "drone", False),
("DJI AND Drone AND NOT Camera", "drone from somewhere else", False),
("DJI AND (Drone OR Camera)", "dji drone", True),
("DJI AND (Drone OR Camera)", "dji camera", True),
("DJI AND (Drone OR Camera)", "dji drone camera", True),
("DJI AND (Drone OR Camera)", "drone camera from somewhere else", False),
("DJI AND (Drone)", "drone camera from somewhere else", False),
("DJI AND (Drone)", "drone DJI from somewhere else", True),
("DJI AND (NOT Drone)", "drone DJI from somewhere else", False),
("DJI AND (Drone AND from)", "drone DJI from somewhere else", True),
("DJI AND (Drone AND something)", "drone DJI from somewhere else", False),
("DJI AND (Drone OR (camera AND bad))", "drone DJI from somewhere else", True),
("DJI AND (Drone OR (camera AND bad))", " DJI camera from somewhere else", False),
("DJI AND (Drone OR (camera AND bad))", " bad DJI camera from somewhere else", True),
],
)
def test_is_substring(var1: List[str] | str, var2: str, res: bool) -> None:
assert is_substring(var1, var2) == res