from hashlib import sha256 import pandas as pd from .audience import Audience class FbAudience(Audience): """Follow the API docs instead of business help (they have slightly conflicting info) - Business help: https://www.facebook.com/business/help/2082575038703844?id=2469097953376494 - API docs: https://developers.facebook.com/docs/marketing-api/audiences/guides/custom-audiences/#hash """ source_attribute_ids = [ 1, # userEmail 9, # userDob 98, # enrUniqueGender 49, # enrUserFirstName # TODO! Add enrUserLastName 55, # enrLocality 60, # enrCountryISO2 ] def __init__(self, collection_id, schema): super().__init__(collection_id=collection_id, schema=schema) def get_audience_data(self): data = self._generate_available_data() # Make gender format digestible for FB data["98"] = data["98"].str.replace("female", "f").replace("male", "m") # Rename fields to match data = data.rename( columns={ "1": "EMAIL", "49": "FN", "9": "DOB", "98": "GEN", "60": "COUNTRY", "55": "CT", } ) """ All fields are required to be lower case and hashed - https://developers.facebook.com/docs/marketing-api/audiences/guides/custom-audiences/#hash """ data = data.applymap(lambda x: self.lower_case(x)) # data = data.applymap(lambda x: self.obfuscate_sha256(x)) final_data = data.applymap( lambda x: None if (x == "unknown" or pd.isna(x)) else self.obfuscate_sha256(x) ) return final_data, data @staticmethod def lower_case(x): """Lower letters""" try: lower_case = x.lower() except Exception: # We can't transform Nones or np.nans lower_case = x return lower_case @staticmethod def obfuscate_sha256(string: str): """Returns SHA 256 obfuscated string""" return sha256(str(string).encode()).hexdigest()