repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
posthog
posthog/cdp/templates/brevo/template_brevo.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="stable", free=False, type="destination", id="template-brevo", name="Brevo", description="Update contacts in Brevo", icon_url="/static/services/brevo...
84
2,636
posthog
posthog/cdp/templates/attio/template_attio.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-attio", name="Attio", description="Create and update contacts in Attio", icon_url="/static/servi...
83
2,613
posthog
posthog/cdp/templates/attio/test_template_attio.py
.py
from posthog.cdp.templates.attio.template_attio import template as template_attio from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest def create_inputs(**kwargs): inputs = { "apiKey": "apikey12345", "email": "max@posthog.com", "personAttributes": {"name": "Max", "job_titl...
69
2,532
posthog
posthog/cdp/templates/zendesk/template_zendesk.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC # Bsed off of https://developer.zendesk.com/api-reference/ticketing/users/users/#create-or-update-user template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-zend...
110
3,601
posthog
posthog/cdp/templates/zendesk/test_template_zendesk.py
.py
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.zendesk.template_zendesk import template as template_zendesk def create_inputs(**kwargs): inputs = { "subdomain": "zendeskhelp", "admin_email": "admin@zendesk.com", "token": "Q0UlvCexisMu6Je5MH...
59
2,077
posthog
posthog/cdp/templates/activecampaign/template_activecampaign.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-activecampaign", name="ActiveCampaign", description="Creates a new contact in ActiveCampaign wheneve...
128
4,399
posthog
posthog/cdp/templates/activecampaign/test_template_activecampaign.py
.py
from posthog.cdp.templates.activecampaign.template_activecampaign import template as template_activecampaign from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest def create_inputs(**kwargs): inputs = { "accountName": "posthog", "apiKey": "API_KEY", "email": "max@posthog.co...
52
1,667
posthog
posthog/cdp/templates/loops/template_loops.py
.py
import dataclasses from copy import deepcopy from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC, HogFunctionTemplateMigrator template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="stable", free=False, type="destination", id="template-loops", name="Loops", d...
237
6,993
posthog
posthog/cdp/templates/loops/test_template_loops.py
.py
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.loops.template_loops import ( template as template_loops, template_send_event as template_loops_send_event, ) class TestTemplateLoops(BaseHogFunctionTemplateTest): template = template_loops def _inputs(se...
176
5,879
posthog
posthog/cdp/templates/userlist/template_userlist.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-userlist", name="Userlist", description="Send user, company, and event data to Userlist", icon_u...
166
5,057
posthog
posthog/cdp/templates/userlist/test_template_userlist.py
.py
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.userlist.template_userlist import template as template_userlist def create_inputs(**kwargs): inputs = { "push_key": "test_push_key", "user_identifier": "user_123", "user_email": "user@example.c...
291
10,423
posthog
posthog/cdp/templates/rudderstack/template_rudderstack.py
.py
import dataclasses from copy import deepcopy from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC, HogFunctionTemplateMigrator template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-rudderstack", name="RudderSta...
155
7,326
posthog
posthog/cdp/templates/rudderstack/test_template_rudderstack.py
.py
from posthog.test.base import BaseTest from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.rudderstack.template_rudderstack import ( TemplateRudderstackMigrator, template as template_rudderstack, ) from products.cdp.backend.models.plugin import PluginConfig class...
134
5,170
posthog
posthog/cdp/templates/mailchimp/test_template_mailchimp.py
.py
from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.mailchimp.template_mailchimp import template as template_mailchimp def create_inputs(**kwargs): inputs = { "apiKey": "abcdef", "audienceId": "a1b2c3", "dataCenterId": "us1", "email": "m...
104
3,255
posthog
posthog/cdp/templates/mailchimp/template_mailchimp.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="deprecated", free=False, type="destination", id="template-mailchimp", name="Mailchimp", description="Updates a contact in Mailchimp and subscribes new o...
143
5,140
posthog
posthog/cdp/templates/posthog/test_template_posthog.py
.py
from posthog.test.base import BaseTest from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.posthog.template_posthog import ( TemplatePostHogMigrator, template as template_posthog, ) from products.cdp.backend.models.plugin import PluginConfig class TestTemplatePos...
111
3,780
posthog
posthog/cdp/templates/posthog/template_posthog.py
.py
import dataclasses from copy import deepcopy from posthog.hogql.escape_sql import escape_hogql_string from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC, HogFunctionTemplateMigrator template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="stable", free=False, type="dest...
119
3,885
posthog
posthog/cdp/templates/aws_kinesis/template_aws_kinesis.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-aws-kinesis", name="AWS Kinesis", description="Put data to an AWS Kinesis stream", icon_url="/st...
90
2,655
posthog
posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
.py
from freezegun import freeze_time from posthog.cdp.templates.aws_kinesis.template_aws_kinesis import template as template_aws_kinesis from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest class TestTemplateAwsKinesis(BaseHogFunctionTemplateTest): template = template_aws_kinesis @freeze_time(...
45
1,927
posthog
posthog/cdp/templates/microsoft_teams/test_template_microsoft_teams.py
.py
import pytest from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.microsoft_teams.template_microsoft_teams import template as template_microsoft_teams class TestTemplateMicrosoftTeams(BaseHogFunctionTemplateTest): template = template_microsoft_teams def _inputs(s...
99
4,601
posthog
posthog/cdp/templates/microsoft_teams/template_microsoft_teams.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="stable", free=True, type="destination", id="template-microsoft-teams", name="Microsoft Teams", description="Sends a message to a Microsoft Teams channel...
74
3,386
posthog
posthog/cdp/templates/google_cloud_storage/test_template_google_cloud_storage.py
.py
from datetime import datetime from posthog.test.base import BaseTest from unittest.mock import patch from posthog.cdp.templates.google_cloud_storage.template_google_cloud_storage import TemplateGoogleCloudStorageMigrator from posthog.models import Integration from products.cdp.backend.models.plugin import Plugin, Pl...
108
4,790
posthog
posthog/cdp/templates/google_cloud_storage/template_google_cloud_storage.py
.py
import json import dataclasses from copy import deepcopy from posthog.hogql.escape_sql import escape_hogql_string from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC, HogFunctionTemplateMigrator from posthog.models.integration import GoogleCloudIntegration template: HogFunctionTemplateDC = ...
122
4,363
posthog
posthog/cdp/templates/mailgun/template_mailgun.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC # See https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Messages template_mailgun_send_email: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="te...
111
3,186
posthog
posthog/cdp/templates/mailgun/test_template_mailgun.py
.py
from typing import Optional from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.mailgun.template_mailgun import template_mailgun_send_email def create_inputs(overrides: Optional[dict] = None): inputs = { "domain_name": "DOMAIN_NAME", "api_key": "API_KE...
104
3,654
posthog
posthog/cdp/templates/_internal/template_blank.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionMappingTemplate, HogFunctionTemplateDC blank_site_destination: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=True, type="site_destination", id="template-blank-site-destination", name="New client-side destination...
163
5,784
posthog
posthog/cdp/templates/onesignal/test_template_onesignal.py
.py
import pytest from freezegun import freeze_time from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest from posthog.cdp.templates.onesignal.template_onesignal import template as template_onesignal from common.hogvm.python.utils import UncaughtHogVMException class TestTemplateOneSignal(BaseHogFunction...
65
2,353
posthog
posthog/cdp/templates/onesignal/template_onesignal.py
.py
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-onesignal", name="OneSignal", description="Send events to OneSignal", icon_url="/static/services...
101
3,207
posthog
posthog/helpers/impersonation.py
.py
from datetime import timedelta from typing import Optional from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model, load_backend from django.core.signing import TimestampSigner from django.http import HttpRequest from loginas import settings as la_settings from loginas.utils import is_imperso...
83
3,171
posthog
posthog/helpers/batch_iterators.py
.py
from abc import ABC, abstractmethod from collections.abc import Callable, Iterator from typing import Any, Generic, TypeVar T = TypeVar("T") class BatchIterator(ABC, Generic[T]): """ Abstract base class for lazily yielding batches of data with their batch index. """ def __init__(self, batch_size: in...
102
3,404
posthog
posthog/helpers/dev_api_key.py
.py
from typing import TYPE_CHECKING from django.conf import settings from posthog.models.utils import hash_key_value if TYPE_CHECKING: from posthog.models.personal_api_key import PersonalAPIKey def get_local_dev_api_key_value(key: "PersonalAPIKey") -> str | None: """Return the plaintext of the seeded local-de...
31
1,385
posthog
posthog/helpers/two_factor_session.py
.py
import json import time import datetime from dataclasses import dataclass from typing import Optional from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.http import HttpRequest from django.utils.crypto ...
511
20,579
posthog
posthog/helpers/slack_subscription_explore.py
.py
# In core ``posthog`` so the delivery paths (``ee/tasks``, ``products/exports``) can import this # without crossing tach's ``products.slack_app`` boundary. from typing import Any from posthog.helpers.slack_scopes import bot_is_ready from posthog.models.integration import Integration BOT_SETUP_DOCS_URL = "https://pos...
25
1,180
posthog
posthog/helpers/session_cache.py
.py
""" Hybrid session-cache storage to avoid race conditions when concurrent requests overwrite session data. """ from typing import Any, Optional from django.contrib.sessions.backends.base import SessionBase from django.core.cache import cache class SessionCache: """ Store temporary data in cache (keyed by se...
62
1,775
posthog
posthog/helpers/multi_property_breakdown.py
.py
import copy from typing import Any, Union funnel_with_breakdown_type = list[list[dict[str, Any]]] possible_funnel_results_types = Union[funnel_with_breakdown_type, list[dict[str, Any]], dict[str, Any]] def protect_old_clients_from_multi_property_default( request_filter: dict[str, Any], result: possible_funnel_re...
68
2,916
posthog
posthog/helpers/dev_login.py
.py
from django.conf import settings def is_dev_login_allowed() -> bool: return settings.DEBUG and settings.ALLOW_DEV_LOGIN
6
126
posthog
posthog/helpers/slack_scopes.py
.py
# In core ``posthog`` so the delivery paths (``ee/tasks``, ``products/exports``) and the # ``products.slack_app`` handlers can share the bot's required scopes without crossing tach # module boundaries. from collections.abc import Iterable import structlog from posthog.models.integration import Integration, SlackInte...
47
1,984
posthog
posthog/helpers/email_utils.py
.py
""" Email-related helpers: address normalization, ESP suppression lookups, user lookup by email, and display-name / message validation. """ import re import html import hashlib import unicodedata from collections.abc import Callable from dataclasses import dataclass from enum import Enum from functools import partial ...
611
22,851
posthog
posthog/helpers/__init__.py
.py
from .dashboard_templates import create_dashboard_from_template __all__ = ["create_dashboard_from_template"]
4
110
posthog
posthog/helpers/verified_domain_enforcement.py
.py
import re from typing import Optional from django.db.models import Q import structlog from loginas.utils import is_impersonated_session from rest_framework.exceptions import PermissionDenied from rest_framework.request import Request from posthog.helpers.two_factor_session import is_path_whitelisted from posthog.mod...
113
4,749
posthog
posthog/helpers/slack_thread_mirror.py
.py
"""Post PostHog comment content into a Slack thread. Token-agnostic: the caller supplies a ``slack_sdk.WebClient`` built from whichever workspace bot token applies (the generic Slack ``Integration``, the conversations SupportHog bot, ...). The inbound counterpart — ingesting Slack replies back as comments — is wired s...
146
5,760
posthog
posthog/helpers/full_text_search.py
.py
import re from typing import Literal, cast from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.db.models.expressions import CombinedExpression UNSAFE_CHARACTERS = r"[\'&|!<>():]" """Characters unsafe in a `tsquery`.""" def process_query(query: str) -> str | None: """ ...
57
2,098
posthog
posthog/helpers/user_devices.py
.py
from django.conf import settings from django.core.signing import BadSignature, TimestampSigner from django.http import HttpRequest, HttpResponse from posthog.models import User KNOWN_DEVICE_COOKIE = "ph_device_{user_id}" KNOWN_DEVICE_COOKIE_MAX_AGE = 2 * 365 * 24 * 60 * 60 # 2 years KNOWN_DEVICE_COOKIE_SALT = "posth...
41
1,426
posthog
posthog/helpers/sso.py
.py
from urllib.parse import urlencode from django.http import HttpRequest from django.utils.http import url_has_allowed_host_and_scheme def get_safe_next_url(next_url: str | None, request: HttpRequest) -> str | None: """Return next_url only when it's a safe same-origin/relative redirect target, else None. The ...
73
3,234
posthog
posthog/helpers/session_recording_playlist_templates.py
.py
# List of default playlists to create when a new project is created # # Each playlist is a dictionary with the following keys: # - name: The name of the playlist # - filters: The filters to apply to the playlist # - description: The description of the playlist DEFAULT_PLAYLISTS = [ { "name": "Recordings of ...
117
4,373
posthog
posthog/helpers/async_concurrency.py
.py
import random import asyncio from collections.abc import Awaitable, Callable from typing import TypeVar _T = TypeVar("_T") async def run_parallel_with_backoff( fns: list[Callable[[], Awaitable[_T]]], *, concurrency: int = 10, max_attempts: int = 5, base_delay_seconds: float = 1.0, max_delay_s...
53
2,149
posthog
posthog/helpers/dashboard_templates.py
.py
from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING, Any, Optional from django.db.models import Q import structlog from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER from posthog.models.scoping import team_scope from posthog.models.tag import Tag...
1,312
47,970
posthog
posthog/helpers/orjson_jsonfield.py
.py
"""Decode Django ``JSONField`` values with orjson instead of the stdlib ``json`` module. Postgres returns ``jsonb`` as raw text — Django registers a no-op psycopg loader (``register_default_jsonb(..., loads=lambda x: x)``) so it can apply ``JSONField.decoder`` itself. Every jsonb read therefore parses in Python via ``...
65
2,928
posthog
posthog/helpers/slack_identity.py
.py
"""Slack identity resolution shared by anything that mirrors comment threads to/from Slack. Token-agnostic: every function takes a ``slack_sdk.WebClient`` so the caller supplies the workspace's bot token (the conversations SupportHog bot, the generic Slack ``Integration``, etc.). Profile and avatar lookups are cached ...
163
6,270
posthog
posthog/helpers/encrypted_fields.py
.py
# Forked from https://github.com/jazzband/django-fernet-encrypted-fields to add a few extra things that are useful for us and # keep consistency as we also decrypt outside of django import json import base64 from django.conf import settings from django.core.checks import Error, register from django.db import models f...
261
9,693
posthog
posthog/helpers/markdown_safety.py
.py
"""Defang externally-hosted URLs in LLM/markdown content before delivery to surfaces that auto-unfurl links. Shared helper used across products. Injected/hallucinated URLs become inert code spans before reaching a surface (e.g. Slack) that would auto-unfurl or linkify them; only PostHog hosts survive. """ import re f...
60
3,005
posthog
posthog/helpers/trigram_search.py
.py
from dataclasses import dataclass from typing import Any from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity from django.db.models import Case, Exists, F, IntegerField, Q, QuerySet, Value, When from django.db.models.functions import Coalesce from opentelemetry import trace # Minimum t...
175
8,205
posthog
posthog/helpers/fuzzy_search.py
.py
"""Core fuzzy-search helpers built on rapidfuzz. Use these for typo-tolerant, separator- and order-insensitive matching of short strings (channel names, labels, entity names) against an in-memory candidate list — e.g. filtering a list fetched from a third-party API where Postgres trigram search (see ``trigram_search.p...
74
2,512
posthog
posthog/helpers/test_markdown_safety.py
.py
from posthog.test.base import BaseTest from parameterized import parameterized from posthog.helpers.markdown_safety import strip_external_links_markdown class TestStripExternalLinks(BaseTest): @parameterized.expand( [ ("no_title", "[x](https://evil.example.com)"), ("double_quote_...
45
2,188
posthog
posthog/helpers/tiktoken_encoding.py
.py
"""Lazy cached access to tiktoken encodings. Tiktoken may download and verify encoding blobs on first use. Centralizing access avoids duplicate lazy-load logic and keeps import-time failures from transient hash mismatches out of unrelated modules. In the production images the blobs are pre-warmed into ``TIKTOKEN_CACH...
33
1,173
posthog
posthog/helpers/tests/test_slack_identity.py
.py
from unittest.mock import MagicMock from django.core.cache import cache from django.test import SimpleTestCase from posthog.helpers.slack_identity import resolve_slack_user def _client_returning(name: str, email: str) -> MagicMock: client = MagicMock() client.users_info.return_value.data = { "ok": T...
36
1,445
posthog
posthog/helpers/tests/test_async_concurrency.py
.py
import asyncio from posthog.helpers.async_concurrency import run_parallel_with_backoff class _RetryableError(Exception): def __init__(self, message: str, *, retry_after_seconds: float | None = None) -> None: super().__init__(message) self.retry_after_seconds = retry_after_seconds def _is_retrya...
88
2,427
posthog
posthog/helpers/tests/test_fuzzy_search.py
.py
import pytest from posthog.helpers.fuzzy_search import DEFAULT_SCORE_CUTOFF, fuzzy_filter, fuzzy_rank, fuzzy_score class TestFuzzyScore: @pytest.mark.parametrize( "query,choice", [ ("product analytics", "product-analytics"), ("product_analytics", "product-analytics"), ...
75
3,025
posthog
posthog/helpers/tests/test_multi_property_breakdown.py
.py
from typing import Any from unittest import TestCase from posthog.helpers.multi_property_breakdown import protect_old_clients_from_multi_property_default class TestMultiPropertyBreakdown(TestCase): def test_handles_empty_inputs(self): data: dict[str, Any] = {} result: list = [] try: ...
66
2,211
posthog
posthog/helpers/tests/test_two_factor_session.py
.py
from uuid import uuid4 import pytest from unittest.mock import MagicMock, patch from django.test import SimpleTestCase from parameterized import parameterized from posthog.helpers.email_utils import ESPSuppressionReason, ESPSuppressionResult from posthog.helpers.two_factor_session import ( MAX_CODE_BASED_VERIFI...
289
13,348
posthog
posthog/helpers/tests/test_user_devices.py
.py
import uuid from posthog.test.base import BaseTest from django.test import RequestFactory from parameterized import parameterized from posthog.helpers.user_devices import ( KNOWN_DEVICE_COOKIE, build_known_device_cookie_value, has_valid_known_device_cookie, ) from posthog.models import User class Test...
72
2,885
posthog
posthog/helpers/tests/test_batch_iterator.py
.py
import pytest from posthog.helpers.batch_iterators import ArrayBatchIterator, CursorBatchIterator, FunctionBatchIterator class TestArrayBatchIterator: def test_array_batch_iterator(self): data: list[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] expected_batches = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] ...
204
8,606
posthog
posthog/helpers/tests/test_geoip.py
.py
from typing import cast import pytest from unittest.mock import Mock from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception from django.test import TestCase from posthog.geoip import geoip, get_geoip_properties australia_ip = "13.106.122.3" uk_ip = "31.28.64.3" us_ip_v6 = "2600:6c52:7a00:11c:1b6:b7b0:ea19:63...
68
2,165
posthog
posthog/helpers/tests/test_encrypted_fields.py
.py
import base64 from freezegun import freeze_time from posthog.test.base import BaseTest from unittest.mock import patch from django.test import SimpleTestCase, override_settings from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primi...
254
11,401
posthog
posthog/helpers/tests/test_email_utils.py
.py
from typing import Optional, cast from unittest.mock import MagicMock, patch from django.test import SimpleTestCase, TestCase, override_settings import requests from parameterized import parameterized from rest_framework import serializers from rest_framework.exceptions import ErrorDetail from posthog.helpers.email...
637
28,605
posthog
posthog/templatetags/posthog_filters.py
.py
from typing import Optional, Union from django import template from posthog.utils import compact_number register = template.Library() Number = Union[int, float] register.filter(compact_number) @register.filter def percentage(value: Optional[Number], decimals: int = 1) -> str: """ Returns a rounded format...
41
878
posthog
posthog/templatetags/posthog_assets.py
.py
import re from django.conf import settings from django.template import Library from posthog.utils import absolute_uri as util_absolute_uri register = Library() @register.simple_tag def absolute_uri(url: str = "") -> str: return util_absolute_uri(url) @register.simple_tag def absolute_asset_url(path: str) -> ...
57
1,506
posthog
posthog/openapi/enum_collisions.py
.py
from __future__ import annotations import re from collections import defaultdict from collections.abc import MutableMapping from typing import Any, TypedDict from drf_spectacular.plumbing import list_hash, load_enum_name_overrides from drf_spectacular.settings import spectacular_settings class EnumCollision(TypedDi...
129
5,077
GFPGAN
cog_predict.py
.py
# flake8: noqa # This file is used for deploying replicate models # running: cog predict -i img=@inputs/whole_imgs/10045.png -i version='v1.4' -i scale=2 # push: cog push r8.im/tencentarc/gfpgan # push (backup): cog push r8.im/xinntao/gfpgan import os os.system('python setup.py develop') os.system('pip install reales...
162
6,726
GFPGAN
setup.py
.py
#!/usr/bin/env python from setuptools import find_packages, setup import os import subprocess import time version_file = 'gfpgan/version.py' def readme(): with open('README.md', encoding='utf-8') as f: content = f.read() return content def get_git_hash(): def _minimal_ext_cmd(cmd): #...
108
3,148
GFPGAN
inference_gfpgan.py
.py
import argparse import cv2 import glob import numpy as np import os import torch from basicsr.utils import imwrite from gfpgan import GFPGANer def main(): """Inference demo for GFPGAN (for users). """ parser = argparse.ArgumentParser() parser.add_argument( '-i', '--input', typ...
175
7,141
GFPGAN
gfpgan/utils.py
.py
import cv2 import os import torch from basicsr.utils import img2tensor, tensor2img from basicsr.utils.download_util import load_file_from_url from facexlib.utils.face_restoration_helper import FaceRestoreHelper from torchvision.transforms.functional import normalize from gfpgan.archs.gfpgan_bilinear_arch import GFPGAN...
149
6,340
GFPGAN
gfpgan/train.py
.py
# flake8: noqa import os.path as osp from basicsr.train import train_pipeline import gfpgan.archs import gfpgan.data import gfpgan.models if __name__ == '__main__': root_path = osp.abspath(osp.join(__file__, osp.pardir, osp.pardir)) train_pipeline(root_path)
12
269
GFPGAN
gfpgan/archs/gfpganv1_clean_arch.py
.py
import math import random import torch from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F from .stylegan2_clean_arch import StyleGAN2GeneratorClean class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean): """StyleGAN2 Generator with SFT modulation (Spatial Fe...
325
13,635
GFPGAN
gfpgan/archs/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import arch modules for registry # scan all the files that end with '_arch.py' under the archs folder arch_folder = osp.dirname(osp.abspath(__file__)) arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scand...
11
496
GFPGAN
gfpgan/archs/stylegan2_bilinear_arch.py
.py
import math import random import torch from basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F class NormStyleCode(nn.Module): def forward(self, x): """Normalize the style codes. ...
614
22,309
GFPGAN
gfpgan/archs/gfpganv1_arch.py
.py
import math import random import torch from basicsr.archs.stylegan2_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2Generator) from basicsr.ops.fused_act import FusedLeakyReLU from basicsr.utils.registry import ARCH_REGISTRY from torch impo...
440
18,390
GFPGAN
gfpgan/archs/gfpgan_bilinear_arch.py
.py
import math import random import torch from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from .gfpganv1_arch import ResUpBlock from .stylegan2_bilinear_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2GeneratorBilinear) cl...
313
13,436
GFPGAN
gfpgan/archs/restoreformer_arch.py
.py
"""Modified from https://github.com/wzhouxiff/RestoreFormer """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class VectorQuantizer(nn.Module): """ see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py ___________...
659
22,900
GFPGAN
gfpgan/archs/stylegan2_clean_arch.py
.py
import math import random import torch from basicsr.archs.arch_util import default_init_weights from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F class NormStyleCode(nn.Module): def forward(self, x): """Normalize the style codes. Args: ...
369
14,317
GFPGAN
gfpgan/archs/arcface_arch.py
.py
import torch.nn as nn from basicsr.utils.registry import ARCH_REGISTRY def conv3x3(inplanes, outplanes, stride=1): """A simple wrapper for 3x3 convolution with padding. Args: inplanes (int): Channel number of inputs. outplanes (int): Channel number of outputs. stride (int): Stride in ...
246
8,075
GFPGAN
gfpgan/data/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import dataset modules for registry # scan all the files that end with '_dataset.py' under the data folder data_folder = osp.dirname(osp.abspath(__file__)) dataset_filenames = [osp.splitext(osp.basename(v))[0] for v ...
11
515
GFPGAN
gfpgan/data/ffhq_degradation_dataset.py
.py
import cv2 import math import numpy as np import os.path as osp import torch import torch.utils.data as data from basicsr.data import degradations as degradations from basicsr.data.data_util import paths_from_folder from basicsr.data.transforms import augment from basicsr.utils import FileClient, get_root_logger, imfro...
231
10,324
GFPGAN
gfpgan/models/__init__.py
.py
import importlib from basicsr.utils import scandir from os import path as osp # automatically scan and import model modules for registry # scan all the files that end with '_model.py' under the model folder model_folder = osp.dirname(osp.abspath(__file__)) model_filenames = [osp.splitext(osp.basename(v))[0] for v in s...
11
506
GFPGAN
gfpgan/models/gfpgan_model.py
.py
import math import os.path as osp import torch from basicsr.archs import build_network from basicsr.losses import build_loss from basicsr.losses.gan_loss import r1_penalty from basicsr.metrics import calculate_metric from basicsr.models.base_model import BaseModel from basicsr.utils import get_root_logger, imwrite, ten...
580
26,386
GFPGAN
tests/test_ffhq_degradation_dataset.py
.py
import pytest import yaml from gfpgan.data.ffhq_degradation_dataset import FFHQDegradationDataset def test_ffhq_degradation_dataset(): with open('tests/data/test_ffhq_degradation_dataset.yml', mode='r') as f: opt = yaml.load(f, Loader=yaml.FullLoader) dataset = FFHQDegradationDataset(opt) asser...
97
3,904
GFPGAN
tests/test_gfpgan_arch.py
.py
import torch from gfpgan.archs.gfpganv1_arch import FacialComponentDiscriminator, GFPGANv1, StyleGAN2GeneratorSFT from gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean, StyleGAN2GeneratorCSFT def test_stylegan2generatorsft(): """Test arch: StyleGAN2GeneratorSFT.""" # model init and forward (gpu) if...
204
7,887
GFPGAN
tests/test_gfpgan_model.py
.py
import tempfile import torch import yaml from basicsr.archs.stylegan2_arch import StyleGAN2Discriminator from basicsr.data.paired_image_dataset import PairedImageDataset from basicsr.losses.losses import GANLoss, L1Loss, PerceptualLoss from gfpgan.archs.arcface_arch import ResNetArcFace from gfpgan.archs.gfpganv1_arch...
133
5,707
GFPGAN
tests/test_arcface_arch.py
.py
import torch from gfpgan.archs.arcface_arch import BasicBlock, Bottleneck, ResNetArcFace def test_resnetarcface(): """Test arch: ResNetArcFace.""" # model init and forward (gpu) if torch.cuda.is_available(): net = ResNetArcFace(block='IRBlock', layers=(2, 2, 2, 2), use_se=True).cuda().eval() ...
50
1,893
GFPGAN
tests/test_stylegan2_clean_arch.py
.py
import torch from gfpgan.archs.stylegan2_clean_arch import StyleGAN2GeneratorClean def test_stylegan2generatorclean(): """Test arch: StyleGAN2GeneratorClean.""" # model init and forward (gpu) if torch.cuda.is_available(): net = StyleGAN2GeneratorClean( out_size=32, num_style_feat=512...
53
2,093
GFPGAN
tests/test_utils.py
.py
import cv2 from facexlib.utils.face_restoration_helper import FaceRestoreHelper from gfpgan.archs.gfpganv1_arch import GFPGANv1 from gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean from gfpgan.utils import GFPGANer def test_gfpganer(): # initialize with the clean model restorer = GFPGANer( mode...
44
1,549
GFPGAN
scripts/parse_landmark.py
.py
import cv2 import json import numpy as np import os import torch from basicsr.utils import FileClient, imfrombytes from collections import OrderedDict # ---------------------------- This script is used to parse facial landmarks ------------------------------------- # # Configurations save_img = False scale = 0.5 # 0....
86
3,521
GFPGAN
scripts/convert_gfpganv_to_clean.py
.py
import argparse import math import torch from gfpgan.archs.gfpganv1_clean_arch import GFPGANv1Clean def modify_checkpoint(checkpoint_bilinear, checkpoint_clean): for ori_k, ori_v in checkpoint_bilinear.items(): if 'stylegan_decoder' in ori_k: if 'style_mlp' in ori_k: # style_mlp_layers ...
165
6,961
ai-agent-book
flatten_epub_toc.py
.py
#!/usr/bin/env python3 """Clean up an EPUB table of contents: strip section numbers from labels and keep pandoc's nested chapter/section hierarchy in nav.xhtml and toc.ncx.""" import os import re import sys import tempfile import zipfile from xml.etree import ElementTree as ET XHTML = "http://www.w3.org/1999/xhtml" ...
199
7,941
ai-agent-book
chapter2/local_llm_serving/test_streaming.py
.py
#!/usr/bin/env python3 """ Test script to demonstrate streaming functionality for both vLLM and Ollama backends """ import sys import platform from main import ToolCallingAgent def test_streaming(): """Test streaming functionality with various queries""" print("="*60) print("🚀 STREAMING TEST DEMO") ...
174
5,620
ai-agent-book
chapter2/local_llm_serving/server.py
.py
""" vLLM Server Launcher for Qwen3 with Tool Calling Support """ import os import sys import subprocess import time import requests from pathlib import Path from config import VLLM_SERVER_CONFIG, VLLM_HOST, VLLM_PORT import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class V...
246
8,387
ai-agent-book
chapter2/local_llm_serving/main.py
.py
#!/usr/bin/env python3 """ Main Entry Point for Tool Calling Demo Automatically selects the best backend based on your platform: - Linux (including WSL2) with NVIDIA GPU: Uses vLLM - Native Windows, macOS, or Linux without CUDA: Uses Ollama """ import os import sys import platform import logging from typing import Opt...
660
25,512
ai-agent-book
chapter2/local_llm_serving/benchmark.py
.py
#!/usr/bin/env python3 """ 本地 LLM 服务性能基准(实验 2-1 配套) 本脚本通过 OpenAI 兼容接口(vLLM 或 Ollama 均可)测量本地部署的小模型在 「服务(serving)」层面的三个核心指标,帮助读者建立对吞吐 / 延迟 / 批处理 / KV Cache 的直觉: 1. throughput —— 单流解码吞吐(tokens/s)与首 token 延迟(TTFT) 2. kv-cache —— 前缀缓存命中 vs 未命中的 TTFT 对比 (对应实验 2-1 第 5 点:系统提示词不变时缓存命中更快, ...
488
18,408
ai-agent-book
chapter2/local_llm_serving/test_parallel_tools.py
.py
""" End-to-end test for parallel tool calling with a real LLM (Ollama). Covers: 1. Deterministic proof of parallel execution: two 2s-sleep tools must finish in ~2s (not ~4s) through each agent's tool-execution path. 2. Real-model runs of the book's "Vancouver time + weather" example through: - OllamaNativeAgent....
250
10,305
ai-agent-book
chapter2/local_llm_serving/check_compatibility.py
.py
#!/usr/bin/env python3 """ Check system compatibility for running vLLM tool calling demo """ import sys import platform import subprocess import shutil def check_system(): """Check system compatibility""" print("="*60) print("🔍 System Compatibility Check") print("="*60) # Get system info ...
154
5,262