



import argparse
import re

import torch
from CLAP import create_model

from transformers import AutoFeatureExtractor, ClapConfig, ClapModel


lowercase_	       =			{
    '''text_branch''': '''text_model''',
    '''audio_branch''': '''audio_model.audio_encoder''',
    '''attn''': '''attention.self''',
    '''self.proj''': '''output.dense''',
    '''attention.self_mask''': '''attn_mask''',
    '''mlp.fc1''': '''intermediate.dense''',
    '''mlp.fc2''': '''output.dense''',
    '''norm1''': '''layernorm_before''',
    '''norm2''': '''layernorm_after''',
    '''bn0''': '''batch_norm''',
}

lowercase_	       =			AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''')






def 					__lowerCAmelCase		(  __lowerCamelCase	:    Any				,   __lowerCamelCase	:    Optional[Any]=False	)  ->						Union[str, Any]:
					__lowerCAmelCase   ,	__lowerCAmelCase	   =create_model(
					    """HTSAT-tiny"""				,   """roberta"""				,   __lowerCamelCase				,   precision="""fp32"""				,   device="""cuda:0""" if torch.cuda.is_available() else """cpu"""				,   enable_fusion=__lowerCamelCase				,   fusion_type="""aff_2d""" if enable_fusion else None				,   )
					return model, model_cfg






def 					__lowerCAmelCase		(  __lowerCamelCase	:    Any	)  ->						Union[str, Any]:
					__lowerCAmelCase	   ={}

					__lowerCAmelCase	   =r""".*sequential.(\d+).*"""
					__lowerCAmelCase	   =r""".*_projection.(\d+).*"""

					for key, value in state_dict.items():
										# check if any key needs to be modified
										for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
															if key_to_modify in key:
																				__lowerCAmelCase	   =key.replace(__lowerCamelCase				,   __lowerCamelCase	)

										if re.match(__lowerCamelCase				,   __lowerCamelCase	):
															# replace sequential layers with list
															__lowerCAmelCase	   =re.match(__lowerCamelCase				,   __lowerCamelCase	).group(1	)

															__lowerCAmelCase	   =key.replace(f"""sequential.{sequential_layer}."""				,   f"""layers.{int(__lowerCamelCase	)//3}.linear."""	)
										elif re.match(__lowerCamelCase				,   __lowerCamelCase	):
															__lowerCAmelCase	   =int(re.match(__lowerCamelCase				,   __lowerCamelCase	).group(1	)	)

															# Because in CLAP they use `nn.Sequential`...
															__lowerCAmelCase	   =1 if projecton_layer == 0 else 2

															__lowerCAmelCase	   =key.replace(f"""_projection.{projecton_layer}."""				,   f"""_projection.linear{transformers_projection_layer}."""	)

										if "audio" and "qkv" in key:
															# split qkv into query key and value
															__lowerCAmelCase	   =value
															__lowerCAmelCase	   =mixed_qkv.size(0	) // 3

															__lowerCAmelCase	   =mixed_qkv[:qkv_dim]
															__lowerCAmelCase	   =mixed_qkv[qkv_dim : qkv_dim * 2]
															__lowerCAmelCase	   =mixed_qkv[qkv_dim * 2 :]

															__lowerCAmelCase	   =query_layer
															__lowerCAmelCase	   =key_layer
															__lowerCAmelCase	   =value_layer
										else:
															__lowerCAmelCase	   =value

					return model_state_dict






def 					__lowerCAmelCase		(  __lowerCamelCase	:    Tuple				,   __lowerCamelCase	:    List[str]				,   __lowerCamelCase	:    List[str]				,   __lowerCamelCase	:    Tuple=False	)  ->						List[Any]:
					__lowerCAmelCase   ,	__lowerCAmelCase	   =init_clap(__lowerCamelCase				,   enable_fusion=__lowerCamelCase	)

					clap_model.eval()
					__lowerCAmelCase	   =clap_model.state_dict()
					__lowerCAmelCase	   =rename_state_dict(__lowerCamelCase	)

					__lowerCAmelCase	   =ClapConfig()
					__lowerCAmelCase	   =enable_fusion
					__lowerCAmelCase	   =ClapModel(__lowerCamelCase	)

					# ignore the spectrogram embedding layer
					model.load_state_dict(__lowerCamelCase				,   strict=__lowerCamelCase	)

					model.save_pretrained(__lowerCamelCase	)
					transformers_config.save_pretrained(__lowerCamelCase	)


if __name__ == "__main__":
				lowercase_	       =			argparse.ArgumentParser()
				parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
				parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
				parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
				parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''')
				lowercase_	       =			parser.parse_args()

				convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)









from itertools import zip_longest

import requests
from bsa import BeautifulSoup
from pandas import DataFrame






def 					__lowerCAmelCase		(  __lowerCamelCase	:    str = "laptop"	)  ->						DataFrame:
					__lowerCAmelCase	   =f"""https://www.amazon.in/laptop/s?k={product}"""
					__lowerCAmelCase	   ={
					    """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36
        (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""",
					    """Accept-Language""": """en-US, en;q=0.5""",
					}
					__lowerCAmelCase	   =BeautifulSoup(requests.get(__lowerCamelCase				,   headers=__lowerCamelCase	).text	)
					# Initialize a Pandas dataframe with the column titles
					__lowerCAmelCase	   =DataFrame(
					    columns=[
					        """Product Title""",
					        """Product Link""",
					        """Current Price of the product""",
					        """Product Rating""",
					        """MRP of the product""",
					        """Discount""",
					    ]	)
					# Loop through each entry and store them in the dataframe
					for item, _ in zip_longest(
					    soup.find_all(
					        """div"""				,   attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""}				,   )				,   soup.find_all("""div"""				,   attrs={"""class""": """a-row a-size-base a-color-base"""}	)				,   ):
										try:
															__lowerCAmelCase	   =item.ha.text
															__lowerCAmelCase	   ="""https://www.amazon.in/""" + item.ha.a["""href"""]
															__lowerCAmelCase	   =item.find("""span"""				,   attrs={"""class""": """a-offscreen"""}	).text
															try:
																				__lowerCAmelCase	   =item.find("""span"""				,   attrs={"""class""": """a-icon-alt"""}	).text
															except AttributeError:
																				__lowerCAmelCase	   ="""Not available"""
															try:
																				__lowerCAmelCase	   =(
																				    """₹"""
																				    + item.find(
																				        """span"""				,   attrs={"""class""": """a-price a-text-price"""}	).text.split("""₹"""	)[1]
																				)
															except AttributeError:
																				__lowerCAmelCase	   =""""""
															try:
																				__lowerCAmelCase	   =float(
																				    (
																				        (
																				            float(product_mrp.strip("""₹"""	).replace(""","""				,   """"""	)	)
																				            - float(product_price.strip("""₹"""	).replace(""","""				,   """"""	)	)
																				        )
																				        / float(product_mrp.strip("""₹"""	).replace(""","""				,   """"""	)	)
																				    )
																				    * 100	)
															except ValueError:
																				__lowerCAmelCase	   =float("""nan"""	)
										except AttributeError:
															pass
										__lowerCAmelCase	   =[
										    product_title,
										    product_link,
										    product_price,
										    product_rating,
										    product_mrp,
										    discount,
										]
					__lowerCAmelCase	   =""" """
					__lowerCAmelCase	   =""" """
					data_frame.index += 1
					return data_frame


if __name__ == "__main__":
				lowercase_	       =			'''headphones'''
				get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")




