### Install PostgreSQL on Linux (Debian/Ubuntu) Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Installs PostgreSQL and its contrib package on Debian/Ubuntu-based Linux distributions and enables the service to start on boot. It also starts the PostgreSQL service. ```bash sudo apt update sudo apt install postgresql postgresql-contrib sudo systemctl enable postgresql sudo systemctl start postgresql ``` -------------------------------- ### Clone Mediaplanpy Repository Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Clones the mediaplanpy repository from GitHub and sets up the project for local development. Includes steps for creating a virtual environment and installing the package in editable mode. ```Bash git clone https://github.com/planmatic/mediaplanpy cd mediaplanpy python -m venv .venv source .venv/bin/activate pip install -e . ``` -------------------------------- ### Install Mediaplanpy with Pip Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Installs the mediaplanpy package directly from GitHub using pip. This is the recommended method for most users to quickly integrate the library into their projects. ```Bash pip install git+https://github.com/planmatic/mediaplanpy ``` -------------------------------- ### Install PostgreSQL on macOS Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Installs PostgreSQL using Homebrew on macOS and starts the PostgreSQL service. This is a prerequisite for using PostgreSQL as a database backend. ```bash brew install postgresql brew services start postgresql ``` -------------------------------- ### Verify PostgreSQL Installation Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Checks the installed version of the PostgreSQL client to verify the installation. ```bash psql --version ``` -------------------------------- ### Create PostgreSQL Database Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Creates a new database named 'mediaplanpy' using the PostgreSQL command-line interface, connecting as the 'postgres' superuser. ```bash psql -U postgres CREATE DATABASE mediaplanpy; ``` -------------------------------- ### Import Mediaplanpy Packages Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Imports the necessary classes, WorkspaceManager and MediaPlan, from the mediaplanpy library to begin working with media plans. ```Python # Import Package from mediaplanpy import WorkspaceManager, MediaPlan ``` -------------------------------- ### Configure Workspace Database Settings Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md An example JSON configuration for the workspace settings file, enabling PostgreSQL integration. It specifies connection details like host, port, database name, schema, table name, username, and password environment variable. ```json "database": { "enabled": true, "host": "localhost", "port": 5432, "database": "mediaplanpy", "schema": "public", "table_name": "media_plans", "username": "postgres", "password_env_var": "MEDIAPLAN_DB_PASSWORD", "ssl": false, "connection_timeout": 30, "auto_create_table": true } ``` -------------------------------- ### Create and Load Workspace Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Creates a new workspace for media plan data and loads it into memory. It outputs the workspace ID and the path to its settings file, which are essential for subsequent operations. ```Python # Create and Load a Workspace workspace_id, settings_file_path = workspace.create() workspace.load(workspace_id=workspace_id) print(f"Workspace ID: {workspace_id}") print(f"Workspace Settings File Path: {settings_file_path}") ``` -------------------------------- ### Initialize WorkspaceManager Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Initializes the WorkspaceManager, which is responsible for managing file organization and data persistence for media plans. This must be done before creating or editing any media plans. ```Python # Initialize Workspace Manager workspace = WorkspaceManager() ``` -------------------------------- ### Run SQL Query for Total Spend Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Executes a SQL query using DuckDB against the workspace data to calculate the total spend across all media plans. The result of the query is then printed. ```Python # Run SQL query for total spend query = "SELECT SUM(lineitem_cost_total) AS total_spend FROM {*}" result = workspace.sql_query(query) print(result) ``` -------------------------------- ### Query Media Plans Table (Bash) Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md This bash command queries the 'media_plans' table in the PostgreSQL database to verify if a new record has been inserted. It requires a running PostgreSQL instance and the 'mediaplanpy' database. ```bash psql -U postgres -d mediaplanpy -c "SELECT * FROM public.media_plans;" ``` -------------------------------- ### Create Media Plan Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Creates a new media plan object with essential campaign and metadata. This includes details like campaign name, objective, dates, budget, and audience information, linked to the initialized workspace. ```Python # Create a Media Plan media_plan = MediaPlan.create( created_by="you@example.com", campaign_name="Summer 2025 Campaign", campaign_objective="Brand Awareness", campaign_start_date="2025-07-01", campaign_end_date="2025-09-30", campaign_budget=100000, agency_id="A1", agency_name="Example Agency", advertiser_id="ADV1", advertiser_name="Sample Advertiser", product_id="P1", product_name="Sample Product", campaign_type_id="C1", campaign_type_name="Awareness", audience_name="Adults 18-54", audience_age_start=18, audience_age_end=54, audience_gender="Any", audience_interests=["Tech Enthusiasts"], location_type="Country", locations=["USA"], workflow_status_id="1", workflow_status_name="Planning", media_plan_name="Test Plan", created_by_id="U123", created_by_name="Your Name", comments="Initial version of media plan", is_current=True, is_archived=False, workspace_manager=workspace ) print(f"Media Plan Created: {media_plan.meta.id}") ``` -------------------------------- ### Test Database Connection and Create Media Plan Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Tests the configured PostgreSQL database connection by creating a new media plan and adding a line item to it. The plan is then saved, which triggers an insertion into the database. ```python from mediaplanpy import WorkspaceManager, MediaPlan # Load your existing workspace workspace = WorkspaceManager() workspace.load(workspace_id="workspace_6b48be28") # Replace with your Workspace ID # Create a new Media Plan plan = MediaPlan.create( created_by="you@example.com", campaign_name="Database Test Campaign", campaign_objective="Awareness", campaign_start_date="2025-09-01", campaign_end_date="2025-11-30", campaign_budget=10000, workspace_manager=workspace ) # Add a line item lineitem = plan.create_lineitem({ "name": "Search Ads", "channel": "Search", "vehicle": "Google", "partner": "Google", "media_product": "Google Ads", "location_type": "Country", "location_name": "USA", "target_audience": "Adults 18-54", "adformat": "Text", "kpi": "Clicks", "cost_total": 2500, "cost_currency": "USD" }) # Save the plan (this will insert into the database) plan.save(workspace) ``` -------------------------------- ### Direct Usage of Storage Backend and Format Handler (Python) Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Provides advanced usage examples for directly interacting with storage backends and format handlers. It shows how to get instances of these components and use their methods for serializing/deserializing data and reading/writing files. ```python from mediaplanpy.storage import get_storage_backend, get_format_handler_instance # Get workspace configuration workspace_config = manager.get_resolved_config() # Get storage backend backend = get_storage_backend(workspace_config) # Get format handler format_handler = get_format_handler_instance("json", indent=4) # Write the file serialized_data = format_handler.serialize(media_plan.to_dict()) backend.write_file("path/to/save.json", serialized_data) # Read the file read_content = backend.read_file("path/to/save.json") data = format_handler.deserialize(read_content) ``` -------------------------------- ### Import Media Plan from Excel Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Creates a new media plan by importing data from an Excel file located in the workspace's 'imports' subdirectory. The imported plan is then saved, and its ID is printed. ```python # Import a new media plan from Excel imported_plan = MediaPlan.import_from_excel( file_name="media_plan_export.xlsx", workspace_manager=workspace ) saved_path = imported_plan.save(workspace) print(f"Imported plan: {imported_plan.meta.id}") ``` -------------------------------- ### List Saved Media Plans Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Retrieves and prints the names and total spend of all media plans stored within the current workspace. This function iterates through the list of plans obtained from the workspace. ```python # List saved media plans plans = workspace.list_mediaplans() for plan in plans: print(plan["meta_name"], plan["stat_total_cost"]) ``` -------------------------------- ### Save Media Plan Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Saves the created media plan to the workspace, generating both a JSON file for the plan definition and a companion Parquet file for analytics. The output indicates the save path. ```Python # Save the Media Plan saved_path = media_plan.save(workspace) print(f"Media plan saved to: {saved_path}") ``` -------------------------------- ### Set PostgreSQL Password Environment Variable (macOS/Linux) Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Exports the 'MEDIAPLAN_DB_PASSWORD' environment variable with a specified password for the current session on macOS or Linux. For persistence, this command should be added to the user's shell configuration file (e.g., ~/.bashrc or ~/.zshrc). ```bash export MEDIAPLAN_DB_PASSWORD="your_password_here" ``` -------------------------------- ### Set PostgreSQL Password Environment Variable (Windows) Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Sets the 'MEDIAPLAN_DB_PASSWORD' environment variable to a specified password on Windows using PowerShell. This is used to securely provide the database password to the application. ```powershell setx MEDIAPLAN_DB_PASSWORD "your_password_here" ``` -------------------------------- ### Get Storage Backend Instance Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Creates an instance of a storage backend, such as LocalStorageBackend or S3StorageBackend. This is essential for performing direct storage operations and implementing custom workflows. ```Python from mediaplanpy.storage import get_storage_backend backend = get_storage_backend(workspace_config) ``` -------------------------------- ### Export Media Plan to Excel Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Exports a media plan, including its metadata and line items, to a formatted Excel file. The file is saved in the workspace's 'exports' folder, with an option to overwrite existing files. ```python # Export media plan to Excel media_plan.export_to_excel( workspace_manager=workspace, file_name="media_plan_export.xlsx", overwrite=True ) ``` -------------------------------- ### Get Supported Schema Versions Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Returns a list of all schema versions that are currently supported by the library. This aids in checking version compatibility. ```Python from mediaplanpy.schema import get_supported_versions versions = get_supported_versions() ``` -------------------------------- ### Add Line Item to Media Plan Source: https://github.com/planmatic/mediaplanpy/blob/main/GET_STARTED.md Adds a line item to the media plan, specifying details such as channel, vehicle, cost, and key performance indicators (KPIs). Multiple line items can be added to represent different aspects of the media campaign. ```Python # Add Line Items lineitem = media_plan.create_lineitem({ "name": "Search", "channel": "Search", "vehicle": "Google", "partner": "Google", "media_product": "Google Ads", "location_type": "Country", "location_name": "USA", "target_audience": "Adults 18-54", "adformat": "Text", "kpi": "Clicks", "cost_total": 5000, "cost_currency": "USD" }) print(f"Line Item Created: {lineitem.id}") ``` -------------------------------- ### Get Workspace Version Info Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves version information about the current workspace. This is crucial for version compatibility checks and planning potential upgrades. ```Python version_info = get_workspace_version_info() ``` -------------------------------- ### Exact Match Filter Example Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/workspace_query.md Shows how to filter data for an exact match on a specific field, such as retrieving all items belonging to campaign 'cmp-001'. ```Python exact_match_campaign = workspace.list_campaigns(filters={'campaign_id': 'cmp-001'}) ``` -------------------------------- ### Get Database Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Fetches the resolved database configuration for the workspace. This function is essential for establishing database connectivity and validating configuration settings. ```Python db_config = get_database_config() ``` -------------------------------- ### Get SDK Version Information Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves detailed version information for the MediaPlanPy SDK. This includes the SDK version, schema version, and release notes. It is valuable for troubleshooting and ensuring compatibility between different versions of the SDK and data. ```Python from mediaplanpy import get_version_info version_info = get_version_info() print(f"SDK Version: {version_info['sdk_version']}") print(f"Schema Version: {version_info['schema_version']}") ``` -------------------------------- ### Get Storage Backend Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves the storage backend configured for the current workspace. This is useful for direct storage operations, allowing interaction with different storage types like Local or S3. ```Python storage_backend = get_storage_backend() ``` -------------------------------- ### Query Media Plans Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Provides functions to list, search, and get summaries of media plans. It supports filtering by archived status and campaign ID, and searching with a query string across specified fields. ```Python def list_media_plans(self, include_archived: bool = True, campaign_id: Optional[str] = None) -> List[Dict[str, Any]] def search_media_plans(self, query: str, fields: Optional[List[str]] = None, include_archived: bool = True) -> List[Dict[str, Any]] def get_media_plan_summary(self, media_plan_id: str) -> Optional[Dict[str, Any]] ``` -------------------------------- ### MediaPlanPy Workspace Status Checks (Python) Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Provides examples of Python code for checking workspace status and feature enablement in MediaPlanPy, raising specific exceptions like `WorkspaceInactiveError` or `FeatureDisabledError` if conditions are not met. ```Python # Automatic status validation workspace.check_workspace_active("media plan creation") # Raises WorkspaceInactiveError if inactive # Feature-specific checks workspace.check_excel_enabled("Excel export") # Raises FeatureDisabledError if Excel disabled ``` -------------------------------- ### Get Format Handler Instance Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Creates an instance of a format handler, which is used for processing different file formats. This function is key for custom format handling and file processing tasks. ```Python from mediaplanpy.storage.formats import get_format_handler_instance handler = get_format_handler_instance("plan.json") ``` -------------------------------- ### Mediaplanpy CLI Entry Points Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Demonstrates the command-line interface entry points for the Mediaplanpy package, including general help and specific commands for workspace initialization and schema validation. ```bash mediaplanpy --help mediaplanpy workspace init mediaplanpy schema validate ``` -------------------------------- ### MediaPlanPy Workspace Configuration (v2.0 JSON) Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Illustrates the JSON structure for v2.0 workspace configuration, detailing settings for workspace identification, status, environment, storage, database, and Excel integration. ```JSON { "workspace_id": "workspace_12345678", "workspace_name": "Production Environment", "workspace_status": "active", "environment": "production", "workspace_settings": { "schema_version": "2.0", "last_upgraded": "2024-01-15", "sdk_version_required": "2.0.x" }, "storage": { "mode": "local", "local": { "base_path": "/data/mediaplans", "create_if_missing": true } }, "database": { "enabled": true, "host": "localhost", "port": 5432, "database": "mediaplans", "schema": "public", "table_name": "media_plans" }, "excel": { "enabled": true, "default_template": "templates/default_template.xlsx" } } ``` -------------------------------- ### Direct Usage of Storage Module (Python) Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Illustrates direct usage of the `read_mediaplan` and `write_mediaplan` functions from the storage module, passing the workspace configuration and media plan data. ```python from mediaplanpy.storage import read_mediaplan, write_mediaplan # Get workspace configuration workspace_config = manager.get_resolved_config() # Write media plan write_mediaplan(workspace_config, media_plan.to_dict(), "path/to/save.json") # Read media plan data = read_mediaplan(workspace_config, "path/to/save.json") ``` -------------------------------- ### Mediaplanpy High-Level API Usage Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Illustrates the high-level Python API usage for Mediaplanpy, showing how to initialize a WorkspaceManager, load workspace configuration, create a MediaPlan, and save it. ```python # Package-level imports from mediaplanpy import MediaPlan, WorkspaceManager, validate, migrate # High-level API workspace = WorkspaceManager() workspace.load() media_plan = MediaPlan.create(...) media_plan.save(workspace) ``` -------------------------------- ### Configure Storage in Workspace (JSON) Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Demonstrates how to configure storage settings, including the mode, local path, and default file format (JSON) within the workspace configuration file. ```json { "workspace_name": "Example Workspace", "storage": { "mode": "local", "local": { "base_path": "/path/to/storage", "create_if_missing": true } }, "storage_formats": { "default_format": "json", "json": { "indent": 2, "ensure_ascii": false } } } ``` -------------------------------- ### MediaPlan Creation and Loading Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Provides methods for creating new MediaPlan objects with specified campaign details and loading existing MediaPlans from a workspace. It handles campaign parameters, dates, budgets, and optional schema versions. ```Python def create(cls, created_by: str, campaign_name: str, campaign_objective: str, campaign_start_date: Union[str, date], campaign_end_date: Union[str, date], campaign_budget: Union[str, int, float, Decimal], schema_version: Optional[str] = None, workspace_manager: Optional['WorkspaceManager'] = None, **kwargs) -> "MediaPlan" def load(cls, workspace_manager: 'WorkspaceManager', path: Optional[str] = None, media_plan_id: Optional[str] = None, validate_version: bool = True, auto_migrate: bool = True) -> "MediaPlan" ``` -------------------------------- ### MediaPlan Factory Method for Creation Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md A class method used to create new MediaPlan instances with essential campaign details. This factory method simplifies the instantiation process by requiring core campaign information upfront. ```Python # Factory Methods @classmethod def create(cls, created_by: str, campaign_name: str, campaign_objective: str, campaign_start_date: Union[str, date], campaign_end_date: Union[str, date], campaign_budget: Union[str, int, float, Decimal], **kwargs) -> "MediaPlan" ``` -------------------------------- ### Dictionary Key Methods Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Lists the key methods for the Dictionary model, including checking field enablement and retrieving field captions. ```Python def is_field_enabled(self, field_name: str) -> bool def get_field_caption(self, field_name: str) -> Optional[str] def get_enabled_fields(self) -> Dict[str, str] ``` -------------------------------- ### WorkspaceManager Initialization and Creation Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Details the initialization of the WorkspaceManager, allowing specification of workspace paths, and the creation of new workspaces with customizable settings and storage paths. It supports overwriting existing workspaces and defining workspace names. ```Python def __init__(self, workspace_path: Optional[str] = None) def create(self, settings_path_name: Optional[str] = None, settings_file_name: Optional[str] = None, storage_path_name: Optional[str] = None, workspace_name: str = "Default", overwrite: bool = False, **kwargs) -> Tuple[str, str] ``` -------------------------------- ### Get Current Schema Version Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves the current version of the media plan schema. This is useful for version checking and ensuring compatibility between different components. ```Python from mediaplanpy.schema import get_current_version version = get_current_version() ``` -------------------------------- ### Save and Load Media Plans (Python) Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Shows how to use the MediaPlan model's save and load_from_storage methods with a WorkspaceManager. It covers both automatic path generation based on campaign ID and specifying custom paths for saving and loading. ```python from mediaplanpy import WorkspaceManager, MediaPlan # Load workspace manager = WorkspaceManager("path/to/workspace.json") manager.load() # Create a media plan media_plan = MediaPlan.create( campaign_id="fall_2025_campaign", # other required parameters... ) # Save to storage with automatic path generation based on campaign ID saved_path = media_plan.save(manager) # The media plan is saved to "fall_2025_campaign.json" # Alternatively, specify a path media_plan.save(manager, "campaigns/my_campaign.json") # Load from storage using campaign ID loaded_plan = MediaPlan.load_from_storage(manager, campaign_id="fall_2025_campaign") # Or load from a specific path loaded_plan = MediaPlan.load_from_storage(manager, "campaigns/my_campaign.json") ``` -------------------------------- ### Get Version Compatibility Type Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Determines the compatibility type of a given schema version. Possible return values include 'current', 'backwards_compatible', 'deprecated', or 'unsupported'. ```Python from mediaplanpy.schema import get_compatibility_type compatibility = get_compatibility_type("1.5") ``` -------------------------------- ### WorkspaceManager Loading and Validation Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Covers loading existing workspaces by path or ID, or from a configuration dictionary. It also includes a method to validate the integrity and configuration of the current workspace. ```Python def load(self, workspace_path: Optional[str] = None, workspace_id: Optional[str] = None, config_dict: Optional[Dict[str, Any]] = None) -> Dict[str, Any] def validate(self) -> bool ``` -------------------------------- ### Normalize Version Format Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Normalizes a version string to a consistent format, for example, converting 'v1.0.0' to '1.0'. This utility is helpful for version comparison and normalization tasks. ```Python from mediaplanpy.schema import normalize_version normalized = normalize_version("v1.0.0") ``` -------------------------------- ### Create MediaPlan Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Creates a new media plan with essential fields such as creator, campaign name, objective, dates, and budget. It supports optional parameters like schema version and workspace manager. ```Python from mediaplanpy import MediaPlan from datetime import date from decimal import Decimal media_plan = MediaPlan.create( created_by="john.doe@company.com", campaign_name="Q4 Brand Campaign", campaign_objective="awareness", campaign_start_date=date(2024, 10, 1), campaign_end_date=date(2024, 12, 31), campaign_budget=Decimal("100000"), product_name="Premium Product Line" ) ``` -------------------------------- ### Validate Campaign Dates Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Validates that the start date of a campaign is less than or equal to its end date. This is a crucial step for ensuring data consistency within campaign models. ```Python def validate_dates() -> Campaign: # Validates start_date <= end_date pass ``` -------------------------------- ### MediaPlanPy Variable Resolution in Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Demonstrates how environment variables like `${user_documents}` and `${user_home}` can be used within the workspace configuration file for dynamic path resolution. ```JSON { "storage": { "local": { "base_path": "${user_documents}/MediaPlans" } } } ``` -------------------------------- ### Mediaplanpy Direct Model API Usage Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Shows direct usage of Mediaplanpy models in Python, demonstrating how to load a MediaPlan from a workspace, specify a path, and perform comprehensive validation. ```python # Direct model usage media_plan = MediaPlan.load(workspace, path="plan.json") errors = media_plan.validate_comprehensive() ``` -------------------------------- ### Setting MediaPlanPy Environment Modes (Python) Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Shows how to programmatically set the environment for MediaPlanPy, switching between 'development' and 'production' modes to adjust validation and logging behavior. ```Python # Development workspace.config['environment'] = 'development' # Enables: verbose logging, schema warnings, experimental features # Production workspace.config['environment'] = 'production' # Enables: strict validation, performance optimization, minimal logging ``` -------------------------------- ### Get Custom Field Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves the configuration for a specific custom field. This is useful for managing custom data points within the media plan, such as UI generation or dynamic field handling. ```Python config = media_plan.get_custom_field_config("dim_custom1") if config and config.get("enabled"): print(f"Field caption: {config.get('caption')}") ``` -------------------------------- ### Get Recent Line Items Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves a list of line items from the workspace, optionally filtered by date and limited by count. This function is useful for fetching recent or specific sets of line item data. ```Python lineitems = workspace.list_lineitems( filters={"lineitem_start_date": {"min": "2023-01-01"}}, limit=100 ) ``` -------------------------------- ### Create Workspace Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Creates a new workspace configuration file for the MediaPlanPy SDK. It allows specifying a workspace name and storage path, with an option to overwrite existing configurations. Returns the workspace ID and the path to the settings file. ```Python from mediaplanpy import WorkspaceManager workspace = WorkspaceManager() workspace_id, config_path = workspace.create( workspace_name="My_Project", storage_path_name="/path/to/data" ) ``` -------------------------------- ### LineItem Standard Metrics Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Details the standard metrics for LineItems, including impressions, clicks, views, and various v2.0 additions like engagements and leads. ```Python # Metrics - Standard (v1.0: 3 fields, v2.0: +17 new fields) metric_impressions: Optional[Decimal] = None metric_clicks: Optional[Decimal] = None metric_views: Optional[Decimal] = None # v2.0 New Standard Metrics metric_engagements: Optional[Decimal] = None metric_followers: Optional[Decimal] = None metric_visits: Optional[Decimal] = None metric_leads: Optional[Decimal] = None metric_sales: Optional[Decimal] = None metric_add_to_cart: Optional[Decimal] = None metric_app_install: Optional[Decimal] = None metric_application_start: Optional[Decimal] = None metric_application_complete: Optional[Decimal] = None metric_contact_us: Optional[Decimal] = None metric_download: Optional[Decimal] = None metric_signup: Optional[Decimal] = None metric_max_daily_spend: Optional[Decimal] = None metric_max_daily_impressions: Optional[Decimal] = None metric_audience_size: Optional[Decimal] = None metric_custom1-10: Optional[Decimal] = None # 10 custom metric fields ``` -------------------------------- ### Load Workspace Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Loads workspace configuration for the MediaPlanPy SDK, supporting automatic migration. Configurations can be loaded via a workspace path, workspace ID, or directly from a dictionary. Returns the loaded workspace configuration. ```Python # Load by workspace ID config = workspace.load(workspace_id="workspace_abc123") # Load from specific path config = workspace.load(workspace_path="/path/to/workspace.json") ``` -------------------------------- ### SQL CREATE TABLE for media_plans Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Defines the structure of the `media_plans` table in SQL, including primary keys, campaign and line item details, metrics, custom fields, and indexes for performance optimization. This schema supports version 2.0 of the media plan structure. ```SQL CREATE TABLE media_plans ( -- Primary identification media_plan_id VARCHAR(255) PRIMARY KEY, media_plan_name VARCHAR(500), schema_version VARCHAR(20) NOT NULL, -- v2.0 Meta fields created_by_name VARCHAR(255) NOT NULL, created_by_id VARCHAR(255), created_at TIMESTAMP WITH TIME ZONE, is_current BOOLEAN, is_archived BOOLEAN, parent_id VARCHAR(255), -- Campaign information campaign_id VARCHAR(255) NOT NULL, campaign_name VARCHAR(500) NOT NULL, campaign_objective VARCHAR(500), campaign_start_date DATE NOT NULL, campaign_end_date DATE NOT NULL, campaign_budget_total DECIMAL(15,2) NOT NULL, -- v2.0 Campaign fields campaign_budget_currency VARCHAR(3), agency_id VARCHAR(255), agency_name VARCHAR(500), advertiser_id VARCHAR(255), advertiser_name VARCHAR(500), campaign_type_id VARCHAR(255), campaign_type_name VARCHAR(255), workflow_status_id VARCHAR(255), workflow_status_name VARCHAR(255), -- Line item information lineitem_id VARCHAR(255) NOT NULL, lineitem_name VARCHAR(500) NOT NULL, lineitem_start_date DATE NOT NULL, lineitem_end_date DATE NOT NULL, lineitem_cost_total DECIMAL(15,2) NOT NULL, -- v2.0 LineItem fields lineitem_cost_currency VARCHAR(3), lineitem_dayparts VARCHAR(255), lineitem_inventory VARCHAR(255), -- Channel and targeting lineitem_channel VARCHAR(255), lineitem_vehicle VARCHAR(255), lineitem_partner VARCHAR(255), -- Cost breakdown (6 standard + 10 custom) lineitem_cost_media DECIMAL(15,2), lineitem_cost_buying DECIMAL(15,2), lineitem_cost_platform DECIMAL(15,2), lineitem_cost_data DECIMAL(15,2), lineitem_cost_creative DECIMAL(15,2), lineitem_cost_custom1 DECIMAL(15,2), -- ... lineitem_cost_custom2-10 -- Standard metrics (3 legacy + 17 v2.0) lineitem_metric_impressions DECIMAL(15,2), lineitem_metric_clicks DECIMAL(15,2), lineitem_metric_views DECIMAL(15,2), lineitem_metric_engagements DECIMAL(15,2), lineitem_metric_leads DECIMAL(15,2), lineitem_metric_sales DECIMAL(15,2), -- ... additional v2.0 metrics -- Custom metrics (10 fields) lineitem_metric_custom1 DECIMAL(15,2), -- ... lineitem_metric_custom2-10 -- Custom dimensions (10 fields) lineitem_dim_custom1 VARCHAR(500), -- ... lineitem_dim_custom2-10 -- Timestamps last_updated TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, file_path VARCHAR(1000), -- Indexes for performance INDEX idx_campaign_id (campaign_id), INDEX idx_schema_version (schema_version), INDEX idx_created_at (created_at), INDEX idx_is_current (is_current), INDEX idx_workflow_status (workflow_status_name), INDEX idx_campaign_dates (campaign_start_date, campaign_end_date) ); ``` -------------------------------- ### Update Workspace Creation with DB Settings Source: https://github.com/planmatic/mediaplanpy/blob/main/CHANGE_LOG.md Enhanced the `Workspace.create()` method to incorporate database connection settings directly into the default Workspace Settings. This simplifies the configuration process for new workspaces. ```Python Workspace.create() ``` -------------------------------- ### Get Line Items as DataFrame and Analyze Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/workspace_query.md Retrieves line items for a specific campaign and returns them as a pandas DataFrame. It then performs a group-by operation to calculate the average cost per channel. ```Python items_df = workspace.list_lineitems( filters={'campaign_id': 'cmp-001'}, return_dataframe=True ) # Analyze with pandas avg_cost_by_channel = items_df.groupby('lineitem_channel')['lineitem_cost_total'].mean() ``` -------------------------------- ### LineItem Constructor Signature Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Provides the constructor signature for the LineItem model, including essential fields and optional keyword arguments. ```Python def __init__(self, id: str, name: str, start_date: date, end_date: date, cost_total: Decimal, **kwargs) ``` -------------------------------- ### Python StorageBackend Interface Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Defines the abstract interface for storage backends, specifying methods for file existence checks, reading, writing, listing, deletion, retrieving file information, and opening files. ```Python class StorageBackend(abc.ABC): @abc.abstractmethod def exists(self, path: str) -> bool: """Check if a file exists at the specified path.""" pass @abc.abstractmethod def read_file(self, path: str, binary: bool = False) -> Union[str, bytes]: """Read a file from the storage location.""" pass @abc.abstractmethod def write_file(self, path: str, content: Union[str, bytes]) -> None: """Write content to a file at the specified path.""" pass @abc.abstractmethod def list_files(self, path: str, pattern: Optional[str] = None) -> List[str]: """List files at the specified path.""" pass @abc.abstractmethod def delete_file(self, path: str) -> None: """Delete a file at the specified path.""" pass @abc.abstractmethod def get_file_info(self, path: str) -> Dict[str, Any]: """Get information about a file.""" pass @abc.abstractmethod def open_file(self, path: str, mode: str = 'r') -> Union[TextIO, BinaryIO]: """Open a file and return a file-like object.""" pass ``` -------------------------------- ### Mediaplanpy Storage Backend Registry Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Defines a dictionary mapping storage backend names (e.g., 'local', 's3') to their respective backend classes in mediaplanpy. ```Python # Storage backend registry (mediaplanpy/storage/__init__.py) _storage_backends = { 'local': LocalStorageBackend, 's3': S3StorageBackend, 'gdrive': GoogleDriveStorageBackend } ``` -------------------------------- ### WorkspaceManager Version Management Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Provides functionalities for managing workspace versions, including upgrading the workspace to a target SDK version, retrieving version information, and checking compatibility with the current SDK. ```Python def upgrade_workspace(self, target_sdk_version: Optional[str] = None, dry_run: bool = False) -> Dict[str, Any] def get_workspace_version_info(self) -> Dict[str, Any] def check_workspace_compatibility(self) -> Dict[str, Any] ``` -------------------------------- ### Mediaplanpy Format Handler Registry Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Maps format names (e.g., 'json', 'parquet') to their corresponding format handler classes within the mediaplanpy storage module. ```Python # Format handler registry (mediaplanpy/storage/formats/__init__.py) _format_handlers = { 'json': JsonFormatHandler, 'parquet': ParquetFormatHandler } ``` -------------------------------- ### Export Media Plan to Excel Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Exports a media plan to an Excel file. Supports specifying an output path and an optional template. The `include_documentation` parameter controls whether documentation details are included in the export. This function is useful for client deliverables and offline editing. ```Python from mediaplanpy.excel import export_to_excel excel_path = export_to_excel( media_plan_data, path="client_report.xlsx", include_documentation=True ) ``` -------------------------------- ### Mediaplanpy Format Extensions Mapping Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md A dictionary that maps file extensions (e.g., '.json', '.parquet') to their corresponding format identifiers used within mediaplanpy. ```Python # File extensions mapping FORMAT_EXTENSIONS = { '.json': 'json', '.parquet': 'parquet', '.xlsx': 'excel', '.xls': 'excel' } ``` -------------------------------- ### Import Media Plan from JSON Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Imports a media plan from a JSON file. This class method handles versioning and can optionally use a workspace manager for context. It's crucial for data recovery and migration. ```Python media_plan = MediaPlan.import_from_json("imported_plan.json", workspace_manager) media_plan = MediaPlan.import_from_json("plan.json", file_path="/path/to/file") ``` -------------------------------- ### Load Media Plan Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Loads a media plan either from a specified file path or by its unique ID. Supports automatic migration of compatible versions. ```Python # Load by ID media_plan = MediaPlan.load(workspace_manager, media_plan_id="plan_123") ``` ```Python # Load from specific path media_plan = MediaPlan.load(workspace_manager, path="mediaplans/plan_123.json") ``` -------------------------------- ### Python FormatHandler Interface Source: https://github.com/planmatic/mediaplanpy/blob/main/docs/storage.md Defines the abstract interface for format handlers, specifying methods for serializing and deserializing data to and from string or binary representations, and to/from file objects. ```Python class FormatHandler(abc.ABC): @abc.abstractmethod def serialize(self, data: Dict[str, Any], **kwargs) -> Union[str, bytes]: """Serialize data to the format's string or binary representation.""" pass @abc.abstractmethod def deserialize(self, content: Union[str, bytes], **kwargs) -> Dict[str, Any]: """Deserialize content from the format's string or binary representation.""" pass @abc.abstractmethod def serialize_to_file(self, data: Dict[str, Any], file_obj: Union[TextIO, BinaryIO], **kwargs) -> None: """Serialize data and write it to a file object.""" pass @abc.abstractmethod def deserialize_from_file(self, file_obj: Union[TextIO, BinaryIO], **kwargs) -> Dict[str, Any]: """Read and deserialize data from a file object.""" pass ``` -------------------------------- ### Upgrade Workspace Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Upgrades a workspace configuration to a new SDK or Schema version, with support for v2.0. It allows specifying a target SDK version and performing a dry run to preview changes without execution. Returns a dictionary detailing the upgrade results. ```Python # Check what would be upgraded result = workspace.upgrade_workspace(dry_run=True) print(f"Would migrate {result['json_files_migrated']} files") # Perform actual upgrade result = workspace.upgrade_workspace() ``` -------------------------------- ### Execute SQL Query Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Executes SQL queries against workspace Parquet files with S3 support. It allows for complex analytics, custom reporting, and data exploration using SQL syntax, with options to return data as a DataFrame or a list of dictionaries. ```Python # Query all data result = workspace.sql_query("SELECT DISTINCT campaign_id FROM {*}") ``` ```Python # Query with pattern matching result = workspace.sql_query( "SELECT SUM(cost_total) as total_spend FROM {campaign_*} WHERE channel='Digital'" ) ``` -------------------------------- ### Mediaplanpy Default Database Configuration Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Specifies the default configuration settings for database connections in mediaplanpy, including port, schema, table name, timeouts, and auto-creation options. ```Python # Database defaults (mediaplanpy/storage/database.py) DEFAULT_DATABASE_CONFIG = { 'port': 5432, 'schema': 'public', 'table_name': 'media_plans', 'connection_timeout': 30, 'auto_create_table': True, 'ssl': True } ``` -------------------------------- ### Create MediaPlan from Dictionary Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Constructs a MediaPlan object from a dictionary, including robust version handling. This method is ideal for importing data from external sources or API responses. ```Python data = {"meta": {...}, "campaign": {...}, "lineitems": [...]} media_plan = MediaPlan.from_dict(data) ``` -------------------------------- ### Mediaplanpy Version Information Constants Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Defines package version constants for the mediaplanpy SDK, including the SDK version, schema version, major and minor versions, and a dictionary mapping version numbers to release notes. ```Python # Package version constants (mediaplanpy/__init__.py) __version__ = '2.0.1' # SDK version __schema_version__ = '2.0' # Current schema version CURRENT_MAJOR = 2 # Major version number CURRENT_MINOR = 0 # Minor version number SUPPORTED_MAJOR_VERSIONS = [1, 2] # Supported major versions VERSION_NOTES = { '1.0.0': 'v1.0 schema support with new versioning strategy - Schema 1.0', '2.0.0': 'v2.0 schema support with v1.0 backwards compatibility - v0.0 support removed', '2.0.1': 'v2.0 schema support with minor non-breaking functionality upgrades' ``` -------------------------------- ### List Campaigns with Stats Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves campaigns with their metadata and statistics using the MediaPlanPy SDK. Supports filtering by various criteria and can return results as a list of dictionaries or a pandas DataFrame. Includes an option to include summary statistics. ```Python # Get all campaigns with stats campaigns = workspace.list_campaigns(include_stats=True) # Filter by date range campaigns = workspace.list_campaigns( filters={"stat_min_start_date": {"min": "2023-01-01"}} ) ``` -------------------------------- ### List Media Plans with Stats Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Retrieves media plans with their metadata and statistics using the MediaPlanPy SDK. Supports filtering by criteria such as campaign ID and can return results as a list of dictionaries or a pandas DataFrame. ```Python # Get all media plans plans = workspace.list_mediaplans() # Filter by campaign plans = workspace.list_mediaplans( filters={"campaign_id": ["camp_123", "camp_456"]} ) ``` -------------------------------- ### Export Media Plan to JSON Source: https://github.com/planmatic/mediaplanpy/blob/main/API_REFERENCE.md Exports the media plan data into JSON format, allowing for backups or integration with other systems. Supports specifying file path, name, and overwrite behavior. ```Python # Export to workspace storage json_path = media_plan.export_to_json(workspace_manager, file_name="backup.json") ``` -------------------------------- ### Audience Constructor Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Constructor signature for the Audience model, requiring essential identification and planning details. ```Python def __init__(self, id: str, name: str, objective: str, start_date: date, end_date: date, budget_total: Decimal, **kwargs) ``` -------------------------------- ### LineItem Required and v2.0 Fields Source: https://github.com/planmatic/mediaplanpy/blob/main/MediaPlanPy-Technical-Architecture-Summary.md Details the required fields and new fields introduced in v2.0 for the LineItem model, including cost currency and daypart targeting. ```Python # Required fields id: str name: str start_date: date end_date: date cost_total: Decimal # v2.0 New Fields cost_currency: Optional[str] = None # Currency for all cost fields dayparts: Optional[str] = None # Time period targeting dayparts_custom: Optional[str] = None inventory: Optional[str] = None # Inventory type specification inventory_custom: Optional[str] = None ```