id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
7,031
from django.db import migrations from django.db.models import Q def migrate_all_mins_to_max(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter(usage_aggregation_type="min").update( usage_aggregation_type="max" )
null
7,032
from django.db import migrations from django.db.models import Q def migrate_stateful_other_to_max(apps, schema_editor): BillableMetric = apps.get_model("metering_billing", "BillableMetric") BillableMetric.objects.filter( ~Q(usage_aggregation_type="max") & ~Q(usage_aggregation_type="latest"), metric_type="stateful", ).update(usage_aggregation_type="max")
null
7,033
from django.db import migrations def populate_description(apps, schema_editor): Plan = apps.get_model("metering_billing", "Plan") for plan in Plan.objects.all(): for plan_version in plan.versions.all(): plan.plan_description = plan_version.description plan.save() break
null
7,034
from django.db import migrations def backtest_substitutions_to_org(apps, schema_editor): BacktestSubstitution = apps.get_model("metering_billing", "BacktestSubstitution") for bts in BacktestSubstitution.objects.all(): bts.organization = bts.backtest.organization bts.save()
null
7,035
from django.db import migrations def webhooktrigger_to_org(apps, schema_editor): WebhookTrigger = apps.get_model("metering_billing", "WebhookTrigger") for wt in WebhookTrigger.objects.all(): wt.organization = wt.webhook_endpoint.organization wt.save()
null
7,036
from django.db import migrations def custom_pricing_unit_conversion_to_org(apps, schema_editor): CustomPricingUnitConversion = apps.get_model( "metering_billing", "CustomPricingUnitConversion" ) for c in CustomPricingUnitConversion.objects.all(): c.organization = c.plan_version.organization c.save()
null
7,037
from django.db import migrations def plan_component_to_org(apps, schema_editor): PlanComponent = apps.get_model("metering_billing", "PlanComponent") for pc in PlanComponent.objects.all(): pc.organization = pc.billable_metric.organization pc.save()
null
7,038
from django.db import migrations def price_tier_to_org(apps, schema_editor): PriceTier = apps.get_model("metering_billing", "PriceTier") for pt in PriceTier.objects.all(): pt.organization = pt.plan_component.billable_metric.organization pt.save()
null
7,039
from django.db import migrations def categorical_filter_to_org(apps, schema_editor): CategoricalFilter = apps.get_model("metering_billing", "CategoricalFilter") Metric = apps.get_model("metering_billing", "Metric") SubscriptionRecord = apps.get_model("metering_billing", "SubscriptionRecord") for m in Metric.objects.all(): m2m = list(m.categorical_filters.all()) m.categorical_filters.clear() for cf in m2m: cf, _ = CategoricalFilter.objects.get_or_create( organization=m.organization, property_name=cf.property_name, operator=cf.operator, comparison_value=cf.comparison_value, ) m.categorical_filters.add(cf) for sr in SubscriptionRecord.objects.all(): sr2m = list(sr.filters.all()) sr.filters.clear() for cf in sr2m: cf, _ = CategoricalFilter.objects.get_or_create( organization=sr.organization, property_name=cf.property_name, operator=cf.operator, comparison_value=cf.comparison_value, ) sr.filters.add(cf) CategoricalFilter.objects.filter(organization__isnull=True).delete()
null
7,040
from django.db import migrations def numeric_filter_to_org(apps, schema_editor): NumericFilter = apps.get_model("metering_billing", "NumericFilter") Metric = apps.get_model("metering_billing", "Metric") for m in Metric.objects.all(): m2m = list(m.numeric_filters.all()) m.numeric_filters.clear() for nf in m2m: nf, _ = NumericFilter.objects.get_or_create( organization=m.organization, property_name=nf.property_name, operator=nf.operator, comparison_value=nf.comparison_value, ) m.numeric_filters.add(nf) NumericFilter.objects.filter(organization__isnull=True).delete()
null
7,041
from django.db import migrations def invoice_line_item_to_org(apps, schema_editor): InvoiceLineItem = apps.get_model("metering_billing", "InvoiceLineItem") for ili in InvoiceLineItem.objects.all(): ili.organization = ili.invoice.organization ili.save()
null
7,042
from django.db import migrations def pricing_unit_to_org(apps, schema_editor): PricingUnit = apps.get_model("metering_billing", "PricingUnit") Organization = apps.get_model("metering_billing", "Organization") for pu in PricingUnit.objects.filter(organization__isnull=True): for org in Organization.objects.all(): PricingUnit.objects.get_or_create( organization=org, name=pu.name, code=pu.code, symbol=pu.symbol, ) pu.delete()
null
7,043
from django.db import migrations def migrate_jsonfields_to_fk(apps, schema_editor): Invoice = apps.get_model("metering_billing", "Invoice") Organization = apps.get_model("metering_billing", "Organization") Subscription = apps.get_model("metering_billing", "Subscription") Customer = apps.get_model("metering_billing", "Customer") invoice_org_dict = {} invoice_customer_dict = {} invoice_sub_dict = {} for invoice in Invoice.objects.all(): try: invoice_org = invoice.old_organization["company_name"] except Exception: invoice_org = None try: invoice_customer = invoice.old_customer["customer_id"] except Exception: invoice_customer = None try: invoice_sub = invoice.old_subscription["subscription_id"] except Exception: invoice_sub = None if invoice_org: if invoice_org in invoice_org_dict: invoice_org_object = invoice_org_dict[invoice_org] else: try: invoice_org_object = Organization.objects.get( company_name=invoice_org ) except Organization.DoesNotExist: invoice_org_object = None invoice_org_dict[invoice_org] = invoice_org_object invoice.organization = invoice_org_object if invoice_customer: if invoice_customer in invoice_customer_dict: invoice_customer_object = invoice_customer_dict[invoice_customer] else: try: invoice_customer_object = Customer.objects.get( organization=invoice_org_object, customer_id=invoice_customer ) except Exception: invoice_customer_object = None invoice_customer_dict[invoice_customer] = invoice_customer_object invoice.customer = invoice_customer_object if invoice_sub: if invoice_sub in invoice_sub_dict: invoice_sub_object = invoice_sub_dict[invoice_sub] else: try: invoice_sub_object = Subscription.objects.get( organization=invoice_org_object, subscription_id=invoice_sub ) except Exception: invoice_sub_object = None invoice_sub_dict[invoice_sub] = invoice_sub_object invoice.subscription = invoice_sub_object invoice.save()
null
7,044
from django.core.cache import cache from django.http import HttpResponseBadRequest from django.utils.translation import gettext_lazy as _ from drf_spectacular.extensions import OpenApiAuthenticationExtension from metering_billing.exceptions import ( NoMatchingAPIKey, OrganizationMismatch, UserNoOrganization, ) from metering_billing.models import APIToken from metering_billing.permissions import HasUserAPIKey from metering_billing.utils import now_utc def get_organization_from_key(key): try: api_key = APIToken.objects.get_from_key(key) except Exception: raise NoMatchingAPIKey(f"API Key starting with {key[:5]} not known") organization = api_key.organization return organization def get_user_org_or_raise_no_org(request): organization_user = request.user.organization if organization_user is None: raise UserNoOrganization( "User does not have an organization. This is unexpected behavior, please contact support." ) return organization_user class HasUserAPIKey(BaseHasAPIKey): model = APIToken def get_key(self, request): try: return request.META.get("HTTP_X_API_KEY") except KeyError: meta_dict = {k.lower(): v for k, v in request.META.items()} if "http_x_api_key".lower() in meta_dict: return meta_dict["http_x_api_key"] else: raise NoAPIKeyProvided("No API key found in request") def parse_organization(request): is_authenticated = request.user.is_authenticated api_key = HasUserAPIKey().get_key(request) if api_key is not None and is_authenticated: organization_api_token = get_organization_from_key(api_key) organization_user = get_user_org_or_raise_no_org(request) if organization_user.pk != organization_api_token.pk: raise OrganizationMismatch( "Organization for API key and session did not match" ) return organization_api_token elif api_key is not None: return get_organization_from_key(api_key) elif is_authenticated: return get_user_org_or_raise_no_org(request)
null
7,045
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook class UnifiedCRMOrganizationIntegration(models.Model): class CRMProvider(models.IntegerChoices): SALESFORCE = (1, "salesforce") organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="unified_crm_organization_links", ) crm_provider = models.IntegerField(choices=CRMProvider.choices) access_token = models.TextField() native_org_url = models.TextField() native_org_id = models.TextField() connection_id = models.TextField() created = models.DateTimeField(default=now_utc) class Meta: constraints = [ UniqueConstraint( fields=[ "organization", "crm_provider", ], name="unique_crm_provider", ), ] def get_crm_provider_from_label(label): mapping = { UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.label: UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.value, } return mapping.get(label, label) def perform_sync(self): if ( self.crm_provider == UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ): self.perform_salesforce_sync() else: raise NotImplementedError("CRM type not supported") def perform_salesforce_sync(self): from metering_billing.views.crm_views import ( sync_customers_with_salesforce, sync_invoices_with_salesforce, ) sync_customers_with_salesforce(self.organization) sync_invoices_with_salesforce(self.organization) def sync_all_crm_integrations(): from metering_billing.models import UnifiedCRMOrganizationIntegration for integration in UnifiedCRMOrganizationIntegration.objects.all(): integration.perform_sync()
null
7,046
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook class UnifiedCRMOrganizationIntegration(models.Model): class CRMProvider(models.IntegerChoices): SALESFORCE = (1, "salesforce") organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="unified_crm_organization_links", ) crm_provider = models.IntegerField(choices=CRMProvider.choices) access_token = models.TextField() native_org_url = models.TextField() native_org_id = models.TextField() connection_id = models.TextField() created = models.DateTimeField(default=now_utc) class Meta: constraints = [ UniqueConstraint( fields=[ "organization", "crm_provider", ], name="unique_crm_provider", ), ] def get_crm_provider_from_label(label): mapping = { UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.label: UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE.value, } return mapping.get(label, label) def perform_sync(self): if ( self.crm_provider == UnifiedCRMOrganizationIntegration.CRMProvider.SALESFORCE ): self.perform_salesforce_sync() else: raise NotImplementedError("CRM type not supported") def perform_salesforce_sync(self): from metering_billing.views.crm_views import ( sync_customers_with_salesforce, sync_invoices_with_salesforce, ) sync_customers_with_salesforce(self.organization) sync_invoices_with_salesforce(self.organization) def sync_single_organization_integrations( organization_integration_pk, crm_provider_values=None ): from metering_billing.models import UnifiedCRMOrganizationIntegration if crm_provider_values is None: crm_provider_values = UnifiedCRMOrganizationIntegration.CRMProvider.values for integration in UnifiedCRMOrganizationIntegration.objects.filter( organization_id=organization_integration_pk, crm_provider__in=crm_provider_values, ): integration.perform_sync()
null
7,047
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook class Organization(models.Model): def __init__(self, *args, **kwargs): def __str__(self): def save(self, *args, **kwargs): def get_tax_provider_values(self): def get_readable_tax_providers(self): def get_address(self) -> Address: def provision_webhooks(self): def provision_currencies(self): def update_subscription_filter_settings_task(org_pk, subscription_filter_keys): from metering_billing.models import Organization org = Organization.objects.get(pk=org_pk) org.subscription_filter_keys = subscription_filter_keys org.save()
null
7,048
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook def calculate_invoice_inner(): def calculate_invoice(): calculate_invoice_inner()
null
7,049
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook def refresh_alerts_inner(): def refresh_alerts(): refresh_alerts_inner()
null
7,050
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook def prune_guard_table_inner(): def prune_guard_table(): prune_guard_table_inner()
null
7,051
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook class CustomerBalanceAdjustment(models.Model): """ This model is used to store the customer balance adjustments. """ adjustment_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="+", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name="customer_balance_adjustments" ) amount = models.DecimalField(decimal_places=10, max_digits=20) pricing_unit = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="adjustments", null=True, blank=True, ) description = models.TextField(null=True, blank=True) created = models.DateTimeField(default=now_utc) effective_at = models.DateTimeField(default=now_utc) expires_at = models.DateTimeField(null=True, blank=True) parent_adjustment = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="drawdowns", ) amount_paid = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0) ) amount_paid_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="paid_adjustments", null=True, blank=True, ) status = models.CharField( max_length=20, choices=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.choices, default=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) def __str__(self): return f"{self.customer.customer_name} {self.amount} {self.created}" class Meta: ordering = ["-created"] unique_together = ("customer", "created") indexes = [ models.Index( fields=["organization", "adjustment_id"] ), # for lookup for single models.Index( fields=["organization", "customer", "pricing_unit", "-expires_at"] ), # for lookup for drawdowns models.Index(fields=["status", "expires_at"]), # for lookup for expired ] def save(self, *args, **kwargs): new = self._state.adding is True if not new: orig = CustomerBalanceAdjustment.objects.get(pk=self.pk) if ( orig.amount != self.amount or orig.pricing_unit != self.pricing_unit or orig.created != self.created or orig.effective_at != self.effective_at or orig.parent_adjustment != self.parent_adjustment ): raise NotEditable( "Cannot update any fields in a balance adjustment other than status and description" ) if self.expires_at is not None and now_utc() > self.expires_at: raise NotEditable("Cannot change the expiry date to the past") if self.amount < 0: assert ( self.parent_adjustment is not None ), "If credit is negative, parent adjustment must be provided" if self.parent_adjustment: assert ( self.parent_adjustment.amount > 0 ), "Parent adjustment must be a credit adjustment" assert ( self.parent_adjustment.customer == self.customer ), "Parent adjustment must be for the same customer" assert self.amount < 0, "Child adjustment must be a debit adjustment" assert ( self.pricing_unit == self.parent_adjustment.pricing_unit ), "Child adjustment must be in the same currency as parent adjustment" assert self.parent_adjustment.get_remaining_balance() - self.amount >= 0, ( "Child adjustment must be less than or equal to the remaining balance of " "the parent adjustment" ) if not self.organization: self.organization = self.customer.organization if self.amount_paid is None or self.amount_paid == 0: self.amount_paid_currency = None if not self.pricing_unit: raise ValidationError("Pricing unit must be provided") super(CustomerBalanceAdjustment, self).save(*args, **kwargs) def get_remaining_balance(self): try: dd_aggregate = self.total_drawdowns except AttributeError: dd_aggregate = self.drawdowns.aggregate(drawdowns=Sum("amount"))[ "drawdowns" ] drawdowns = dd_aggregate or 0 return self.amount + drawdowns def zero_out(self, reason=None): if reason == "expired": fmt = self.expires_at.strftime("%Y-%m-%d %H:%M") description = f"Expiring remaining credit at {fmt} UTC" elif reason == "voided": fmt = now_utc().strftime("%Y-%m-%d %H:%M") description = f"Voiding remaining credit at {fmt} UTC" else: description = "Zeroing out remaining credit" remaining_balance = self.get_remaining_balance() if remaining_balance > 0: CustomerBalanceAdjustment.objects.create( organization=self.customer.organization, customer=self.customer, amount=-remaining_balance, pricing_unit=self.pricing_unit, parent_adjustment=self, description=description, ) self.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE self.save() def draw_down_amount(customer, amount, pricing_unit, description=""): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .annotate( cost_basis=Cast( Coalesce(F("amount_paid") / F("amount"), 0), FloatField() ) ) .order_by( F("expires_at").asc(nulls_last=True), F("cost_basis").desc(nulls_last=True), ) .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") + F("drawn_down_amount")) ) am = amount for adj in adjs: remaining_balance = adj.remaining_balance if remaining_balance <= 0: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() continue drawdown_amount = min(am, remaining_balance) CustomerBalanceAdjustment.objects.create( organization=customer.organization, customer=customer, amount=-drawdown_amount, pricing_unit=adj.pricing_unit, parent_adjustment=adj, description=description, ) if drawdown_amount == remaining_balance: adj.status = CUSTOMER_BALANCE_ADJUSTMENT_STATUS.INACTIVE adj.save() am -= drawdown_amount if am == 0: break return am def get_pricing_unit_balance(customer, pricing_unit): now = now_utc() adjs = ( CustomerBalanceAdjustment.objects.filter( Q(expires_at__gte=now) | Q(expires_at__isnull=True), organization=customer.organization, customer=customer, pricing_unit=pricing_unit, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) .prefetch_related("drawdowns") .annotate( drawn_down_amount=Coalesce( Sum("drawdowns__amount"), 0, output_field=models.DecimalField() ) ) .annotate(remaining_balance=F("amount") - F("drawn_down_amount")) .aggregate(total_balance=Sum("remaining_balance"))["total_balance"] ) total_balance = adjs or 0 return total_balance def zero_out_expired_balance_adjustments(): from metering_billing.models import CustomerBalanceAdjustment now = now_utc() expired_balance_adjustments = CustomerBalanceAdjustment.objects.filter( expires_at__lt=now, amount__gt=0, status=CUSTOMER_BALANCE_ADJUSTMENT_STATUS.ACTIVE, ) for ba in expired_balance_adjustments: ba.zero_out(reason="expired")
null
7,052
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook PAYMENT_PROCESSOR_MAP = {} try: PAYMENT_PROCESSOR_MAP[PAYMENT_PROCESSORS.STRIPE] = StripeConnector() except Exception as e: print("ERROR: ", e) logger.error(e) sentry_sdk.capture_exception(e) pass try: PAYMENT_PROCESSOR_MAP[PAYMENT_PROCESSORS.BRAINTREE] = BraintreeConnector() except Exception as e: print("ERROR: ", e) logger.error(e) sentry_sdk.capture_exception(e) pass pass class Invoice(models.Model): class PaymentStatus(models.IntegerChoices): DRAFT = (1, _("draft")) VOIDED = (2, _("voided")) PAID = (3, _("paid")) UNPAID = (4, _("unpaid")) amount = models.DecimalField( decimal_places=10, max_digits=20, default=Decimal(0.0), validators=[MinValueValidator(0)], ) currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="invoices", null=True, blank=True, ) issue_date = models.DateTimeField(max_length=100, default=now_utc) invoice_pdf = models.URLField(max_length=300, null=True, blank=True) org_connected_to_cust_payment_provider = models.BooleanField(default=False) cust_connected_to_payment_provider = models.BooleanField(default=False) payment_status = models.PositiveSmallIntegerField( choices=PaymentStatus.choices, default=PaymentStatus.UNPAID ) due_date = models.DateTimeField(max_length=100, null=True, blank=True) invoice_number = models.CharField(max_length=13) invoice_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="invoices", null=True ) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, related_name="invoices" ) subscription_records = models.ManyToManyField( "SubscriptionRecord", related_name="invoices" ) invoice_past_due_webhook_sent = models.BooleanField(default=False) history = HistoricalRecords() __original_payment_status = None # EXTERNAL CONNECTIONS external_payment_obj_id = models.CharField(max_length=100, blank=True, null=True) external_payment_obj_type = models.CharField( choices=PAYMENT_PROCESSORS.choices, max_length=40, blank=True, null=True ) external_payment_obj_status = models.TextField(blank=True, null=True) salesforce_integration = models.OneToOneField( "UnifiedCRMInvoiceIntegration", on_delete=models.SET_NULL, null=True, blank=True ) def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__original_payment_status = self.payment_status class Meta: indexes = [ models.Index(fields=["organization", "payment_status"]), models.Index(fields=["organization", "customer"]), models.Index(fields=["organization", "invoice_number"]), models.Index(fields=["organization", "invoice_id"]), models.Index(fields=["organization", "external_payment_obj_id"]), models.Index(fields=["organization", "-issue_date"]), ] def __str__(self): return str(self.invoice_number) def save(self, *args, **kwargs): if not self.currency: self.currency = self.organization.default_currency ### Generate invoice number new = self._state.adding is True if new and self.payment_status != Invoice.PaymentStatus.DRAFT: issue_date = self.issue_date.date() issue_date_string = issue_date.strftime("%y%m%d") next_invoice_number = "000001" last_invoice = ( Invoice.objects.filter( invoice_number__startswith=issue_date_string, organization=self.organization, ) .order_by("-invoice_number") .first() ) if last_invoice: last_invoice_number = int(last_invoice.invoice_number[7:]) next_invoice_number = "{0:06d}".format(last_invoice_number + 1) self.invoice_number = issue_date_string + "-" + next_invoice_number super().save(*args, **kwargs) if ( self.__original_payment_status != self.payment_status and self.payment_status == Invoice.PaymentStatus.PAID and self.amount > 0 ): invoice_paid_webhook(self, self.organization) self.__original_payment_status = self.payment_status def update_invoice_status(): from metering_billing.models import Invoice incomplete_invoices = Invoice.objects.filter( Q(payment_status=Invoice.PaymentStatus.UNPAID), external_payment_obj_id__isnull=False, ) for incomplete_invoice in incomplete_invoices: pp = incomplete_invoice.external_payment_obj_type if pp in PAYMENT_PROCESSOR_MAP and PAYMENT_PROCESSOR_MAP[pp].working(): organization = incomplete_invoice.organization status = PAYMENT_PROCESSOR_MAP[pp].update_payment_object_status( organization, incomplete_invoice.external_payment_obj_id ) if status == Invoice.PaymentStatus.PAID: incomplete_invoice.payment_status = Invoice.PaymentStatus.PAID incomplete_invoice.save()
null
7,053
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook def import_customers_from_payment_processor_inner(payment_processor, organization_pk): from metering_billing.models import Organization organization = Organization.objects.get(pk=organization_pk) connector = PAYMENT_PROCESSOR_MAP[payment_processor] n = connector.import_customers(organization) return n def import_customers_from_payment_processor(payment_processor, organization_pk): import_customers_from_payment_processor_inner(payment_processor, organization_pk)
null
7,054
import logging from decimal import Decimal, InvalidOperation import pytz from celery import shared_task from dateutil.relativedelta import relativedelta from django.conf import settings from django.db.models import Q from metering_billing.payment_processors import PAYMENT_PROCESSOR_MAP from metering_billing.serializers.experiment_serializers import ( AllSubstitutionResultsSerializer, ) from metering_billing.serializers.serializer_utils import PlanVersionUUIDField from metering_billing.utils import ( date_as_max_dt, date_as_min_dt, dates_bwn_two_dts, make_all_dates_times_strings, make_all_datetimes_dates, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import ( CUSTOMER_BALANCE_ADJUSTMENT_STATUS, EXPERIMENT_STATUS, ) from metering_billing.webhooks import invoice_past_due_webhook def check_past_due_invoices_inner(): from metering_billing.models import Invoice now = now_utc() incomplete_invoices = Invoice.objects.filter( Q(payment_status=Invoice.PaymentStatus.UNPAID), due_date__lt=now, invoice_past_due_webhook_sent=False, ) for invoice in incomplete_invoices: invoice_past_due_webhook(invoice, invoice.organization) invoice.invoice_past_due_webhook_sent = True invoice.save() def check_past_due_invoices(): check_past_due_invoices_inner()
null
7,055
import csv import datetime import io import logging import boto3 from botocore.exceptions import ClientError from django.conf import settings from django.utils.text import slugify from metering_billing.invoice_pdf import s3_bucket_exists, s3_file_exists from metering_billing.models import Organization from metering_billing.s3_utils import get_bucket_name from metering_billing.utils import convert_to_datetime, now_utc CSV_FOLDER = "invoice_csvs" def get_key(organization, csv_folder, csv_filename): organization_id = organization.organization_id.hex key = f"{organization_id}/{csv_folder}/{csv_filename}.csv" return key def generate_invoices_csv(organization, start_date=None, end_date=None): # Format start and end dates as YYMMDD csv_filename = get_csv_filename(organization, start_date, end_date) csv_buffer = io.StringIO() writer = csv.writer(csv_buffer) invoices = organization.invoices.filter().select_related("customer") if start_date: start_time = convert_to_datetime( start_date, date_behavior="min", tz=organization.timezone ) invoices = invoices.filter(issue_date__gte=start_time) if end_date: end_time = convert_to_datetime( end_date, date_behavior="max", tz=organization.timezone ) invoices = invoices.filter(issue_date__lte=end_time) writer.writerow( [ # HEADER "externalId", "entity", # customer "terms", # unsure about this one, can work on case-by case "tranDate", # issue date "postingPeriod", # mmm yyyy format of issue date "dueDate", # due date "currency", # 3 letter iso code # LINE ITEMS "item", # lets make this the internal lotus IDs of the plans "description", "quantity", "rate", "amount", "taxCode", ] ) for invoice in invoices: externalId = invoice.invoice_number entity = invoice.customer.customer_id terms = None tranDate = invoice.issue_date.strftime("%m/%d/%Y") postingPeriod = invoice.issue_date.strftime("%B %Y") dueDate = invoice.due_date.strftime("%m/%d/%Y") if invoice.due_date else None currency = invoice.currency.code for line_item in invoice.line_items.all(): if line_item.associated_recurring_charge: item = ( "recurring_charge_" + line_item.associated_recurring_charge.recurring_charge_id.hex ) elif line_item.associated_plan_component: item = ( "usage_component_" + line_item.associated_plan_component.usage_component_id.hex ) else: item = line_item.name description = line_item.name quantity = line_item.quantity or 1 amount = line_item.amount rate = amount / quantity taxCode = None writer.writerow( [ externalId, entity, terms, tranDate, postingPeriod, dueDate, currency, item, description, quantity, rate, amount, taxCode, ] ) upload_csv(organization, csv_buffer, CSV_FOLDER, csv_filename) def get_csv_filename(organization, start_date, end_date): if start_date is not None and end_date is not None: start_date_str = datetime.datetime.strftime(start_date, "%y%m%d") end_date_str = datetime.datetime.strftime(end_date, "%y%m%d") csv_filename = f"{start_date_str}-{end_date_str}" elif start_date is not None: now = now_utc().astimezone(organization.timezone) start_date_str = datetime.datetime.strftime(start_date, "%y%m%d") now_str = datetime.datetime.strftime(now, "%y%m%d") csv_filename = f"{start_date_str}-{now_str}" elif end_date is not None: end_date_str = ( datetime.datetime.strftime(end_date, "%y%m%d") if end_date else "" ) csv_filename = f"start-{end_date_str}" else: now = now_utc().astimezone(organization.timezone) now_str = datetime.datetime.strftime(now, "%y%m%d") csv_filename = f"start-{now_str}" return csv_filename def s3_file_exists(bucket_name, key): try: s3.Object(bucket_name, key).load() except ClientError as e: if e.response["Error"]["Code"] == "404": return False else: raise else: return True class Organization(models.Model): class OrganizationType(models.IntegerChoices): PRODUCTION = (1, "Production") DEVELOPMENT = (2, "Development") EXTERNAL_DEMO = (3, "Demo") INTERNAL_DEMO = (4, "Internal Demo") team = models.ForeignKey( Team, on_delete=models.CASCADE, null=True, related_name="organizations" ) organization_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) organization_name = models.TextField(blank=False, null=False) created = models.DateField(default=now_utc) organization_type = models.PositiveSmallIntegerField( choices=OrganizationType.choices, default=OrganizationType.DEVELOPMENT ) properties = models.JSONField(default=dict, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) # BILLING RELATED FIELDS default_payment_provider = models.CharField( blank=True, choices=PAYMENT_PROCESSORS.choices, max_length=40, null=True ) stripe_integration = models.ForeignKey( "StripeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) braintree_integration = models.ForeignKey( "BraintreeOrganizationIntegration", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, related_name="+", null=True, blank=True, help_text="The primary origin address for the organization", ) default_currency = models.ForeignKey( "PricingUnit", on_delete=models.SET_NULL, related_name="organizations", null=True, blank=True, ) # TAX RELATED FIELDS tax_rate = models.DecimalField( max_digits=7, decimal_places=4, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(999.9999)), ], help_text="Tax rate as percentage. For example, 10.5 for 10.5%", null=True, ) tax_providers = TaxProviderListField(default=[TAX_PROVIDER.LOTUS]) # TIMEZONE RELATED FIELDS timezone = TimeZoneField(default="UTC", use_pytz=True) __original_timezone = None # SUBSCRIPTION RELATED FIELDS subscription_filter_keys = ArrayField( models.TextField(), default=list, blank=True, help_text="Allowed subscription filter keys", ) __original_subscription_filter_keys = None # PROVISIONING FIELDS webhooks_provisioned = models.BooleanField(default=False) currencies_provisioned = models.IntegerField(default=0) crm_settings_provisioned = models.BooleanField(default=False) # settings gen_cust_in_stripe_after_lotus = models.BooleanField(default=False) gen_cust_in_braintree_after_lotus = models.BooleanField(default=False) payment_grace_period = models.IntegerField(null=True, default=None) lotus_is_customer_source_for_salesforce = models.BooleanField(default=False) # HISTORY RELATED FIELDS history = HistoricalRecords() def __init__(self, *args, **kwargs): super(Organization, self).__init__(*args, **kwargs) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys class Meta: indexes = [ models.Index(fields=["organization_name"]), models.Index(fields=["organization_type"]), models.Index(fields=["organization_id"]), models.Index(fields=["team"]), ] def __str__(self): return self.organization_name def save(self, *args, **kwargs): from metering_billing.aggregation.billable_metrics import METRIC_HANDLER_MAP new = self._state.adding is True # self._state.adding represents whether creating new instance or updating if self.timezone != self.__original_timezone and not new: num_updated = self.customers.filter(timezone_set=False).update( timezone=self.timezone ) if num_updated > 0: customer_ids = self.customers.filter(timezone_set=False).values_list( "id", flat=True ) customer_cache_keys = [f"tz_customer_{id}" for id in customer_ids] cache.delete_many(customer_cache_keys) if self.team is None: self.team = Team.objects.create(name=self.organization_name) if self.subscription_filter_keys is None: self.subscription_filter_keys = [] self.subscription_filter_keys = sorted( list( set(self.subscription_filter_keys).union( set(self.__original_subscription_filter_keys) ) ) ) super(Organization, self).save(*args, **kwargs) if self.subscription_filter_keys != self.__original_subscription_filter_keys: for metric in self.metrics.all(): METRIC_HANDLER_MAP[metric.metric_type].create_continuous_aggregate( metric, refresh=True ) self.__original_timezone = self.timezone self.__original_subscription_filter_keys = self.subscription_filter_keys if new: self.provision_currencies() if not self.default_currency: self.default_currency = PricingUnit.objects.get( organization=self, code="USD" ) self.save() if not self.webhooks_provisioned: self.provision_webhooks() def get_tax_provider_values(self): return self.tax_providers def get_readable_tax_providers(self): choices_dict = dict(TAX_PROVIDER.choices) return [choices_dict.get(val) for val in self.tax_providers] def get_address(self) -> Address: if self.default_payment_provider == PAYMENT_PROCESSORS.STRIPE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].get_organization_address(self) elif self.default_payment_provider == PAYMENT_PROCESSORS.BRAINTREE: return PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].get_organization_address(self) else: return self.address def provision_webhooks(self): if SVIX_CONNECTOR is not None and not self.webhooks_provisioned: logger.info("provisioning webhooks") svix = SVIX_CONNECTOR svix.application.create( ApplicationIn(uid=self.organization_id.hex, name=self.organization_name) ) self.webhooks_provisioned = True self.save() def provision_currencies(self): if SUPPORTED_CURRENCIES_VERSION != self.currencies_provisioned: for name, code, symbol in SUPPORTED_CURRENCIES: PricingUnit.objects.get_or_create( organization=self, code=code, name=name, symbol=symbol, custom=False ) PricingUnit.objects.filter( ~Q(code__in=[code for _, code, _ in SUPPORTED_CURRENCIES]), custom=False, organization=self, ).delete() self.currencies_provisioned = SUPPORTED_CURRENCIES_VERSION self.save() def get_bucket_name(organization): team = organization.team team_organizations = team.organizations.all() # if the team has a prod organization, make them their own bucket if ( team_organizations.filter( organization_type__in=[ Organization.OrganizationType.PRODUCTION, Organization.OrganizationType.DEVELOPMENT, ] ).count() > 0 ): bucket_name = "prod-" + team.team_id.hex + "-" + slugify(team.name) prod = True else: bucket_name = "dev" prod = False return bucket_name, prod def get_invoices_csv_presigned_url(organization, start_date=None, end_date=None): # Format start and end dates as YYMMDD csv_filename = get_csv_filename(organization, start_date, end_date) bucket_name, prod = get_bucket_name(organization) key = get_key(organization, CSV_FOLDER, csv_filename) if not prod: team_id = organization.team.team_id.hex team = organization.team team_id = team.team_id.hex + "-" + slugify(team.name) key = f"{team_id}/{key}" # if its an external demo, or we're in debug mode, don't generate these if ( organization.organization_type == Organization.OrganizationType.EXTERNAL_DEMO or settings.DEBUG ): return {"exists": False, "url": None} exists = s3_file_exists(bucket_name=bucket_name, key=key) if not exists: generate_invoices_csv(organization, start_date, end_date) s3_resource = boto3.resource("s3") bucket = s3_resource.Bucket(bucket_name) object = bucket.Object(key) url = object.meta.client.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": bucket_name, "Key": key}, ExpiresIn=3600, ) return {"exists": True, "url": url}
null
7,056
import logging import os from decimal import Decimal from io import BytesIO import boto3 from botocore.exceptions import ClientError from django.conf import settings from django.forms.models import model_to_dict from django.utils.text import slugify from reportlab.lib.colors import Color, HexColor from reportlab.lib.pagesizes import letter from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen import canvas from reportlab.rl_config import TTFSearchPath from metering_billing.models import InvoiceLineItemAdjustment, Organization from metering_billing.s3_utils import get_bucket_name from metering_billing.serializers.serializer_utils import PlanUUIDField from metering_billing.utils import make_hashable from metering_billing.utils.enums import CHARGEABLE_ITEM_TYPE The provided code snippet includes necessary dependencies for implementing the `transform_date` function. Write a Python function `def transform_date(date)` to solve the following problem: Transforms a datetime date into the correct format Here is the function: def transform_date(date): """Transforms a datetime date into the correct format""" if type(date) == str: return date formatted_string = date.strftime("%d/%m/%Y") return formatted_string
Transforms a datetime date into the correct format
7,057
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR ) class CustomerSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = Customer fields = ( "customer_id", "email", "customer_name", "invoices", "total_amount_due", "subscriptions", "integrations", "default_currency", "payment_provider", "payment_provider_id", "has_payment_method", "address", "billing_address", "shipping_address", "tax_rate", "timezone", "tax_providers", ) extra_kwargs = { "customer_id": {"required": True, "read_only": True}, "email": {"required": True, "read_only": True}, "customer_name": {"required": True, "read_only": True, "allow_null": True}, "invoices": {"required": True, "read_only": True}, "total_amount_due": {"required": True, "read_only": True}, "subscriptions": {"required": True, "read_only": True}, "integrations": {"required": True, "read_only": True}, "default_currency": {"required": True, "read_only": True}, "payment_provider": { "required": True, "read_only": True, "allow_null": True, "allow_blank": False, }, "payment_provider_id": { "required": True, "read_only": True, "allow_null": True, "allow_blank": True, }, "has_payment_method": {"required": True, "read_only": True}, "address": {"required": True, "read_only": True}, "tax_rate": {"required": True, "read_only": True}, "timezone": {"required": True, "read_only": True}, } customer_id = serializers.CharField() email = serializers.EmailField(allow_null=True) subscriptions = serializers.SerializerMethodField() invoices = serializers.SerializerMethodField() total_amount_due = serializers.SerializerMethodField() default_currency = PricingUnitSerializer() integrations = serializers.SerializerMethodField( help_text="A dictionary containing the customer's integrations. Keys are the integration type, and the value is a dictionary containing the integration's properties, which can vary by integration.", ) payment_provider = serializers.ChoiceField( choices=PAYMENT_PROCESSORS.choices, allow_null=True, required=True, allow_blank=False, ) payment_provider_id = serializers.SerializerMethodField() has_payment_method = serializers.SerializerMethodField() address = serializers.SerializerMethodField() billing_address = serializers.SerializerMethodField() shipping_address = serializers.SerializerMethodField() timezone = TimeZoneSerializerField(use_pytz=True) tax_providers = serializers.SerializerMethodField( help_text="A list of tax providers that are enabled for this customer. The list is ordered, meaning we will succesively try to calculate taxes using each provider until we find one that works." ) def get_tax_providers( self, obj ) -> serializers.ListField( child=serializers.ChoiceField(choices=TAX_PROVIDER.labels), required=True ): return obj.get_readable_tax_providers() def get_billing_address( self, obj ) -> AddressSerializer(allow_null=True, required=True): billing_address = obj.get_billing_address() if billing_address: return AddressSerializer(billing_address).data return None def get_shipping_address( self, obj ) -> AddressSerializer(allow_null=True, required=True): shipping_address = obj.get_shipping_address() if shipping_address: return AddressSerializer(shipping_address).data return None def get_payment_provider_id( self, obj ) -> serializers.CharField(allow_null=True, required=True): d = self.get_integrations(obj) if obj.payment_provider == PAYMENT_PROCESSORS.STRIPE: stripe_dict = d.get(PAYMENT_PROCESSORS.STRIPE) if stripe_dict: return stripe_dict["stripe_id"] elif obj.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: braintree_dict = d.get(PAYMENT_PROCESSORS.BRAINTREE) if braintree_dict: return braintree_dict["paypal_id"] return None def get_address(self, obj) -> AddressSerializer(allow_null=True, required=True): billing_address = obj.get_billing_address() if billing_address: return AddressSerializer(billing_address).data return None def get_has_payment_method(self, obj) -> bool: d = self.get_integrations(obj) if obj.payment_provider == PAYMENT_PROCESSORS.STRIPE: stripe_dict = d.get(PAYMENT_PROCESSORS.STRIPE) if stripe_dict: return stripe_dict["has_payment_method"] elif obj.payment_provider == PAYMENT_PROCESSORS.BRAINTREE: braintree_dict = d.get(PAYMENT_PROCESSORS.BRAINTREE) if braintree_dict: return braintree_dict["has_payment_method"] return False def _format_stripe_integration( self, stripe_connections_dict ) -> CustomerStripeIntegrationSerializer: return { "stripe_id": stripe_connections_dict["id"], "has_payment_method": len( stripe_connections_dict.get("payment_methods", []) ) > 0, } def _format_braintree_integration( self, braintree_connections_dict ) -> CustomerBraintreeIntegrationSerializer: return { "braintree_id": braintree_connections_dict["id"], "has_payment_method": len( braintree_connections_dict.get("payment_methods", []) ) > 0, } def get_integrations(self, customer) -> CustomerIntegrationsSerializer: d = {} if customer.stripe_integration: d[PAYMENT_PROCESSORS.STRIPE] = { "stripe_id": customer.stripe_integration.stripe_customer_id, "has_payment_method": PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.STRIPE ].has_payment_method(customer), } else: d[PAYMENT_PROCESSORS.STRIPE] = None if customer.braintree_integration: d[PAYMENT_PROCESSORS.BRAINTREE] = { "braintree_id": customer.braintree_integration.braintree_customer_id, "has_payment_method": PAYMENT_PROCESSOR_MAP[ PAYMENT_PROCESSORS.BRAINTREE ].has_payment_method(customer), } else: d[PAYMENT_PROCESSORS.BRAINTREE] = None return d def get_subscriptions(self, obj) -> SubscriptionRecordSerializer(many=True): try: sr_objs = obj.active_subscription_records except AttributeError: sr_objs = ( obj.subscription_records.active() .filter(organization=obj.organization) .order_by("start_date") ) return SubscriptionRecordSerializer(sr_objs, many=True).data def get_invoices(self, obj) -> LightweightInvoiceSerializer(many=True): try: timeline = obj.active_invoices except AttributeError: timeline = obj.invoices.filter( payment_status__in=[ Invoice.PaymentStatus.PAID, Invoice.PaymentStatus.UNPAID, ], organization=obj.organization, ).order_by("-issue_date") timeline = LightweightInvoiceSerializer(timeline, many=True).data return timeline def get_total_amount_due(self, obj) -> Decimal: try: return obj.total_amount_due or Decimal(0) except AttributeError: return Decimal(0) ) ) ) class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) def customer_created_webhook(customer, customer_data=None): from api.serializers.model_serializers import CustomerSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.CUSTOMER_CREATED) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) payload = ( customer_data if customer_data else CustomerSerializer(customer).data ) payload = make_all_decimals_floats(payload) payload = make_all_dates_times_strings(payload) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.CUSTOMER_CREATED, "payload": payload, } event_id = ( slugify(str(customer.customer_id)) + "_" + slugify(str(customer.customer_name)) + "_" + "created" ) try: response = svix.message.create( customer.organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.CUSTOMER_CREATED, event_id=event_id, payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e)
null
7,058
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) ) class InvoiceSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = Invoice fields = ( "invoice_id", "invoice_number", "cost_due", "amount", "currency", "issue_date", "payment_status", "external_payment_obj_id", "external_payment_obj_type", "external_payment_obj_status", "line_items", "customer", "due_date", "start_date", "end_date", "seller", "invoice_pdf", ) extra_kwargs = { "invoice_id": {"required": True, "read_only": True}, "invoice_number": {"required": True, "read_only": True}, "cost_due": {"required": True, "read_only": True}, "amount": {"required": True, "read_only": True}, "issue_date": {"required": True, "read_only": True}, "payment_status": {"required": True, "read_only": True}, "due_date": {"required": True, "allow_null": True, "read_only": True}, "external_payment_obj_id": { "required": True, "allow_null": True, "allow_blank": False, "read_only": True, }, "external_payment_obj_type": { "required": True, "allow_null": True, "allow_blank": False, "read_only": True, }, "start_date": {"required": True, "read_only": True}, "end_date": {"required": True, "read_only": True}, "seller": {"required": True, "read_only": True}, "invoice_pdf": {"required": True, "allow_null": True, "read_only": True}, } invoice_id = InvoiceUUIDField() external_payment_obj_type = serializers.ChoiceField( choices=PAYMENT_PROCESSORS.choices, allow_null=True, required=True, allow_blank=False, ) currency = PricingUnitSerializer() customer = LightweightCustomerSerializerForInvoice() line_items = InvoiceLineItemSerializer(many=True) start_date = serializers.SerializerMethodField() end_date = serializers.SerializerMethodField() seller = SellerSerializer(source="organization") payment_status = serializers.SerializerMethodField() cost_due = serializers.DecimalField( max_digits=20, decimal_places=10, min_value=0, source="amount" ) def get_payment_status( self, obj ) -> serializers.ChoiceField(choices=Invoice.PaymentStatus.labels): return obj.get_payment_status_display() def get_start_date(self, obj) -> datetime.date: try: min_date = obj.min_date except AttributeError: min_date = obj.line_items.all().aggregate(min_date=Min("start_date"))[ "min_date" ] return ( convert_to_date(min_date) if min_date else convert_to_date(obj.issue_date) ) def get_end_date(self, obj) -> datetime.date: try: max_date = obj.max_date except AttributeError: max_date = obj.line_items.all().aggregate(max_date=Max("end_date"))[ "max_date" ] return ( convert_to_date(max_date) if max_date else convert_to_date(obj.issue_date) ) ) ) ) def invoice_paid_webhook(invoice, organization): from api.serializers.model_serializers import InvoiceSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.filter(organization=organization) .prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.INVOICE_PAID) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) invoice_data = InvoiceSerializer(invoice).data invoice_data = make_all_decimals_floats(invoice_data) invoice_data = make_all_dates_times_strings(invoice_data) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.INVOICE_PAID, "payload": invoice_data, } try: svix.message.create( organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.INVOICE_PAID, event_id=str(organization.organization_id.hex) + "_" + str(invoice_data["invoice_number"]) + "_" + "paid", payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e)
null
7,059
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class SubscriptionRecordSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = SubscriptionRecord fields = ( "subscription_id", "start_date", "end_date", "auto_renew", "is_new", "subscription_filters", "customer", "billing_plan", "fully_billed", "addons", "metadata", ) extra_kwargs = { "subscription_id": {"required": True}, "start_date": {"required": True}, "end_date": {"required": True}, "auto_renew": {"required": True}, "is_new": {"required": True}, "subscription_filters": {"required": True}, "customer": {"required": True}, "fully_billed": {"required": True}, "addons": {"required": True}, "metadata": {"required": True}, } subscription_id = SubscriptionUUIDField(source="subscription_record_id") subscription_filters = SubscriptionFilterSerializer(many=True) customer = LightweightCustomerSerializer() billing_plan = LightweightPlanVersionSerializer() addons = LightweightAddOnSubscriptionRecordSerializer( many=True, source="addon_subscription_records" ) fully_billed = serializers.SerializerMethodField() def get_fully_billed(self, obj) -> bool: return all(obj.billing_records.values_list("fully_billed", flat=True)) ) ) ) ) def subscription_created_webhook(subscription, subscription_data=None): from api.serializers.model_serializers import SubscriptionRecordSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CREATED) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) payload = ( subscription_data if subscription_data else SubscriptionRecordSerializer(subscription).data ) payload = make_all_decimals_floats(payload) payload = make_all_dates_times_strings(payload) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CREATED, "payload": payload, } event_id = ( slugify(str(subscription.customer)) + "_" + slugify(str(subscription.billing_plan)) + "_" + slugify(str(subscription.subscription_record_id.hex)[:50]) + "_" + "created" ) try: svix.message.create( subscription.organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CREATED, event_id=event_id, payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e)
null
7,060
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) ) ) ) class LightweightSubscriptionRecordSerializer(SubscriptionRecordSerializer): class Meta(SubscriptionRecordSerializer.Meta): model = SubscriptionRecord fields = tuple( set(SubscriptionRecordSerializer.Meta.fields).union(set(["plan_detail"])) ) plan_detail = LightweightPlanVersionSerializer( source="billing_plan", read_only=True ) subscription_filters = SubscriptionFilterSerializer(many=True, read_only=True) class UsageAlertSerializer(TimezoneFieldMixin, serializers.ModelSerializer): class Meta: model = UsageAlert fields = ( "usage_alert_id", "metric", "plan_version", "threshold", ) usage_alert_id = UsageAlertUUIDField(read_only=True) metric = MetricSerializer() plan_version = LightweightPlanVersionSerializer() metric = MetricSerializer() plan_version = LightweightPlanVersionSerializer() ) class UsageAlertPayload(serializers.Serializer): subscription = LightweightSubscriptionRecordSerializer() usage_alert = UsageAlertSerializer() usage = serializers.DecimalField(max_digits=20, decimal_places=10) time_triggered = serializers.DateTimeField() def usage_alert_webhook(usage_alert, alert_result, subscription_record, organization): from api.serializers.model_serializers import ( LightweightSubscriptionRecordSerializer, UsageAlertSerializer, ) from api.serializers.webhook_serializers import UsageAlertPayload from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.filter(organization=organization) .prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.USAGE_ALERT_TRIGGERED) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) alert_data = { "subscription": LightweightSubscriptionRecordSerializer( subscription_record ).data, "usage_alert": UsageAlertSerializer(usage_alert).data, "usage": alert_result.usage, "time_triggered": alert_result.last_run_timestamp, } response = { "event_type": WEBHOOK_TRIGGER_EVENTS.USAGE_ALERT_TRIGGERED, "payload": UsageAlertPayload(alert_data).data, } event_id = ( str(organization.organization_id.hex)[:50] + "_" + str(usage_alert.usage_alert_id.hex)[:50] + "_" + str(subscription_record.subscription_record_id.hex)[:50] + "_" + str(alert_result.last_run_timestamp.timestamp()) + "_" + "triggered" ) try: svix.message.create( organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.USAGE_ALERT_TRIGGERED, event_id=event_id, payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e)
null
7,061
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class SubscriptionRecordSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = SubscriptionRecord fields = ( "subscription_id", "start_date", "end_date", "auto_renew", "is_new", "subscription_filters", "customer", "billing_plan", "fully_billed", "addons", "metadata", ) extra_kwargs = { "subscription_id": {"required": True}, "start_date": {"required": True}, "end_date": {"required": True}, "auto_renew": {"required": True}, "is_new": {"required": True}, "subscription_filters": {"required": True}, "customer": {"required": True}, "fully_billed": {"required": True}, "addons": {"required": True}, "metadata": {"required": True}, } subscription_id = SubscriptionUUIDField(source="subscription_record_id") subscription_filters = SubscriptionFilterSerializer(many=True) customer = LightweightCustomerSerializer() billing_plan = LightweightPlanVersionSerializer() addons = LightweightAddOnSubscriptionRecordSerializer( many=True, source="addon_subscription_records" ) fully_billed = serializers.SerializerMethodField() def get_fully_billed(self, obj) -> bool: return all(obj.billing_records.values_list("fully_billed", flat=True)) ) ) ) ) def subscription_cancelled_webhook(subscription, subscription_data=None): from api.serializers.model_serializers import SubscriptionRecordSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.prefetch_related("triggers") .filter( triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CANCELLED ) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) payload = ( subscription_data if subscription_data else SubscriptionRecordSerializer(subscription).data ) payload = make_all_decimals_floats(payload) payload = make_all_dates_times_strings(payload) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CANCELLED, "payload": payload, } event_id = ( slugify(str(subscription.customer)) + "_" + slugify(str(subscription.billing_plan)) + "_" + slugify(str(subscription.subscription_record_id.hex)[:50]) + "_" + "cancelled" ) try: response = svix.message.create( subscription.organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_CANCELLED, event_id=event_id, payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e)
null
7,062
import logging from django.conf import settings from django.utils.text import slugify from metering_billing.utils import ( make_all_dates_times_strings, make_all_decimals_floats, now_utc, ) from metering_billing.utils.enums import WEBHOOK_TRIGGER_EVENTS from svix.api import MessageIn logger = logging.getLogger("django.server") SVIX_CONNECTOR = settings.SVIX_CONNECTOR class WebhookEndpoint(models.Model): webhook_endpoint_id = models.UUIDField( default=uuid.uuid4, editable=False, unique=True ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE, related_name="webhook_endpoints" ) name = models.TextField(blank=True, null=True) webhook_url = models.TextField() webhook_secret = models.UUIDField(default=uuid.uuid4, editable=False) objects = WebhookEndpointManager() class Meta: constraints = [ models.UniqueConstraint( fields=["organization", "webhook_url"], name="unique_webhook_url" ) ] indexes = [ models.Index( fields=["organization", "webhook_endpoint_id"] ), # for single lookup ] def save(self, *args, **kwargs): new = self._state.adding is True triggers = kwargs.pop("triggers", []) super(WebhookEndpoint, self).save(*args, **kwargs) if SVIX_CONNECTOR is not None: try: svix = SVIX_CONNECTOR if new: endpoint_create_dict = { "uid": self.webhook_endpoint_id.hex, "description": self.name, "url": self.webhook_url, "version": 1, "secret": "whsec_" + self.webhook_secret.hex, } if len(triggers) > 0: endpoint_create_dict["filter_types"] = [] for trigger in triggers: endpoint_create_dict["filter_types"].append( trigger.trigger_name ) trigger.webhook_endpoint = self trigger.save() svix_endpoint = svix.endpoint.create( self.organization.organization_id.hex, EndpointIn(**endpoint_create_dict), ) else: triggers = self.triggers.all().values_list( "trigger_name", flat=True ) svix_endpoint = svix.endpoint.get( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) svix_endpoint = svix_endpoint.__dict__ svix_update_dict = {} svix_update_dict["uid"] = self.webhook_endpoint_id.hex svix_update_dict["description"] = self.name svix_update_dict["url"] = self.webhook_url # triggers svix_triggers = svix_endpoint.get("filter_types") or [] version = svix_endpoint.get("version") if set(triggers) != set(svix_triggers): version += 1 svix_update_dict["filter_types"] = list(triggers) svix_update_dict["version"] = version svix.endpoint.update( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointUpdate(**svix_update_dict), ) current_endpoint_secret = svix.endpoint.get_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, ) if current_endpoint_secret.key != self.webhook_secret.hex: svix.endpoint.rotate_secret( self.organization.organization_id.hex, self.webhook_endpoint_id.hex, EndpointSecretRotateIn(key=self.webhook_secret.hex), ) except (HttpError, HTTPValidationError) as e: list_response_application_out = svix.application.list() dt = list_response_application_out.data lst = [x for x in dt if x.uid == self.organization.organization_id.hex] try: svix_app = lst[0] except IndexError: svix_app = None if svix_app: list_response_endpoint_out = svix.endpoint.list(svix_app.id).data else: list_response_endpoint_out = [] dictionary = { "error": e, "organization_id": self.organization.organization_id.hex, "webhook_endpoint_id": self.webhook_endpoint_id.hex, "svix_app": svix_app, "endpoint data": list_response_endpoint_out, } self.delete() raise ExternalConnectionFailure( "Webhooks service failed to connect. Did not provision webhook endpoint. Error: {}".format( dictionary ) ) class SubscriptionRecordSerializer( ConvertEmptyStringToNullMixin, TimezoneFieldMixin, serializers.ModelSerializer ): class Meta: model = SubscriptionRecord fields = ( "subscription_id", "start_date", "end_date", "auto_renew", "is_new", "subscription_filters", "customer", "billing_plan", "fully_billed", "addons", "metadata", ) extra_kwargs = { "subscription_id": {"required": True}, "start_date": {"required": True}, "end_date": {"required": True}, "auto_renew": {"required": True}, "is_new": {"required": True}, "subscription_filters": {"required": True}, "customer": {"required": True}, "fully_billed": {"required": True}, "addons": {"required": True}, "metadata": {"required": True}, } subscription_id = SubscriptionUUIDField(source="subscription_record_id") subscription_filters = SubscriptionFilterSerializer(many=True) customer = LightweightCustomerSerializer() billing_plan = LightweightPlanVersionSerializer() addons = LightweightAddOnSubscriptionRecordSerializer( many=True, source="addon_subscription_records" ) fully_billed = serializers.SerializerMethodField() def get_fully_billed(self, obj) -> bool: return all(obj.billing_records.values_list("fully_billed", flat=True)) ) ) ) ) def subscription_renewed_webhook(subscription, subscription_data=None): from api.serializers.model_serializers import SubscriptionRecordSerializer from metering_billing.models import WebhookEndpoint if SVIX_CONNECTOR is not None: endpoints = ( WebhookEndpoint.objects.prefetch_related("triggers") .filter(triggers__trigger_name=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_RENEWED) .distinct() ) if endpoints.count() > 0: svix = SVIX_CONNECTOR now = str(now_utc()) payload = ( subscription_data if subscription_data else SubscriptionRecordSerializer(subscription).data ) payload = make_all_decimals_floats(payload) payload = make_all_dates_times_strings(payload) response = { "event_type": WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_RENEWED, "payload": payload, } event_id = ( slugify(str(subscription.customer)) + "_" + slugify(str(subscription.billing_plan)) + "_" + slugify(str(subscription.subscription_record_id.hex)[:50]) + "_" + "created" ) try: response = svix.message.create( subscription.organization.organization_id.hex, MessageIn( event_type=WEBHOOK_TRIGGER_EVENTS.SUBSCRIPTION_RENEWED, event_id=event_id, payload={ "attempt": 5, "created_at": now, "properties": response, }, ), ) except Exception as e: logger.error(e) logger.error(e)
null
7,063
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def parse_nested_response(obj) -> dict: json_enc = json.dumps(obj, default=lambda o: "<not serializable>") return json.loads(json_enc)
null
7,064
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def print_prefetch_counts(queryset, prefix=""): for obj in queryset: print(f"{prefix}{obj.__class__.__name__} {obj.pk}") if hasattr(obj, "_prefetched_objects_cache"): for prefetch_key, prefetched_objs in obj._prefetched_objects_cache.items(): print(f"{prefix} - {prefetch_key}: {prefetched_objs.all().count()}") print_prefetch_counts(prefetched_objs.all(), prefix=prefix + " ")
null
7,065
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def make_hashable(obj): if isinstance(obj, MutableSequence): return tuple(make_hashable(x) for x in obj) elif isinstance(obj, set): return frozenset(make_hashable(x) for x in obj) elif isinstance(obj, MutableMapping): return OrderedDict((make_hashable(k), make_hashable(v)) for k, v in obj.items()) else: return obj
null
7,066
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def convert_to_decimal(value): if value is None: return Decimal(0) return Decimal(value).quantize(Decimal(".0000000001"), rounding=ROUND_UP)
null
7,067
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def convert_to_two_decimal_places(value): if value is None: return Decimal(0) return Decimal(value).quantize(Decimal(".01"), rounding=ROUND_HALF_UP)
null
7,068
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) class ServerError(APIException): def convert_to_date(value): if isinstance(value, datetime.datetime): return value.date() elif isinstance(value, str): return convert_to_date(parser.parse(value)) elif isinstance(value, datetime.date): return value else: raise ServerError(f"can't convert type {type(value)} into date")
null
7,069
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def make_all_decimals_floats(data): if isinstance(data, list): return [make_all_decimals_floats(x) for x in data] elif isinstance(data, (dict, collections.OrderedDict)): return { make_all_decimals_floats(key): make_all_decimals_floats(val) for key, val in data.items() } elif isinstance(data, Decimal): return float(data) else: return data
null
7,070
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def round_all_decimals_to_two_places(data): if isinstance(data, list): return [round_all_decimals_to_two_places(x) for x in data] elif isinstance(data, (dict, collections.OrderedDict)): return { round_all_decimals_to_two_places(key): round_all_decimals_to_two_places(val) for key, val in data.items() } elif isinstance(data, Decimal): return data.quantize(Decimal(".01"), rounding=ROUND_HALF_UP) else: return data
null
7,071
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def make_all_decimals_strings(data): if isinstance(data, list): return [make_all_decimals_strings(x) for x in data] elif isinstance(data, (dict, collections.OrderedDict)): return { make_all_decimals_strings(key): make_all_decimals_strings(val) for key, val in data.items() } elif isinstance(data, Decimal): return str(data) else: return data
null
7,072
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def make_all_dates_times_strings(data): if isinstance(data, list): return [make_all_dates_times_strings(x) for x in data] elif isinstance(data, (dict, collections.OrderedDict)): return { make_all_dates_times_strings(key): make_all_dates_times_strings(val) for key, val in data.items() } elif isinstance(data, (datetime.date, datetime.datetime)): return str(data) else: return data
null
7,073
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def make_all_datetimes_dates(data): if isinstance(data, list): return [make_all_datetimes_dates(x) for x in data] elif isinstance(data, (dict, collections.OrderedDict)): return { make_all_datetimes_dates(key): make_all_datetimes_dates(val) for key, val in data.items() } elif isinstance(data, datetime.datetime): return data.date() else: return data
null
7,074
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def years_bwn_twodates(start_date, end_date): years_btwn = relativedelta(end_date, start_date).years for n in range(years_btwn + 1): yield (start_date + relativedelta(years=n)).year
null
7,075
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def months_bwn_two_dates(start_date, end_date): months_btwn = ( 12 * relativedelta(end_date, start_date).years + relativedelta(end_date, start_date).months ) for n in range(months_btwn + 1): next_date = start_date + relativedelta(months=n) yield (next_date.year, next_date.month)
null
7,076
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def dates_bwn_two_dts(start_date, end_date): if isinstance(start_date, datetime.datetime): start_date = start_date.date() if isinstance(end_date, datetime.datetime): end_date = end_date.date() i = 0 while start_date + relativedelta(days=i) <= end_date: yield start_date + relativedelta(days=i) i += 1
null
7,077
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def date_as_min_dt(date, timezone): def date_as_max_dt(date, timezone): def hours_bwn_twodates(start_date, end_date): start_time = date_as_min_dt(start_date) end_time = date_as_max_dt(end_date) hours_btwn = abs(relativedelta(start_time, end_time).hours) for n in range(hours_btwn + 1): yield start_date + relativedelta(hours=n)
null
7,078
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) The provided code snippet includes necessary dependencies for implementing the `decimal_to_cents` function. Write a Python function `def decimal_to_cents(amount)` to solve the following problem: Turn a decimal into cents. Here is the function: def decimal_to_cents(amount): """ Turn a decimal into cents. """ return int(amount.quantize(Decimal(".01"), rounding=ROUND_DOWN) * Decimal(100))
Turn a decimal into cents.
7,079
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def convert_to_datetime(value, date_behavior="min", tz=pytz.UTC): def periods_bwn_twodates( granularity, start_time, end_time, truncate_to_granularity=False ): start_time = convert_to_datetime(start_time, date_behavior="min") end_time = convert_to_datetime(end_time, date_behavior="max") rd = relativedelta(start_time, end_time) if ( granularity == USAGE_CALC_GRANULARITY.TOTAL or granularity == METRIC_GRANULARITY.TOTAL or granularity is None ): yield start_time else: if granularity == METRIC_GRANULARITY.SECOND: rd = relativedelta(seconds=+1) normalize_rd = relativedelta(microsecond=0) elif granularity == METRIC_GRANULARITY.MINUTE: normalize_rd = relativedelta(second=0, microsecond=0) rd = relativedelta(minutes=+1) elif granularity == METRIC_GRANULARITY.HOUR: normalize_rd = relativedelta(minute=0, second=0, microsecond=0) rd = relativedelta(hours=+1) elif ( granularity == USAGE_CALC_GRANULARITY.DAILY or granularity == METRIC_GRANULARITY.DAY ): normalize_rd = relativedelta(hour=0, minute=0, second=0, microsecond=0) rd = relativedelta(days=+1) elif granularity == METRIC_GRANULARITY.MONTH: normalize_rd = relativedelta( day=1, hour=0, minute=0, second=0, microsecond=0 ) rd = relativedelta(months=+1) elif granularity == METRIC_GRANULARITY.QUARTER: cur_quarter = (start_time.month - 1) // 3 normalize_rd = relativedelta( month=cur_quarter * 4, day=1, hour=0, minute=0, second=0, microsecond=0 ) rd = relativedelta(months=+3) elif granularity == METRIC_GRANULARITY.YEAR: normalize_rd = relativedelta( month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ) rd = relativedelta(years=+1) k = 1 start_time = ( start_time + normalize_rd if truncate_to_granularity else start_time ) end_time = end_time + normalize_rd if truncate_to_granularity else end_time ret = start_time while ret <= end_time: yield ret ret = start_time + k * rd k += 1
null
7,080
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def now_plus_day(): return datetime.datetime.now(datetime.timezone.utc) + relativedelta(days=+1)
null
7,081
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def now_utc(): return datetime.datetime.utcnow().replace(tzinfo=pytz.utc) def now_utc_ts(): return str(now_utc().timestamp())
null
7,082
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def get_granularity_ratio(metric_granularity, proration_granularity, start_date): if ( proration_granularity == METRIC_GRANULARITY.TOTAL or proration_granularity is None ): return 1 granularity_dict = { METRIC_GRANULARITY.SECOND: { METRIC_GRANULARITY.SECOND: 1, }, METRIC_GRANULARITY.MINUTE: { METRIC_GRANULARITY.SECOND: 60, METRIC_GRANULARITY.MINUTE: 1, }, METRIC_GRANULARITY.HOUR: { METRIC_GRANULARITY.SECOND: 60 * 60, METRIC_GRANULARITY.MINUTE: 60, METRIC_GRANULARITY.HOUR: 1, }, METRIC_GRANULARITY.DAY: { METRIC_GRANULARITY.SECOND: 24 * 60 * 60, METRIC_GRANULARITY.MINUTE: 24 * 60, METRIC_GRANULARITY.HOUR: 24, METRIC_GRANULARITY.DAY: 1, }, } plus_month = start_date + relativedelta(months=1) days_in_month = (plus_month - start_date).days granularity_dict[METRIC_GRANULARITY.MONTH] = { METRIC_GRANULARITY.SECOND: days_in_month * 24 * 60 * 60, METRIC_GRANULARITY.MINUTE: days_in_month * 24 * 60, METRIC_GRANULARITY.HOUR: days_in_month * 24, METRIC_GRANULARITY.DAY: days_in_month, METRIC_GRANULARITY.MONTH: 1, } plus_quarter = start_date + relativedelta(months=3) days_in_quarter = (plus_quarter - start_date).days granularity_dict[METRIC_GRANULARITY.QUARTER] = { METRIC_GRANULARITY.SECOND: days_in_quarter * 24 * 60 * 60, METRIC_GRANULARITY.MINUTE: days_in_quarter * 24 * 60, METRIC_GRANULARITY.HOUR: days_in_quarter * 24, METRIC_GRANULARITY.DAY: days_in_quarter, METRIC_GRANULARITY.MONTH: 3, METRIC_GRANULARITY.QUARTER: 1, } plus_year = start_date + relativedelta(years=1) days_in_year = (plus_year - start_date).days granularity_dict[METRIC_GRANULARITY.YEAR] = { METRIC_GRANULARITY.SECOND: days_in_year * 24 * 60 * 60, METRIC_GRANULARITY.MINUTE: days_in_year * 24 * 60, METRIC_GRANULARITY.HOUR: days_in_year * 24, METRIC_GRANULARITY.DAY: days_in_year, METRIC_GRANULARITY.MONTH: 12, METRIC_GRANULARITY.QUARTER: 4, METRIC_GRANULARITY.YEAR: 1, } return granularity_dict[metric_granularity][proration_granularity]
null
7,083
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def date_as_max_dt(date, timezone): if isinstance(timezone, pytz.BaseTzInfo): tz = timezone elif isinstance(timezone, str): if timezone not in pytz.all_timezones: raise ValueError(f"Invalid timezone: {timezone}") tz = pytz.timezone(timezone) else: raise ValueError(f"Invalid timezone: {timezone}") return datetime.datetime.combine(date, datetime.time.max).astimezone(tz) def calculate_end_date( interval, start_date, timezone, day_anchor=None, month_anchor=None ): if interval == PLAN_DURATION.MONTHLY: end_date = date_as_max_dt( start_date + relativedelta(months=+1, days=-1), timezone ) if day_anchor: tentative_end_date = date_as_max_dt( start_date + relativedelta(day=day_anchor, days=-1), timezone ) if tentative_end_date > start_date: end_date = tentative_end_date else: end_date = date_as_max_dt( start_date + relativedelta(months=1, day=day_anchor, days=-1), timezone, ) elif interval == PLAN_DURATION.QUARTERLY: end_date = date_as_max_dt( start_date + relativedelta(months=+3, days=-1), timezone ) if day_anchor and not month_anchor: end_date = date_as_max_dt( start_date + relativedelta(months=3, day=day_anchor, days=-1), timezone ) rd = relativedelta(end_date, start_date) if rd.months >= 3 and ( rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): # went too far end_date = date_as_max_dt( start_date + relativedelta(months=2, day=day_anchor, days=-1), timezone, ) elif day_anchor and month_anchor: end_date = date_as_max_dt( start_date + relativedelta(month=month_anchor, day=day_anchor, days=-1), timezone, ) rd = relativedelta(end_date, start_date) if rd.months >= 3 and ( rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): # went too far i = 12 while rd.months >= 3: end_date = date_as_max_dt( start_date + relativedelta(months=i, day=day_anchor, days=-1), timezone, ) rd = relativedelta(end_date, start_date) i -= 1 elif end_date < start_date: old_end_date = end_date rd = relativedelta(end_date, old_end_date) i = 0 while not (rd.months % 3 == 0 and rd.months > 0): end_date = date_as_max_dt( start_date + relativedelta(months=i, day=day_anchor, days=-1), timezone, ) rd = relativedelta(end_date, old_end_date) i += 1 elif month_anchor and not day_anchor: end_date = date_as_max_dt( start_date + relativedelta(month=month_anchor, days=-1), timezone ) rd = relativedelta(end_date, start_date) if rd.months >= 3 and ( rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): while rd.months >= 3: end_date = date_as_max_dt( end_date + relativedelta(months=-3), timezone ) rd = relativedelta(end_date, start_date) elif end_date < start_date: while end_date < start_date: end_date = date_as_max_dt( end_date + relativedelta(months=3), timezone ) elif interval == PLAN_DURATION.YEARLY: end_date = date_as_max_dt( start_date + relativedelta(years=+1, days=-1), timezone ) if day_anchor and not month_anchor: end_date = date_as_max_dt( start_date + relativedelta(years=1, day=day_anchor, days=-1), timezone ) rd = relativedelta(end_date, start_date) if rd.years >= 1 and ( rd.months > 0 or rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): end_date = date_as_max_dt( start_date + relativedelta(months=11, day=day_anchor, days=-1), timezone, ) elif day_anchor and month_anchor: end_date = date_as_max_dt( start_date + relativedelta(years=1, month=month_anchor, day=day_anchor, days=-1), timezone, ) rd = relativedelta(end_date, start_date) if rd.years >= 1 and ( rd.months > 0 or rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): end_date = end_date + relativedelta(years=-1) elif month_anchor and not day_anchor: end_date = date_as_max_dt( start_date + relativedelta(years=1, month=month_anchor, days=-1), timezone, ) rd = relativedelta(end_date, start_date) if rd.years >= 1 and ( rd.months > 0 or rd.days > 0 or rd.hours > 0 or rd.minutes > 0 or rd.seconds > 0 or rd.microseconds > 0 ): end_date = end_date + relativedelta(years=-1) return end_date
null
7,084
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def event_uuid(): return "event_" + str(uuid.uuid4().hex)
null
7,085
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def product_uuid(): return "prod_" + str(uuid.uuid4().hex)
null
7,086
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def customer_uuid(): return "cust_" + str(uuid.uuid4().hex)
null
7,087
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def metric_uuid(): return "metric_" + str(uuid.uuid4().hex)
null
7,088
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def plan_version_uuid(): return "plnvrs_" + str(uuid.uuid4().hex)
null
7,089
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def plan_uuid(): return "plan_" + str(uuid.uuid4().hex)
null
7,090
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def subscription_uuid(): return "subs_" + str(uuid.uuid4().hex)
null
7,091
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def subscription_record_uuid(): return "subsrec_" + str(uuid.uuid4().hex)
null
7,092
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def backtest_uuid(): return "btst_" + str(uuid.uuid4().hex)
null
7,093
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def invoice_uuid(): return "inv_" + str(uuid.uuid4().hex)
null
7,094
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def organization_uuid(): return "org_" + str(uuid.uuid4().hex)
null
7,095
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def webhook_secret_uuid(): return "whsec_" + str(uuid.uuid4().hex)
null
7,096
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def webhook_endpoint_uuid(): return "whend_" + str(uuid.uuid4().hex)
null
7,097
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def customer_balance_adjustment_uuid(): return "custbaladj_" + str(uuid.uuid4().hex)
null
7,098
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def addon_uuid(): return "addon_" + str(uuid.uuid4().hex)
null
7,099
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def addon_version_uuid(): return "addon_vrs_" + str(uuid.uuid4().hex)
null
7,100
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def addon_sr_uuid(): return "addon_subscription_" + str(uuid.uuid4().hex)
null
7,101
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def usage_alert_uuid(): return "usgalert_" + str(uuid.uuid4().hex)
null
7,102
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def random_uuid(): return str(uuid.uuid4().hex)
null
7,103
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) The provided code snippet includes necessary dependencies for implementing the `namedtuplefetchall` function. Write a Python function `def namedtuplefetchall(cursor)` to solve the following problem: Return all rows from a cursor as a namedtuple Here is the function: def namedtuplefetchall(cursor): "Return all rows from a cursor as a namedtuple" desc = cursor.description nt_result = namedtuple("Result", [col[0] for col in desc]) return [nt_result(*row) for row in cursor.fetchall()]
Return all rows from a cursor as a namedtuple
7,104
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def customer_id_uuidv5(customer_id): from django.conf import settings return uuid.uuid5(settings.CUSTOMER_ID_NAMESPACE, customer_id)
null
7,105
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def event_name_uuidv5(event_name): from django.conf import settings return uuid.uuid5(settings.EVENT_NAME_NAMESPACE, event_name)
null
7,106
import collections import datetime import json import uuid from collections import OrderedDict, namedtuple from collections.abc import MutableMapping, MutableSequence from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal import pytz from dateutil import parser from dateutil.relativedelta import relativedelta from django.db.models import Field, Model from metering_billing.exceptions.exceptions import ServerError from metering_billing.utils.enums import ( METRIC_GRANULARITY, PLAN_DURATION, USAGE_CALC_GRANULARITY, ) def idempotency_id_uuidv5(idempotency_id): from django.conf import settings return uuid.uuid5(settings.IDEMPOTENCY_ID_NAMESPACE, idempotency_id)
null
7,107
import math def get_alpha(rate=30, cutoff=1): tau = 1 / (2 * math.pi * cutoff) te = 1 / rate return 1 / (1 + tau / te)
null
7,108
from torch import nn def conv(in_channels, out_channels, kernel_size=3, padding=1, bn=True, dilation=1, stride=1, relu=True, bias=True): modules = [nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias)] if bn: modules.append(nn.BatchNorm2d(out_channels)) if relu: modules.append(nn.ReLU(inplace=True)) return nn.Sequential(*modules)
null
7,109
from torch import nn def conv_dw(in_channels, out_channels, kernel_size=3, padding=1, stride=1, dilation=1): return nn.Sequential( nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation=dilation, groups=in_channels, bias=False), nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), )
null
7,110
from torch import nn def conv_dw_no_bn(in_channels, out_channels, kernel_size=3, padding=1, stride=1, dilation=1): return nn.Sequential( nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation=dilation, groups=in_channels, bias=False), nn.ELU(inplace=True), nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False), nn.ELU(inplace=True), )
null
7,111
import argparse import cv2 import os import torch from torch.nn import DataParallel import torch.optim as optim from torch.utils.data import DataLoader from torchvision import transforms from datasets.coco import CocoTrainDataset from datasets.transformations import ConvertKeypoints, Scale, Rotate, CropPad, Flip from modules.get_parameters import get_parameters_conv, get_parameters_bn, get_parameters_conv_depthwise from models.with_mobilenet import PoseEstimationWithMobileNet from modules.loss import l2_loss from modules.load_state import load_state, load_from_mobilenet from val import evaluate class CocoTrainDataset(Dataset): def __init__(self, labels, images_folder, stride, sigma, paf_thickness, transform=None): super().__init__() self._images_folder = images_folder self._stride = stride self._sigma = sigma self._paf_thickness = paf_thickness self._transform = transform with open(labels, 'rb') as f: self._labels = pickle.load(f) def __getitem__(self, idx): label = copy.deepcopy(self._labels[idx]) # label modified in transform image = cv2.imread(os.path.join(self._images_folder, label['img_paths']), cv2.IMREAD_COLOR) mask = np.ones(shape=(label['img_height'], label['img_width']), dtype=np.float32) mask = get_mask(label['segmentations'], mask) sample = { 'label': label, 'image': image, 'mask': mask } if self._transform: sample = self._transform(sample) mask = cv2.resize(sample['mask'], dsize=None, fx=1/self._stride, fy=1/self._stride, interpolation=cv2.INTER_AREA) keypoint_maps = self._generate_keypoint_maps(sample) sample['keypoint_maps'] = keypoint_maps keypoint_mask = np.zeros(shape=keypoint_maps.shape, dtype=np.float32) for idx in range(keypoint_mask.shape[0]): keypoint_mask[idx] = mask sample['keypoint_mask'] = keypoint_mask paf_maps = self._generate_paf_maps(sample) sample['paf_maps'] = paf_maps paf_mask = np.zeros(shape=paf_maps.shape, dtype=np.float32) for idx in range(paf_mask.shape[0]): paf_mask[idx] = mask sample['paf_mask'] = paf_mask image = sample['image'].astype(np.float32) image = (image - 128) / 256 sample['image'] = image.transpose((2, 0, 1)) del sample['label'] return sample def __len__(self): return len(self._labels) def _generate_keypoint_maps(self, sample): n_keypoints = 18 n_rows, n_cols, _ = sample['image'].shape keypoint_maps = np.zeros(shape=(n_keypoints + 1, n_rows // self._stride, n_cols // self._stride), dtype=np.float32) # +1 for bg label = sample['label'] for keypoint_idx in range(n_keypoints): keypoint = label['keypoints'][keypoint_idx] if keypoint[2] <= 1: self._add_gaussian(keypoint_maps[keypoint_idx], keypoint[0], keypoint[1], self._stride, self._sigma) for another_annotation in label['processed_other_annotations']: keypoint = another_annotation['keypoints'][keypoint_idx] if keypoint[2] <= 1: self._add_gaussian(keypoint_maps[keypoint_idx], keypoint[0], keypoint[1], self._stride, self._sigma) keypoint_maps[-1] = 1 - keypoint_maps.max(axis=0) return keypoint_maps def _add_gaussian(self, keypoint_map, x, y, stride, sigma): n_sigma = 4 tl = [int(x - n_sigma * sigma), int(y - n_sigma * sigma)] tl[0] = max(tl[0], 0) tl[1] = max(tl[1], 0) br = [int(x + n_sigma * sigma), int(y + n_sigma * sigma)] map_h, map_w = keypoint_map.shape br[0] = min(br[0], map_w * stride) br[1] = min(br[1], map_h * stride) shift = stride / 2 - 0.5 for map_y in range(tl[1] // stride, br[1] // stride): for map_x in range(tl[0] // stride, br[0] // stride): d2 = (map_x * stride + shift - x) * (map_x * stride + shift - x) + \ (map_y * stride + shift - y) * (map_y * stride + shift - y) exponent = d2 / 2 / sigma / sigma if exponent > 4.6052: # threshold, ln(100), ~0.01 continue keypoint_map[map_y, map_x] += math.exp(-exponent) if keypoint_map[map_y, map_x] > 1: keypoint_map[map_y, map_x] = 1 def _generate_paf_maps(self, sample): n_pafs = len(BODY_PARTS_KPT_IDS) n_rows, n_cols, _ = sample['image'].shape paf_maps = np.zeros(shape=(n_pafs * 2, n_rows // self._stride, n_cols // self._stride), dtype=np.float32) label = sample['label'] for paf_idx in range(n_pafs): keypoint_a = label['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][0]] keypoint_b = label['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][1]] if keypoint_a[2] <= 1 and keypoint_b[2] <= 1: self._set_paf(paf_maps[paf_idx * 2:paf_idx * 2 + 2], keypoint_a[0], keypoint_a[1], keypoint_b[0], keypoint_b[1], self._stride, self._paf_thickness) for another_annotation in label['processed_other_annotations']: keypoint_a = another_annotation['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][0]] keypoint_b = another_annotation['keypoints'][BODY_PARTS_KPT_IDS[paf_idx][1]] if keypoint_a[2] <= 1 and keypoint_b[2] <= 1: self._set_paf(paf_maps[paf_idx * 2:paf_idx * 2 + 2], keypoint_a[0], keypoint_a[1], keypoint_b[0], keypoint_b[1], self._stride, self._paf_thickness) return paf_maps def _set_paf(self, paf_map, x_a, y_a, x_b, y_b, stride, thickness): x_a /= stride y_a /= stride x_b /= stride y_b /= stride x_ba = x_b - x_a y_ba = y_b - y_a _, h_map, w_map = paf_map.shape x_min = int(max(min(x_a, x_b) - thickness, 0)) x_max = int(min(max(x_a, x_b) + thickness, w_map)) y_min = int(max(min(y_a, y_b) - thickness, 0)) y_max = int(min(max(y_a, y_b) + thickness, h_map)) norm_ba = (x_ba * x_ba + y_ba * y_ba) ** 0.5 if norm_ba < 1e-7: # Same points, no paf return x_ba /= norm_ba y_ba /= norm_ba for y in range(y_min, y_max): for x in range(x_min, x_max): x_ca = x - x_a y_ca = y - y_a d = math.fabs(x_ca * y_ba - y_ca * x_ba) if d <= thickness: paf_map[0, y, x] = x_ba paf_map[1, y, x] = y_ba class ConvertKeypoints: def __call__(self, sample): label = sample['label'] h, w, _ = sample['image'].shape keypoints = label['keypoints'] for keypoint in keypoints: # keypoint[2] == 0: occluded, == 1: visible, == 2: not in image if keypoint[0] == keypoint[1] == 0: keypoint[2] = 2 if (keypoint[0] < 0 or keypoint[0] >= w or keypoint[1] < 0 or keypoint[1] >= h): keypoint[2] = 2 for other_label in label['processed_other_annotations']: keypoints = other_label['keypoints'] for keypoint in keypoints: if keypoint[0] == keypoint[1] == 0: keypoint[2] = 2 if (keypoint[0] < 0 or keypoint[0] >= w or keypoint[1] < 0 or keypoint[1] >= h): keypoint[2] = 2 label['keypoints'] = self._convert(label['keypoints'], w, h) for other_label in label['processed_other_annotations']: other_label['keypoints'] = self._convert(other_label['keypoints'], w, h) return sample def _convert(self, keypoints, w, h): # Nose, Neck, R hand, L hand, R leg, L leg, Eyes, Ears reorder_map = [1, 7, 9, 11, 6, 8, 10, 13, 15, 17, 12, 14, 16, 3, 2, 5, 4] converted_keypoints = list(keypoints[i - 1] for i in reorder_map) converted_keypoints.insert(1, [(keypoints[5][0] + keypoints[6][0]) / 2, (keypoints[5][1] + keypoints[6][1]) / 2, 0]) # Add neck as a mean of shoulders if keypoints[5][2] == 2 or keypoints[6][2] == 2: converted_keypoints[1][2] = 2 elif keypoints[5][2] == 1 and keypoints[6][2] == 1: converted_keypoints[1][2] = 1 if (converted_keypoints[1][0] < 0 or converted_keypoints[1][0] >= w or converted_keypoints[1][1] < 0 or converted_keypoints[1][1] >= h): converted_keypoints[1][2] = 2 return converted_keypoints class Scale: def __init__(self, prob=1, min_scale=0.5, max_scale=1.1, target_dist=0.6): self._prob = prob self._min_scale = min_scale self._max_scale = max_scale self._target_dist = target_dist def __call__(self, sample): prob = random.random() scale_multiplier = 1 if prob <= self._prob: prob = random.random() scale_multiplier = (self._max_scale - self._min_scale) * prob + self._min_scale label = sample['label'] scale_abs = self._target_dist / label['scale_provided'] scale = scale_abs * scale_multiplier sample['image'] = cv2.resize(sample['image'], dsize=(0, 0), fx=scale, fy=scale) label['img_height'], label['img_width'], _ = sample['image'].shape sample['mask'] = cv2.resize(sample['mask'], dsize=(0, 0), fx=scale, fy=scale) label['objpos'][0] *= scale label['objpos'][1] *= scale for keypoint in sample['label']['keypoints']: keypoint[0] *= scale keypoint[1] *= scale for other_annotation in sample['label']['processed_other_annotations']: other_annotation['objpos'][0] *= scale other_annotation['objpos'][1] *= scale for keypoint in other_annotation['keypoints']: keypoint[0] *= scale keypoint[1] *= scale return sample class Rotate: def __init__(self, pad, max_rotate_degree=40): self._pad = pad self._max_rotate_degree = max_rotate_degree def __call__(self, sample): prob = random.random() degree = (prob - 0.5) * 2 * self._max_rotate_degree h, w, _ = sample['image'].shape img_center = (w / 2, h / 2) R = cv2.getRotationMatrix2D(img_center, degree, 1) abs_cos = abs(R[0, 0]) abs_sin = abs(R[0, 1]) bound_w = int(h * abs_sin + w * abs_cos) bound_h = int(h * abs_cos + w * abs_sin) dsize = (bound_w, bound_h) R[0, 2] += dsize[0] / 2 - img_center[0] R[1, 2] += dsize[1] / 2 - img_center[1] sample['image'] = cv2.warpAffine(sample['image'], R, dsize=dsize, borderMode=cv2.BORDER_CONSTANT, borderValue=self._pad) sample['label']['img_height'], sample['label']['img_width'], _ = sample['image'].shape sample['mask'] = cv2.warpAffine(sample['mask'], R, dsize=dsize, borderMode=cv2.BORDER_CONSTANT, borderValue=(1, 1, 1)) # border is ok label = sample['label'] label['objpos'] = self._rotate(label['objpos'], R) for keypoint in label['keypoints']: point = [keypoint[0], keypoint[1]] point = self._rotate(point, R) keypoint[0], keypoint[1] = point[0], point[1] for other_annotation in label['processed_other_annotations']: for keypoint in other_annotation['keypoints']: point = [keypoint[0], keypoint[1]] point = self._rotate(point, R) keypoint[0], keypoint[1] = point[0], point[1] return sample def _rotate(self, point, R): return [R[0, 0] * point[0] + R[0, 1] * point[1] + R[0, 2], R[1, 0] * point[0] + R[1, 1] * point[1] + R[1, 2]] class CropPad: def __init__(self, pad, center_perterb_max=40, crop_x=368, crop_y=368): self._pad = pad self._center_perterb_max = center_perterb_max self._crop_x = crop_x self._crop_y = crop_y def __call__(self, sample): prob_x = random.random() prob_y = random.random() offset_x = int((prob_x - 0.5) * 2 * self._center_perterb_max) offset_y = int((prob_y - 0.5) * 2 * self._center_perterb_max) label = sample['label'] shifted_center = (label['objpos'][0] + offset_x, label['objpos'][1] + offset_y) offset_left = -int(shifted_center[0] - self._crop_x / 2) offset_up = -int(shifted_center[1] - self._crop_y / 2) cropped_image = np.empty(shape=(self._crop_y, self._crop_x, 3), dtype=np.uint8) for i in range(3): cropped_image[:, :, i].fill(self._pad[i]) cropped_mask = np.empty(shape=(self._crop_y, self._crop_x), dtype=np.uint8) cropped_mask.fill(1) image_x_start = int(shifted_center[0] - self._crop_x / 2) image_y_start = int(shifted_center[1] - self._crop_y / 2) image_x_finish = image_x_start + self._crop_x image_y_finish = image_y_start + self._crop_y crop_x_start = 0 crop_y_start = 0 crop_x_finish = self._crop_x crop_y_finish = self._crop_y w, h = label['img_width'], label['img_height'] should_crop = True if image_x_start < 0: # Adjust crop area crop_x_start -= image_x_start image_x_start = 0 if image_x_start >= w: should_crop = False if image_y_start < 0: crop_y_start -= image_y_start image_y_start = 0 if image_y_start >= h: should_crop = False if image_x_finish > w: diff = image_x_finish - w image_x_finish -= diff crop_x_finish -= diff if image_x_finish < 0: should_crop = False if image_y_finish > h: diff = image_y_finish - h image_y_finish -= diff crop_y_finish -= diff if image_y_finish < 0: should_crop = False if should_crop: cropped_image[crop_y_start:crop_y_finish, crop_x_start:crop_x_finish, :] =\ sample['image'][image_y_start:image_y_finish, image_x_start:image_x_finish, :] cropped_mask[crop_y_start:crop_y_finish, crop_x_start:crop_x_finish] =\ sample['mask'][image_y_start:image_y_finish, image_x_start:image_x_finish] sample['image'] = cropped_image sample['mask'] = cropped_mask label['img_width'] = self._crop_x label['img_height'] = self._crop_y label['objpos'][0] += offset_left label['objpos'][1] += offset_up for keypoint in label['keypoints']: keypoint[0] += offset_left keypoint[1] += offset_up for other_annotation in label['processed_other_annotations']: for keypoint in other_annotation['keypoints']: keypoint[0] += offset_left keypoint[1] += offset_up return sample def _inside(self, point, width, height): if point[0] < 0 or point[1] < 0: return False if point[0] >= width or point[1] >= height: return False return True class Flip: def __init__(self, prob=0.5): self._prob = prob def __call__(self, sample): prob = random.random() do_flip = prob <= self._prob if not do_flip: return sample sample['image'] = cv2.flip(sample['image'], 1) sample['mask'] = cv2.flip(sample['mask'], 1) label = sample['label'] w, h = label['img_width'], label['img_height'] label['objpos'][0] = w - 1 - label['objpos'][0] for keypoint in label['keypoints']: keypoint[0] = w - 1 - keypoint[0] label['keypoints'] = self._swap_left_right(label['keypoints']) for other_annotation in label['processed_other_annotations']: other_annotation['objpos'][0] = w - 1 - other_annotation['objpos'][0] for keypoint in other_annotation['keypoints']: keypoint[0] = w - 1 - keypoint[0] other_annotation['keypoints'] = self._swap_left_right(other_annotation['keypoints']) return sample def _swap_left_right(self, keypoints): right = [2, 3, 4, 8, 9, 10, 14, 16] left = [5, 6, 7, 11, 12, 13, 15, 17] for r, l in zip(right, left): keypoints[r], keypoints[l] = keypoints[l], keypoints[r] return keypoints def get_parameters_conv(model, name): return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d) and m.groups == 1 and p == name) def get_parameters_conv_depthwise(model, name): return get_parameters(model, lambda m, p: isinstance(m, nn.Conv2d) and m.groups == m.in_channels and m.in_channels == m.out_channels and p == name) def get_parameters_bn(model, name): return get_parameters(model, lambda m, p: isinstance(m, nn.BatchNorm2d) and p == name) class PoseEstimationWithMobileNet(nn.Module): def __init__(self, num_refinement_stages=1, num_channels=128, num_heatmaps=19, num_pafs=38): super().__init__() self.model = nn.Sequential( conv( 3, 32, stride=2, bias=False), conv_dw( 32, 64), conv_dw( 64, 128, stride=2), conv_dw(128, 128), conv_dw(128, 256, stride=2), conv_dw(256, 256), conv_dw(256, 512), # conv4_2 conv_dw(512, 512, dilation=2, padding=2), conv_dw(512, 512), conv_dw(512, 512), conv_dw(512, 512), conv_dw(512, 512) # conv5_5 ) self.cpm = Cpm(512, num_channels) self.initial_stage = InitialStage(num_channels, num_heatmaps, num_pafs) self.refinement_stages = nn.ModuleList() for idx in range(num_refinement_stages): self.refinement_stages.append(RefinementStage(num_channels + num_heatmaps + num_pafs, num_channels, num_heatmaps, num_pafs)) def forward(self, x): backbone_features = self.model(x) backbone_features = self.cpm(backbone_features) stages_output = self.initial_stage(backbone_features) for refinement_stage in self.refinement_stages: stages_output.extend( refinement_stage(torch.cat([backbone_features, stages_output[-2], stages_output[-1]], dim=1))) return stages_output def l2_loss(input, target, mask, batch_size): loss = (input - target) * mask loss = (loss * loss) / 2 / batch_size return loss.sum() def load_state(net, checkpoint): source_state = checkpoint['state_dict'] target_state = net.state_dict() new_target_state = collections.OrderedDict() for target_key, target_value in target_state.items(): if target_key in source_state and source_state[target_key].size() == target_state[target_key].size(): new_target_state[target_key] = source_state[target_key] else: new_target_state[target_key] = target_state[target_key] print('[WARNING] Not found pre-trained parameters for {}'.format(target_key)) net.load_state_dict(new_target_state) def load_from_mobilenet(net, checkpoint): source_state = checkpoint['state_dict'] target_state = net.state_dict() new_target_state = collections.OrderedDict() for target_key, target_value in target_state.items(): k = target_key if k.find('model') != -1: k = k.replace('model', 'module.model') if k in source_state and source_state[k].size() == target_state[target_key].size(): new_target_state[target_key] = source_state[k] else: new_target_state[target_key] = target_state[target_key] print('[WARNING] Not found pre-trained parameters for {}'.format(target_key)) net.load_state_dict(new_target_state) def evaluate(labels, output_name, images_folder, net, multiscale=False, visualize=False): net = net.cuda().eval() base_height = 368 scales = [1] if multiscale: scales = [0.5, 1.0, 1.5, 2.0] stride = 8 dataset = CocoValDataset(labels, images_folder) coco_result = [] for sample in dataset: file_name = sample['file_name'] img = sample['img'] avg_heatmaps, avg_pafs = infer(net, img, scales, base_height, stride) total_keypoints_num = 0 all_keypoints_by_type = [] for kpt_idx in range(18): # 19th for bg total_keypoints_num += extract_keypoints(avg_heatmaps[:, :, kpt_idx], all_keypoints_by_type, total_keypoints_num) pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, avg_pafs) coco_keypoints, scores = convert_to_coco_format(pose_entries, all_keypoints) image_id = int(file_name[0:file_name.rfind('.')]) for idx in range(len(coco_keypoints)): coco_result.append({ 'image_id': image_id, 'category_id': 1, # person 'keypoints': coco_keypoints[idx], 'score': scores[idx] }) if visualize: for keypoints in coco_keypoints: for idx in range(len(keypoints) // 3): cv2.circle(img, (int(keypoints[idx * 3]), int(keypoints[idx * 3 + 1])), 3, (255, 0, 255), -1) cv2.imshow('keypoints', img) key = cv2.waitKey() if key == 27: # esc return with open(output_name, 'w') as f: json.dump(coco_result, f, indent=4) run_coco_eval(labels, output_name) def train(prepared_train_labels, train_images_folder, num_refinement_stages, base_lr, batch_size, batches_per_iter, num_workers, checkpoint_path, weights_only, from_mobilenet, checkpoints_folder, log_after, val_labels, val_images_folder, val_output_name, checkpoint_after, val_after): net = PoseEstimationWithMobileNet(num_refinement_stages) stride = 8 sigma = 7 path_thickness = 1 dataset = CocoTrainDataset(prepared_train_labels, train_images_folder, stride, sigma, path_thickness, transform=transforms.Compose([ ConvertKeypoints(), Scale(), Rotate(pad=(128, 128, 128)), CropPad(pad=(128, 128, 128)), Flip()])) train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers) optimizer = optim.Adam([ {'params': get_parameters_conv(net.model, 'weight')}, {'params': get_parameters_conv_depthwise(net.model, 'weight'), 'weight_decay': 0}, {'params': get_parameters_bn(net.model, 'weight'), 'weight_decay': 0}, {'params': get_parameters_bn(net.model, 'bias'), 'lr': base_lr * 2, 'weight_decay': 0}, {'params': get_parameters_conv(net.cpm, 'weight'), 'lr': base_lr}, {'params': get_parameters_conv(net.cpm, 'bias'), 'lr': base_lr * 2, 'weight_decay': 0}, {'params': get_parameters_conv_depthwise(net.cpm, 'weight'), 'weight_decay': 0}, {'params': get_parameters_conv(net.initial_stage, 'weight'), 'lr': base_lr}, {'params': get_parameters_conv(net.initial_stage, 'bias'), 'lr': base_lr * 2, 'weight_decay': 0}, {'params': get_parameters_conv(net.refinement_stages, 'weight'), 'lr': base_lr * 4}, {'params': get_parameters_conv(net.refinement_stages, 'bias'), 'lr': base_lr * 8, 'weight_decay': 0}, {'params': get_parameters_bn(net.refinement_stages, 'weight'), 'weight_decay': 0}, {'params': get_parameters_bn(net.refinement_stages, 'bias'), 'lr': base_lr * 2, 'weight_decay': 0}, ], lr=base_lr, weight_decay=5e-4) num_iter = 0 current_epoch = 0 drop_after_epoch = [100, 200, 260] scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=drop_after_epoch, gamma=0.333) if checkpoint_path: checkpoint = torch.load(checkpoint_path) if from_mobilenet: load_from_mobilenet(net, checkpoint) else: load_state(net, checkpoint) if not weights_only: optimizer.load_state_dict(checkpoint['optimizer']) scheduler.load_state_dict(checkpoint['scheduler']) num_iter = checkpoint['iter'] current_epoch = checkpoint['current_epoch'] net = DataParallel(net).cuda() net.train() for epochId in range(current_epoch, 280): scheduler.step() total_losses = [0, 0] * (num_refinement_stages + 1) # heatmaps loss, paf loss per stage batch_per_iter_idx = 0 for batch_data in train_loader: if batch_per_iter_idx == 0: optimizer.zero_grad() images = batch_data['image'].cuda() keypoint_masks = batch_data['keypoint_mask'].cuda() paf_masks = batch_data['paf_mask'].cuda() keypoint_maps = batch_data['keypoint_maps'].cuda() paf_maps = batch_data['paf_maps'].cuda() stages_output = net(images) losses = [] for loss_idx in range(len(total_losses) // 2): losses.append(l2_loss(stages_output[loss_idx * 2], keypoint_maps, keypoint_masks, images.shape[0])) losses.append(l2_loss(stages_output[loss_idx * 2 + 1], paf_maps, paf_masks, images.shape[0])) total_losses[loss_idx * 2] += losses[-2].item() / batches_per_iter total_losses[loss_idx * 2 + 1] += losses[-1].item() / batches_per_iter loss = losses[0] for loss_idx in range(1, len(losses)): loss += losses[loss_idx] loss /= batches_per_iter loss.backward() batch_per_iter_idx += 1 if batch_per_iter_idx == batches_per_iter: optimizer.step() batch_per_iter_idx = 0 num_iter += 1 else: continue if num_iter % log_after == 0: print('Iter: {}'.format(num_iter)) for loss_idx in range(len(total_losses) // 2): print('\n'.join(['stage{}_pafs_loss: {}', 'stage{}_heatmaps_loss: {}']).format( loss_idx + 1, total_losses[loss_idx * 2 + 1] / log_after, loss_idx + 1, total_losses[loss_idx * 2] / log_after)) for loss_idx in range(len(total_losses)): total_losses[loss_idx] = 0 if num_iter % checkpoint_after == 0: snapshot_name = '{}/checkpoint_iter_{}.pth'.format(checkpoints_folder, num_iter) torch.save({'state_dict': net.module.state_dict(), 'optimizer': optimizer.state_dict(), 'scheduler': scheduler.state_dict(), 'iter': num_iter, 'current_epoch': epochId}, snapshot_name) if num_iter % val_after == 0: print('Validation...') evaluate(val_labels, val_output_name, val_images_folder, net) net.train()
null
7,112
import argparse import cv2 import numpy as np import torch from models.with_mobilenet import PoseEstimationWithMobileNet from modules.keypoints import extract_keypoints, group_keypoints from modules.load_state import load_state from modules.pose import Pose, track_poses from val import normalize, pad_width def infer_fast(net, img, net_input_height_size, stride, upsample_ratio, cpu, pad_value=(0, 0, 0), img_mean=np.array([128, 128, 128], np.float32), img_scale=np.float32(1/256)): height, width, _ = img.shape scale = net_input_height_size / height scaled_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) scaled_img = normalize(scaled_img, img_mean, img_scale) min_dims = [net_input_height_size, max(scaled_img.shape[1], net_input_height_size)] padded_img, pad = pad_width(scaled_img, stride, pad_value, min_dims) tensor_img = torch.from_numpy(padded_img).permute(2, 0, 1).unsqueeze(0).float() if not cpu: tensor_img = tensor_img.cuda() stages_output = net(tensor_img) stage2_heatmaps = stages_output[-2] heatmaps = np.transpose(stage2_heatmaps.squeeze().cpu().data.numpy(), (1, 2, 0)) heatmaps = cv2.resize(heatmaps, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC) stage2_pafs = stages_output[-1] pafs = np.transpose(stage2_pafs.squeeze().cpu().data.numpy(), (1, 2, 0)) pafs = cv2.resize(pafs, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC) return heatmaps, pafs, scale, pad def extract_keypoints(heatmap, all_keypoints, total_keypoint_num): heatmap[heatmap < 0.1] = 0 heatmap_with_borders = np.pad(heatmap, [(2, 2), (2, 2)], mode='constant') heatmap_center = heatmap_with_borders[1:heatmap_with_borders.shape[0]-1, 1:heatmap_with_borders.shape[1]-1] heatmap_left = heatmap_with_borders[1:heatmap_with_borders.shape[0]-1, 2:heatmap_with_borders.shape[1]] heatmap_right = heatmap_with_borders[1:heatmap_with_borders.shape[0]-1, 0:heatmap_with_borders.shape[1]-2] heatmap_up = heatmap_with_borders[2:heatmap_with_borders.shape[0], 1:heatmap_with_borders.shape[1]-1] heatmap_down = heatmap_with_borders[0:heatmap_with_borders.shape[0]-2, 1:heatmap_with_borders.shape[1]-1] heatmap_peaks = (heatmap_center > heatmap_left) &\ (heatmap_center > heatmap_right) &\ (heatmap_center > heatmap_up) &\ (heatmap_center > heatmap_down) heatmap_peaks = heatmap_peaks[1:heatmap_center.shape[0]-1, 1:heatmap_center.shape[1]-1] keypoints = list(zip(np.nonzero(heatmap_peaks)[1], np.nonzero(heatmap_peaks)[0])) # (w, h) keypoints = sorted(keypoints, key=itemgetter(0)) suppressed = np.zeros(len(keypoints), np.uint8) keypoints_with_score_and_id = [] keypoint_num = 0 for i in range(len(keypoints)): if suppressed[i]: continue for j in range(i+1, len(keypoints)): if math.sqrt((keypoints[i][0] - keypoints[j][0]) ** 2 + (keypoints[i][1] - keypoints[j][1]) ** 2) < 6: suppressed[j] = 1 keypoint_with_score_and_id = (keypoints[i][0], keypoints[i][1], heatmap[keypoints[i][1], keypoints[i][0]], total_keypoint_num + keypoint_num) keypoints_with_score_and_id.append(keypoint_with_score_and_id) keypoint_num += 1 all_keypoints.append(keypoints_with_score_and_id) return keypoint_num def group_keypoints(all_keypoints_by_type, pafs, pose_entry_size=20, min_paf_score=0.05): pose_entries = [] all_keypoints = np.array([item for sublist in all_keypoints_by_type for item in sublist]) points_per_limb = 10 grid = np.arange(points_per_limb, dtype=np.float32).reshape(1, -1, 1) all_keypoints_by_type = [np.array(keypoints, np.float32) for keypoints in all_keypoints_by_type] for part_id in range(len(BODY_PARTS_PAF_IDS)): part_pafs = pafs[:, :, BODY_PARTS_PAF_IDS[part_id]] kpts_a = all_keypoints_by_type[BODY_PARTS_KPT_IDS[part_id][0]] kpts_b = all_keypoints_by_type[BODY_PARTS_KPT_IDS[part_id][1]] n = len(kpts_a) m = len(kpts_b) if n == 0 or m == 0: continue # Get vectors between all pairs of keypoints, i.e. candidate limb vectors. a = kpts_a[:, :2] a = np.broadcast_to(a[None], (m, n, 2)) b = kpts_b[:, :2] vec_raw = (b[:, None, :] - a).reshape(-1, 1, 2) # Sample points along every candidate limb vector. steps = (1 / (points_per_limb - 1) * vec_raw) points = steps * grid + a.reshape(-1, 1, 2) points = points.round().astype(dtype=np.int32) x = points[..., 0].ravel() y = points[..., 1].ravel() # Compute affinity score between candidate limb vectors and part affinity field. field = part_pafs[y, x].reshape(-1, points_per_limb, 2) vec_norm = np.linalg.norm(vec_raw, ord=2, axis=-1, keepdims=True) vec = vec_raw / (vec_norm + 1e-6) affinity_scores = (field * vec).sum(-1).reshape(-1, points_per_limb) valid_affinity_scores = affinity_scores > min_paf_score valid_num = valid_affinity_scores.sum(1) affinity_scores = (affinity_scores * valid_affinity_scores).sum(1) / (valid_num + 1e-6) success_ratio = valid_num / points_per_limb # Get a list of limbs according to the obtained affinity score. valid_limbs = np.where(np.logical_and(affinity_scores > 0, success_ratio > 0.8))[0] if len(valid_limbs) == 0: continue b_idx, a_idx = np.divmod(valid_limbs, n) affinity_scores = affinity_scores[valid_limbs] # Suppress incompatible connections. a_idx, b_idx, affinity_scores = connections_nms(a_idx, b_idx, affinity_scores) connections = list(zip(kpts_a[a_idx, 3].astype(np.int32), kpts_b[b_idx, 3].astype(np.int32), affinity_scores)) if len(connections) == 0: continue if part_id == 0: pose_entries = [np.ones(pose_entry_size) * -1 for _ in range(len(connections))] for i in range(len(connections)): pose_entries[i][BODY_PARTS_KPT_IDS[0][0]] = connections[i][0] pose_entries[i][BODY_PARTS_KPT_IDS[0][1]] = connections[i][1] pose_entries[i][-1] = 2 pose_entries[i][-2] = np.sum(all_keypoints[connections[i][0:2], 2]) + connections[i][2] elif part_id == 17 or part_id == 18: kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0] kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1] for i in range(len(connections)): for j in range(len(pose_entries)): if pose_entries[j][kpt_a_id] == connections[i][0] and pose_entries[j][kpt_b_id] == -1: pose_entries[j][kpt_b_id] = connections[i][1] elif pose_entries[j][kpt_b_id] == connections[i][1] and pose_entries[j][kpt_a_id] == -1: pose_entries[j][kpt_a_id] = connections[i][0] continue else: kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0] kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1] for i in range(len(connections)): num = 0 for j in range(len(pose_entries)): if pose_entries[j][kpt_a_id] == connections[i][0]: pose_entries[j][kpt_b_id] = connections[i][1] num += 1 pose_entries[j][-1] += 1 pose_entries[j][-2] += all_keypoints[connections[i][1], 2] + connections[i][2] if num == 0: pose_entry = np.ones(pose_entry_size) * -1 pose_entry[kpt_a_id] = connections[i][0] pose_entry[kpt_b_id] = connections[i][1] pose_entry[-1] = 2 pose_entry[-2] = np.sum(all_keypoints[connections[i][0:2], 2]) + connections[i][2] pose_entries.append(pose_entry) filtered_entries = [] for i in range(len(pose_entries)): if pose_entries[i][-1] < 3 or (pose_entries[i][-2] / pose_entries[i][-1] < 0.2): continue filtered_entries.append(pose_entries[i]) pose_entries = np.asarray(filtered_entries) return pose_entries, all_keypoints class Pose: num_kpts = 18 kpt_names = ['nose', 'neck', 'r_sho', 'r_elb', 'r_wri', 'l_sho', 'l_elb', 'l_wri', 'r_hip', 'r_knee', 'r_ank', 'l_hip', 'l_knee', 'l_ank', 'r_eye', 'l_eye', 'r_ear', 'l_ear'] sigmas = np.array([.26, .79, .79, .72, .62, .79, .72, .62, 1.07, .87, .89, 1.07, .87, .89, .25, .25, .35, .35], dtype=np.float32) / 10.0 vars = (sigmas * 2) ** 2 last_id = -1 color = [0, 224, 255] def __init__(self, keypoints, confidence): super().__init__() self.keypoints = keypoints self.confidence = confidence self.bbox = Pose.get_bbox(self.keypoints) self.id = None self.filters = [[OneEuroFilter(), OneEuroFilter()] for _ in range(Pose.num_kpts)] def get_bbox(keypoints): found_keypoints = np.zeros((np.count_nonzero(keypoints[:, 0] != -1), 2), dtype=np.int32) found_kpt_id = 0 for kpt_id in range(Pose.num_kpts): if keypoints[kpt_id, 0] == -1: continue found_keypoints[found_kpt_id] = keypoints[kpt_id] found_kpt_id += 1 bbox = cv2.boundingRect(found_keypoints) return bbox def update_id(self, id=None): self.id = id if self.id is None: self.id = Pose.last_id + 1 Pose.last_id += 1 def draw(self, img): assert self.keypoints.shape == (Pose.num_kpts, 2) for part_id in range(len(BODY_PARTS_PAF_IDS) - 2): kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0] global_kpt_a_id = self.keypoints[kpt_a_id, 0] if global_kpt_a_id != -1: x_a, y_a = self.keypoints[kpt_a_id] cv2.circle(img, (int(x_a), int(y_a)), 3, Pose.color, -1) kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1] global_kpt_b_id = self.keypoints[kpt_b_id, 0] if global_kpt_b_id != -1: x_b, y_b = self.keypoints[kpt_b_id] cv2.circle(img, (int(x_b), int(y_b)), 3, Pose.color, -1) if global_kpt_a_id != -1 and global_kpt_b_id != -1: cv2.line(img, (int(x_a), int(y_a)), (int(x_b), int(y_b)), Pose.color, 2) def track_poses(previous_poses, current_poses, threshold=3, smooth=False): """Propagate poses ids from previous frame results. Id is propagated, if there are at least `threshold` similar keypoints between pose from previous frame and current. If correspondence between pose on previous and current frame was established, pose keypoints are smoothed. :param previous_poses: poses from previous frame with ids :param current_poses: poses from current frame to assign ids :param threshold: minimal number of similar keypoints between poses :param smooth: smooth pose keypoints between frames :return: None """ current_poses = sorted(current_poses, key=lambda pose: pose.confidence, reverse=True) # match confident poses first mask = np.ones(len(previous_poses), dtype=np.int32) for current_pose in current_poses: best_matched_id = None best_matched_pose_id = None best_matched_iou = 0 for id, previous_pose in enumerate(previous_poses): if not mask[id]: continue iou = get_similarity(current_pose, previous_pose) if iou > best_matched_iou: best_matched_iou = iou best_matched_pose_id = previous_pose.id best_matched_id = id if best_matched_iou >= threshold: mask[best_matched_id] = 0 else: # pose not similar to any previous best_matched_pose_id = None current_pose.update_id(best_matched_pose_id) if smooth: for kpt_id in range(Pose.num_kpts): if current_pose.keypoints[kpt_id, 0] == -1: continue # reuse filter if previous pose has valid filter if (best_matched_pose_id is not None and previous_poses[best_matched_id].keypoints[kpt_id, 0] != -1): current_pose.filters[kpt_id] = previous_poses[best_matched_id].filters[kpt_id] current_pose.keypoints[kpt_id, 0] = current_pose.filters[kpt_id][0](current_pose.keypoints[kpt_id, 0]) current_pose.keypoints[kpt_id, 1] = current_pose.filters[kpt_id][1](current_pose.keypoints[kpt_id, 1]) current_pose.bbox = Pose.get_bbox(current_pose.keypoints) def run_demo(net, image_provider, height_size, cpu, track, smooth): net = net.eval() if not cpu: net = net.cuda() stride = 8 upsample_ratio = 4 num_keypoints = Pose.num_kpts previous_poses = [] delay = 1 for img in image_provider: orig_img = img.copy() heatmaps, pafs, scale, pad = infer_fast(net, img, height_size, stride, upsample_ratio, cpu) total_keypoints_num = 0 all_keypoints_by_type = [] for kpt_idx in range(num_keypoints): # 19th for bg total_keypoints_num += extract_keypoints(heatmaps[:, :, kpt_idx], all_keypoints_by_type, total_keypoints_num) pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, pafs) for kpt_id in range(all_keypoints.shape[0]): all_keypoints[kpt_id, 0] = (all_keypoints[kpt_id, 0] * stride / upsample_ratio - pad[1]) / scale all_keypoints[kpt_id, 1] = (all_keypoints[kpt_id, 1] * stride / upsample_ratio - pad[0]) / scale current_poses = [] for n in range(len(pose_entries)): if len(pose_entries[n]) == 0: continue pose_keypoints = np.ones((num_keypoints, 2), dtype=np.int32) * -1 for kpt_id in range(num_keypoints): if pose_entries[n][kpt_id] != -1.0: # keypoint was found pose_keypoints[kpt_id, 0] = int(all_keypoints[int(pose_entries[n][kpt_id]), 0]) pose_keypoints[kpt_id, 1] = int(all_keypoints[int(pose_entries[n][kpt_id]), 1]) pose = Pose(pose_keypoints, pose_entries[n][18]) current_poses.append(pose) if track: track_poses(previous_poses, current_poses, smooth=smooth) previous_poses = current_poses for pose in current_poses: pose.draw(img) img = cv2.addWeighted(orig_img, 0.6, img, 0.4, 0) for pose in current_poses: cv2.rectangle(img, (pose.bbox[0], pose.bbox[1]), (pose.bbox[0] + pose.bbox[2], pose.bbox[1] + pose.bbox[3]), (0, 255, 0)) if track: cv2.putText(img, 'id: {}'.format(pose.id), (pose.bbox[0], pose.bbox[1] - 16), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255)) cv2.imshow('Lightweight Human Pose Estimation Python Demo', img) key = cv2.waitKey(delay) if key == 27: # esc return elif key == 112: # 'p' if delay == 1: delay = 0 else: delay = 1
null
7,113
import copy import json import math import os import pickle import cv2 import numpy as np import pycocotools from torch.utils.data.dataset import Dataset def get_mask(segmentations, mask): for segmentation in segmentations: rle = pycocotools.mask.frPyObjects(segmentation, mask.shape[0], mask.shape[1]) mask[pycocotools.mask.decode(rle) > 0.5] = 0 return mask
null
7,114
import argparse import torch from models.with_mobilenet import PoseEstimationWithMobileNet from modules.load_state import load_state def convert_to_onnx(net, output_name): input = torch.randn(1, 3, 256, 456) input_names = ['data'] output_names = ['stage_0_output_1_heatmaps', 'stage_0_output_0_pafs', 'stage_1_output_1_heatmaps', 'stage_1_output_0_pafs'] torch.onnx.export(net, input, output_name, verbose=True, input_names=input_names, output_names=output_names)
null
7,115
import argparse import json import pickle The provided code snippet includes necessary dependencies for implementing the `prepare_annotations` function. Write a Python function `def prepare_annotations(annotations_per_image, images_info, net_input_size)` to solve the following problem: Prepare labels for training. For each annotated person calculates center to perform crop around it during the training. Also converts data to the internal format. :param annotations_per_image: all annotations for specified image id :param images_info: auxiliary information about all images :param net_input_size: network input size during training :return: list of prepared annotations Here is the function: def prepare_annotations(annotations_per_image, images_info, net_input_size): """Prepare labels for training. For each annotated person calculates center to perform crop around it during the training. Also converts data to the internal format. :param annotations_per_image: all annotations for specified image id :param images_info: auxiliary information about all images :param net_input_size: network input size during training :return: list of prepared annotations """ prepared_annotations = [] for _, annotations in annotations_per_image.items(): previous_centers = [] for annotation in annotations[0]: if (annotation['num_keypoints'] < 5 or annotation['area'] < 32 * 32): continue person_center = [annotation['bbox'][0] + annotation['bbox'][2] / 2, annotation['bbox'][1] + annotation['bbox'][3] / 2] is_close = False for previous_center in previous_centers: distance_to_previous = ((person_center[0] - previous_center[0]) ** 2 + (person_center[1] - previous_center[1]) ** 2) ** 0.5 if distance_to_previous < previous_center[2] * 0.3: is_close = True break if is_close: continue prepared_annotation = { 'img_paths': images_info[annotation['image_id']]['file_name'], 'img_width': images_info[annotation['image_id']]['width'], 'img_height': images_info[annotation['image_id']]['height'], 'objpos': person_center, 'image_id': annotation['image_id'], 'bbox': annotation['bbox'], 'segment_area': annotation['area'], 'scale_provided': annotation['bbox'][3] / net_input_size, 'num_keypoints': annotation['num_keypoints'], 'segmentations': annotations[1] } keypoints = [] for i in range(len(annotation['keypoints']) // 3): keypoint = [annotation['keypoints'][i * 3], annotation['keypoints'][i * 3 + 1], 2] if annotation['keypoints'][i * 3 + 2] == 1: keypoint[2] = 0 elif annotation['keypoints'][i * 3 + 2] == 2: keypoint[2] = 1 keypoints.append(keypoint) prepared_annotation['keypoints'] = keypoints prepared_other_annotations = [] for other_annotation in annotations[0]: if other_annotation == annotation: continue prepared_other_annotation = { 'objpos': [other_annotation['bbox'][0] + other_annotation['bbox'][2] / 2, other_annotation['bbox'][1] + other_annotation['bbox'][3] / 2], 'bbox': other_annotation['bbox'], 'segment_area': other_annotation['area'], 'scale_provided': other_annotation['bbox'][3] / net_input_size, 'num_keypoints': other_annotation['num_keypoints'] } keypoints = [] for i in range(len(other_annotation['keypoints']) // 3): keypoint = [other_annotation['keypoints'][i * 3], other_annotation['keypoints'][i * 3 + 1], 2] if other_annotation['keypoints'][i * 3 + 2] == 1: keypoint[2] = 0 elif other_annotation['keypoints'][i * 3 + 2] == 2: keypoint[2] = 1 keypoints.append(keypoint) prepared_other_annotation['keypoints'] = keypoints prepared_other_annotations.append(prepared_other_annotation) prepared_annotation['processed_other_annotations'] = prepared_other_annotations prepared_annotations.append(prepared_annotation) previous_centers.append((person_center[0], person_center[1], annotation['bbox'][2], annotation['bbox'][3])) return prepared_annotations
Prepare labels for training. For each annotated person calculates center to perform crop around it during the training. Also converts data to the internal format. :param annotations_per_image: all annotations for specified image id :param images_info: auxiliary information about all images :param net_input_size: network input size during training :return: list of prepared annotations
7,116
from openai import OpenAI import sys import os import configparser API_KEYS_LOCATION = os.path.join(CONFIG_DIR, 'openaiapirc') def create_template_ini_file(): """ If the ini file does not exist create it and add the organization_id and secret_key """ if not os.path.isfile(API_KEYS_LOCATION): with open(API_KEYS_LOCATION, 'w') as f: f.write('[openai]\n') f.write('organization_id=\n') f.write('secret_key=\n') f.write('model=gpt-3.5-turbo-0613\n') f.write('base_url=https://api.openai.com/v1\n') print('OpenAI API config file created at {}'.format(API_KEYS_LOCATION)) print('Please edit it and add your organization ID and secret key') print('If you do not yet have an organization ID and secret key, you\n' 'need to register for OpenAI Codex: \n' 'https://openai.com/blog/openai-codex/') sys.exit(1) client, model_name = initialize_openai_api() The provided code snippet includes necessary dependencies for implementing the `initialize_openai_api` function. Write a Python function `def initialize_openai_api()` to solve the following problem: Initialize the OpenAI API Here is the function: def initialize_openai_api(): """ Initialize the OpenAI API """ # Check if file at API_KEYS_LOCATION exists create_template_ini_file() config = configparser.ConfigParser() config.read(API_KEYS_LOCATION) api_key = config['openai']['secret_key'].strip('"').strip("'") model_name = config['openai'].get('model', 'gpt-3.5-turbo').strip('"').strip("'") base_url = config['openai'].get('base_url', 'https://api.openai.com/v1').strip('"').strip("'") client = OpenAI(api_key=api_key, base_url=base_url) return client, model_name
Initialize the OpenAI API
7,117
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglFunction: def __init__(self, func, api_num_spec_tokens=None, bind_arguments=None): self.func = func self.api_num_spec_tokens = api_num_spec_tokens self.bind_arguments = bind_arguments or {} self.pin_prefix_rid = None # Parse arguments argspec = inspect.getfullargspec(func) assert argspec.args[0] == "s", 'The first argument must be "s"' self.arg_names = argspec.args[1:] def bind(self, **kwargs): assert all(key in self.arg_names for key in kwargs) new_bind_dict = {**self.bind_arguments, **kwargs} return SglFunction(self.func, bind_arguments=new_bind_dict) def run( self, *args, max_new_tokens: int = 16, stop: Union[str, List[str]] = (), temperature: float = 1.0, top_p: float = 1.0, top_k: int = -1, frequency_penalty: float = 0.0, presence_penalty: float = 0.0, ignore_eos: bool = False, stream: bool = False, backend=None, **kwargs, ): from sglang.lang.interpreter import run_program default_sampling_para = SglSamplingParams( max_new_tokens=max_new_tokens, stop=stop, temperature=temperature, top_p=top_p, top_k=top_k, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, ignore_eos=ignore_eos, ) backend = backend or global_config.default_backend return run_program(self, backend, args, kwargs, default_sampling_para, stream) def run_batch( self, batch_kwargs, *, max_new_tokens: int = 16, stop: Union[str, List[str]] = (), temperature: float = 1.0, top_p: float = 1.0, top_k: int = -1, frequency_penalty: float = 0.0, presence_penalty: float = 0.0, ignore_eos: bool = False, backend=None, num_threads: Union[str, int] = "auto", progress_bar: bool = False, ): from sglang.lang.interpreter import run_program_batch assert isinstance(batch_kwargs, (list, tuple)) if len(batch_kwargs) == 0: return [] assert isinstance(batch_kwargs[0], dict) default_sampling_para = SglSamplingParams( max_new_tokens=max_new_tokens, stop=stop, temperature=temperature, top_p=top_p, top_k=top_k, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, ignore_eos=ignore_eos, ) backend = backend or global_config.default_backend return run_program_batch( self, backend, batch_kwargs, default_sampling_para, num_threads, progress_bar, ) def trace(self, *, backend=None, **kwargs): from sglang.lang.tracer import trace_program backend = backend or global_config.default_backend return trace_program(self, kwargs, backend) def pin(self, backend=None): from sglang.lang.interpreter import pin_program backend = backend or global_config.default_backend return pin_program(self, backend) def unpin(self, backend=None): from sglang.lang.interpreter import unpin_program backend = backend or global_config.default_backend return unpin_program(self, backend) def compile(self, *, backend=None): from sglang.lang.compiler import compile_func return compile_func(self, backend) def __call__(self, *args, **kwargs): from sglang.lang.tracer import TracingScope tracing_scope = TracingScope.get_current_scope() if tracing_scope is None: return self.run(*args, **kwargs) else: kwargs["backend"] = tracing_scope.tracer_state.backend return self.trace(*args, **kwargs) def function( func: Optional[Callable] = None, api_num_spec_tokens: Optional[int] = None ): if func: return SglFunction(func, api_num_spec_tokens=api_num_spec_tokens) def decorator(func): return SglFunction(func, api_num_spec_tokens=api_num_spec_tokens) return decorator
null
7,118
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) def Runtime(*args, **kwargs): # Avoid importing unnecessary dependency from sglang.srt.server import Runtime return Runtime(*args, **kwargs)
null
7,119
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class BaseBackend: def __init__(self) -> None: self.support_concate_and_append = False self.chat_template = get_chat_template("default") def get_model_name(self): raise NotImplementedError() def get_chat_template(self): return self.chat_template def cache_prefix(self, prefix_str: str): pass def uncache_prefix(self, rid: str): pass def end_request(self, rid: Union[str, List[str]]): pass def begin_program(self, s: StreamExecutor): pass def end_program(self, s: Union[StreamExecutor, List[StreamExecutor]]): pass def commit_lazy_operations(self, s: StreamExecutor): pass def fork_program( self, src: StreamExecutor, dst: List[StreamExecutor], position_ids_offset: Optional[List[int]] = None, ): pass def fill_image(self, s: StreamExecutor): pass def generate( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def generate_stream( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def select( self, s: StreamExecutor, choices: List[str], temperature: float, ): raise NotImplementedError() def concatenate_and_append(self, src_rids: List[str], dst_rid: str): raise NotImplementedError() def shutdown(self): pass def flush_cache(self): pass def get_server_args(self): pass global_config = GlobalConfig() def set_default_backend(backend: BaseBackend): global_config.default_backend = backend
null
7,120
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class BaseBackend: def __init__(self) -> None: self.support_concate_and_append = False self.chat_template = get_chat_template("default") def get_model_name(self): raise NotImplementedError() def get_chat_template(self): return self.chat_template def cache_prefix(self, prefix_str: str): pass def uncache_prefix(self, rid: str): pass def end_request(self, rid: Union[str, List[str]]): pass def begin_program(self, s: StreamExecutor): pass def end_program(self, s: Union[StreamExecutor, List[StreamExecutor]]): pass def commit_lazy_operations(self, s: StreamExecutor): pass def fork_program( self, src: StreamExecutor, dst: List[StreamExecutor], position_ids_offset: Optional[List[int]] = None, ): pass def fill_image(self, s: StreamExecutor): pass def generate( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def generate_stream( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def select( self, s: StreamExecutor, choices: List[str], temperature: float, ): raise NotImplementedError() def concatenate_and_append(self, src_rids: List[str], dst_rid: str): raise NotImplementedError() def shutdown(self): pass def flush_cache(self): pass def get_server_args(self): pass global_config = GlobalConfig() def flush_cache(backend: BaseBackend = None): backend = backend or global_config.default_backend if backend is None: return False return backend.flush_cache()
null
7,121
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class BaseBackend: def __init__(self) -> None: self.support_concate_and_append = False self.chat_template = get_chat_template("default") def get_model_name(self): raise NotImplementedError() def get_chat_template(self): return self.chat_template def cache_prefix(self, prefix_str: str): pass def uncache_prefix(self, rid: str): pass def end_request(self, rid: Union[str, List[str]]): pass def begin_program(self, s: StreamExecutor): pass def end_program(self, s: Union[StreamExecutor, List[StreamExecutor]]): pass def commit_lazy_operations(self, s: StreamExecutor): pass def fork_program( self, src: StreamExecutor, dst: List[StreamExecutor], position_ids_offset: Optional[List[int]] = None, ): pass def fill_image(self, s: StreamExecutor): pass def generate( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def generate_stream( self, s: StreamExecutor, sampling_params: SglSamplingParams, ): raise NotImplementedError() def select( self, s: StreamExecutor, choices: List[str], temperature: float, ): raise NotImplementedError() def concatenate_and_append(self, src_rids: List[str], dst_rid: str): raise NotImplementedError() def shutdown(self): pass def flush_cache(self): pass def get_server_args(self): pass global_config = GlobalConfig() def get_server_args(backend: BaseBackend = None): backend = backend or global_config.default_backend if backend is None: return None return backend.get_server_args()
null
7,122
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglGen(SglExpr): def __init__( self, name, max_new_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, dtype, regex, ): def __repr__(self): class SglSelect(SglExpr): def __init__(self, name, choices, temperature): def __repr__(self): def gen( name: Optional[str] = None, max_tokens: Optional[int] = None, stop: Optional[Union[str, List[str]]] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, top_k: Optional[int] = None, frequency_penalty: Optional[float] = None, presence_penalty: Optional[float] = None, ignore_eos: Optional[bool] = None, dtype: Optional[type] = None, choices: Optional[List[str]] = None, regex: Optional[str] = None, ): if choices: return SglSelect(name, choices, 0.0 if temperature is None else temperature) # check regex is valid if regex is not None: try: re.compile(regex) except re.error as e: raise e return SglGen( name, max_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, dtype, regex, )
null
7,123
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglGen(SglExpr): def __init__( self, name, max_new_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, dtype, regex, ): super().__init__() self.name = name self.sampling_params = SglSamplingParams( max_new_tokens=max_new_tokens, stop=stop, temperature=temperature, top_p=top_p, top_k=top_k, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, ignore_eos=ignore_eos, dtype=dtype, regex=regex, ) def __repr__(self): return f"Gen('{self.name}')" def gen_int( name: Optional[str] = None, max_tokens: Optional[int] = None, stop: Optional[Union[str, List[str]]] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, top_k: Optional[int] = None, frequency_penalty: Optional[float] = None, presence_penalty: Optional[float] = None, ignore_eos: Optional[bool] = None, ): return SglGen( name, max_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, int, None, )
null
7,124
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglGen(SglExpr): def __init__( self, name, max_new_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, dtype, regex, ): super().__init__() self.name = name self.sampling_params = SglSamplingParams( max_new_tokens=max_new_tokens, stop=stop, temperature=temperature, top_p=top_p, top_k=top_k, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, ignore_eos=ignore_eos, dtype=dtype, regex=regex, ) def __repr__(self): return f"Gen('{self.name}')" def gen_string( name: Optional[str] = None, max_tokens: Optional[int] = None, stop: Optional[Union[str, List[str]]] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, top_k: Optional[int] = None, frequency_penalty: Optional[float] = None, presence_penalty: Optional[float] = None, ignore_eos: Optional[bool] = None, ): return SglGen( name, max_tokens, stop, temperature, top_p, top_k, frequency_penalty, presence_penalty, ignore_eos, str, None, )
null
7,125
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglExpr: def __init__(self): def __add__(self, other): def __radd__(self, other): def concatenate_ir(self, a, b): def print_graph_dfs(self): def dfs_print(x): class SglImage(SglExpr): def __init__(self, path): def __repr__(self) -> str: def image(expr: SglExpr): return SglImage(expr)
null
7,126
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglSelect(SglExpr): def __init__(self, name, choices, temperature): super().__init__() self.name = name self.choices = choices self.temperature = temperature def __repr__(self): return f"Select({self.name}, choices={self.choices})" def select( name: Optional[str] = None, choices: List[str] = None, temperature: float = 0.0, ): assert choices is not None return SglSelect(name, choices, temperature)
null
7,127
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) def _role_common(name: str, expr: Optional[SglExpr] = None): if expr is None: return SglExprList([SglRoleBegin(name), SglRoleEnd(name)]) else: return SglExprList([SglRoleBegin(name), expr, SglRoleEnd(name)]) class SglExpr: node_ct = 0 def __init__(self): self.node_id = SglExpr.node_ct self.prev_node = None self.pid = None SglExpr.node_ct += 1 def __add__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr) return self.concatenate_ir(self, other) def __radd__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr), f"{other}" return self.concatenate_ir(other, self) def concatenate_ir(self, a, b): if isinstance(a, SglExprList): if isinstance(b, SglExprList): return SglExprList(a.expr_list + b.expr_list) else: return SglExprList(a.expr_list + [b]) elif isinstance(b, SglExprList): return SglExprList([a] + b.expr_list) return SglExprList([a, b]) def print_graph_dfs(self): ret = [""] visited = set() def dfs_print(x): if x is None or x in visited: return visited.add(x) # Print dependency if x.prev_node is not None: dfs_print(x.prev_node) if isinstance(x, SglExprList): for y in x.expr_list: dfs_print(y) # elif isinstance(x, SglRole): # dfs_print(x.expr) elif isinstance(x, SglVariable): dfs_print(x.source) # Print the node itself if isinstance(x, (SglFork, SglGetForkItem)): ret[0] += f"%{x.node_id} = {x}\n" else: if x.prev_node is not None: ret[0] += ( f"%{x.node_id} = %{x.prev_node.node_id} + " + str(x) + "\n" ) else: ret[0] += f"%{x.node_id} = " + str(x) + "\n" dfs_print(self) return ret[0] def system(expr: Optional[SglExpr] = None): return _role_common("system", expr)
null
7,128
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) def _role_common(name: str, expr: Optional[SglExpr] = None): if expr is None: return SglExprList([SglRoleBegin(name), SglRoleEnd(name)]) else: return SglExprList([SglRoleBegin(name), expr, SglRoleEnd(name)]) class SglExpr: node_ct = 0 def __init__(self): self.node_id = SglExpr.node_ct self.prev_node = None self.pid = None SglExpr.node_ct += 1 def __add__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr) return self.concatenate_ir(self, other) def __radd__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr), f"{other}" return self.concatenate_ir(other, self) def concatenate_ir(self, a, b): if isinstance(a, SglExprList): if isinstance(b, SglExprList): return SglExprList(a.expr_list + b.expr_list) else: return SglExprList(a.expr_list + [b]) elif isinstance(b, SglExprList): return SglExprList([a] + b.expr_list) return SglExprList([a, b]) def print_graph_dfs(self): ret = [""] visited = set() def dfs_print(x): if x is None or x in visited: return visited.add(x) # Print dependency if x.prev_node is not None: dfs_print(x.prev_node) if isinstance(x, SglExprList): for y in x.expr_list: dfs_print(y) # elif isinstance(x, SglRole): # dfs_print(x.expr) elif isinstance(x, SglVariable): dfs_print(x.source) # Print the node itself if isinstance(x, (SglFork, SglGetForkItem)): ret[0] += f"%{x.node_id} = {x}\n" else: if x.prev_node is not None: ret[0] += ( f"%{x.node_id} = %{x.prev_node.node_id} + " + str(x) + "\n" ) else: ret[0] += f"%{x.node_id} = " + str(x) + "\n" dfs_print(self) return ret[0] def user(expr: Optional[SglExpr] = None): return _role_common("user", expr)
null
7,129
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) def _role_common(name: str, expr: Optional[SglExpr] = None): if expr is None: return SglExprList([SglRoleBegin(name), SglRoleEnd(name)]) else: return SglExprList([SglRoleBegin(name), expr, SglRoleEnd(name)]) class SglExpr: node_ct = 0 def __init__(self): self.node_id = SglExpr.node_ct self.prev_node = None self.pid = None SglExpr.node_ct += 1 def __add__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr) return self.concatenate_ir(self, other) def __radd__(self, other): if isinstance(other, str): other = SglConstantText(other) assert isinstance(other, SglExpr), f"{other}" return self.concatenate_ir(other, self) def concatenate_ir(self, a, b): if isinstance(a, SglExprList): if isinstance(b, SglExprList): return SglExprList(a.expr_list + b.expr_list) else: return SglExprList(a.expr_list + [b]) elif isinstance(b, SglExprList): return SglExprList([a] + b.expr_list) return SglExprList([a, b]) def print_graph_dfs(self): ret = [""] visited = set() def dfs_print(x): if x is None or x in visited: return visited.add(x) # Print dependency if x.prev_node is not None: dfs_print(x.prev_node) if isinstance(x, SglExprList): for y in x.expr_list: dfs_print(y) # elif isinstance(x, SglRole): # dfs_print(x.expr) elif isinstance(x, SglVariable): dfs_print(x.source) # Print the node itself if isinstance(x, (SglFork, SglGetForkItem)): ret[0] += f"%{x.node_id} = {x}\n" else: if x.prev_node is not None: ret[0] += ( f"%{x.node_id} = %{x.prev_node.node_id} + " + str(x) + "\n" ) else: ret[0] += f"%{x.node_id} = " + str(x) + "\n" dfs_print(self) return ret[0] def assistant(expr: Optional[SglExpr] = None): return _role_common("assistant", expr)
null
7,130
import re from typing import Callable, List, Optional, Union from sglang.backend.anthropic import Anthropic from sglang.backend.base_backend import BaseBackend from sglang.backend.openai import OpenAI from sglang.backend.runtime_endpoint import RuntimeEndpoint from sglang.backend.vertexai import VertexAI from sglang.global_config import global_config from sglang.lang.ir import ( SglExpr, SglExprList, SglFunction, SglGen, SglImage, SglRoleBegin, SglRoleEnd, SglSelect, ) class SglRoleBegin(SglExpr): def __init__(self, role): super().__init__() self.role = role def __repr__(self): return f"RoleBegin({self.role})" def user_begin(): return SglRoleBegin("user")
null