




import os
import sys

from . import rsa_key_generator as rkg

UpperCAmelCase_   							=      128
UpperCAmelCase_   							=      256




def    lowerCamelCase__			(		A__			:   str    ,     A__			:   int = DEFAULT_BLOCK_SIZE      ):





       '''simple docstring'''



       __lowerCamelCase  =		message.encode("""ascii"""      )

       __lowerCamelCase  =		[]
       for block_start in range(0    ,     len(A__      )    ,     A__      ):
              __lowerCamelCase  =		0
              for i in range(A__    ,     min(block_start + block_size    ,     len(A__      )      )      ):
                     block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
              block_ints.append(A__      )
       return block_ints




def    lowerCamelCase__			(		A__			:   list[int]    ,     A__			:   int    ,     A__			:   int = DEFAULT_BLOCK_SIZE      ):





       '''simple docstring'''



       __lowerCamelCase  =		[]
       for block_int in block_ints:
              __lowerCamelCase  =		[]
              for i in range(block_size - 1    ,     -1    ,     -1      ):
                     if len(A__      ) + i < message_length:
                            __lowerCamelCase  =		block_int // (BYTE_SIZE**i)
                            __lowerCamelCase  =		block_int % (BYTE_SIZE**i)
                            block_message.insert(0    ,     chr(A__      )      )
              message.extend(A__      )
       return "".join(A__      )




def    lowerCamelCase__			(		A__			:   str    ,     A__			:   tuple[int, int]    ,     A__			:   int = DEFAULT_BLOCK_SIZE      ):





       '''simple docstring'''



       __lowerCamelCase  =		[]
       __lowerCamelCase,  __lowerCamelCase  =		key

       for block in get_blocks_from_text(A__    ,     A__      ):
              encrypted_blocks.append(pow(A__    ,     A__    ,     A__      )      )
       return encrypted_blocks




def    lowerCamelCase__			(		A__			:   list[int]    ,     A__			:   int    ,     A__			:   tuple[int, int]    ,     A__			:   int = DEFAULT_BLOCK_SIZE    ,     ):





       '''simple docstring'''



       __lowerCamelCase  =		[]
       __lowerCamelCase,  __lowerCamelCase  =		key
       for block in encrypted_blocks:
              decrypted_blocks.append(pow(A__    ,     A__    ,     A__      )      )
       return get_text_from_blocks(A__    ,     A__    ,     A__      )




def    lowerCamelCase__			(		A__			:   str      ):





       '''simple docstring'''



       with open(A__      ) as fo:
              __lowerCamelCase  =		fo.read()
       __lowerCamelCase,  __lowerCamelCase,  __lowerCamelCase  =		content.split(""","""      )
       return (int(A__      ), int(A__      ), int(A__      ))




def    lowerCamelCase__			(		A__			:   str    ,     A__			:   str    ,     A__			:   str    ,     A__			:   int = DEFAULT_BLOCK_SIZE    ,     ):





       '''simple docstring'''



       __lowerCamelCase,  __lowerCamelCase,  __lowerCamelCase  =		read_key_file(A__      )
       if key_size < block_size * 8:
              sys.exit(
                  """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
                  """requires the block size to be equal to or greater than the key size. """
                  """Either decrease the block size or use different keys.""".format(
                      block_size * 8    ,     A__      )      )

       __lowerCamelCase  =		[str(A__      ) for i in encrypt_message(A__    ,     (n, e)    ,     A__      )]

       __lowerCamelCase  =		""",""".join(A__      )
       __lowerCamelCase  =		f'{len(A__      )}_{block_size}_{encrypted_content}'
       with open(A__    ,     """w"""      ) as fo:
              fo.write(A__      )
       return encrypted_content




def    lowerCamelCase__			(		A__			:   str    ,     A__			:   str      ):





       '''simple docstring'''



       __lowerCamelCase,  __lowerCamelCase,  __lowerCamelCase  =		read_key_file(A__      )
       with open(A__      ) as fo:
              __lowerCamelCase  =		fo.read()
       __lowerCamelCase,  __lowerCamelCase,  __lowerCamelCase  =		content.split("""_"""      )
       __lowerCamelCase  =		int(A__      )
       __lowerCamelCase  =		int(A__      )

       if key_size < block_size * 8:
              sys.exit(
                  """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
                  """requires the block size to be equal to or greater than the key size. """
                  """Did you specify the correct key file and encrypted file?""".format(
                      block_size * 8    ,     A__      )      )

       __lowerCamelCase  =		[]
       for block in encrypted_message.split(""","""      ):
              encrypted_blocks.append(int(A__      )      )

       return decrypt_message(A__    ,     A__    ,     (n, d)    ,     A__      )




def    lowerCamelCase__			(		):





       '''simple docstring'''



       __lowerCamelCase  =		"""encrypted_file.txt"""
       __lowerCamelCase  =		input(R"""Encrypt\Decrypt [e\d]: """      )

       if response.lower().startswith("""e"""      ):
              __lowerCamelCase  =		"""encrypt"""
       elif response.lower().startswith("""d"""      ):
              __lowerCamelCase  =		"""decrypt"""

       if mode == "encrypt":
              if not os.path.exists("""rsa_pubkey.txt"""      ):
                     rkg.make_key_files("""rsa"""    ,     1024      )

              __lowerCamelCase  =		input("""\nEnter message: """      )
              __lowerCamelCase  =		"""rsa_pubkey.txt"""
              print(f'Encrypting and writing to {filename}...'      )
              __lowerCamelCase  =		encrypt_and_write_to_file(A__    ,     A__    ,     A__      )

              print("""\nEncrypted text:"""      )
              print(A__      )

       elif mode == "decrypt":
              __lowerCamelCase  =		"""rsa_privkey.txt"""
              print(f'Reading from {filename} and decrypting...'      )
              __lowerCamelCase  =		read_from_file_and_decrypt(A__    ,     A__      )
              print("""writing decryption to rsa_decryption.txt..."""      )
              with open("""rsa_decryption.txt"""    ,     """w"""      ) as dec:
                     dec.write(A__      )

              print("""\nDecryption:"""      )
              print(A__      )


if __name__ == "__main__":
       main()







import argparse
import json
import re
import string
import sys

import numpy as np


UpperCAmelCase_   							=      0.5




def    lowerCamelCase__			(		A__			:   Optional[Any]    ,     A__			:   Union[str, Any]      ):





       '''simple docstring'''



       __lowerCamelCase  =		[""".""", """,""", """;""", """:"""]

       for token in remove_tokens:
              __lowerCamelCase  =		ground_truth.replace(A__    ,     """"""      )
              __lowerCamelCase  =		prediction.replace(A__    ,     """"""      )

       __lowerCamelCase,  __lowerCamelCase  =		ground_truth.lower(), prediction.lower()
       __lowerCamelCase,  __lowerCamelCase  =		ground_truth.replace("""/"""    ,     """ """      ), prediction.replace("""/"""    ,     """ """      )
       __lowerCamelCase,  __lowerCamelCase  =		set(ground_truth.split(""" """      )      ), set(prediction.split(""" """      )      )

       __lowerCamelCase  =		ground_truth.intersection(A__      )
       __lowerCamelCase  =		ground_truth.union(A__      )
       __lowerCamelCase  =		len(A__      ) / len(A__      )
       return jaccard




def    lowerCamelCase__			(		A__			:   Optional[Any]      ):





       '''simple docstring'''



       def remove_articles(A__			:   Tuple      ):
              return re.sub(R"""\b(a|an|the)\b"""    ,     """ """    ,     A__      )

       def white_space_fix(A__			:   Optional[Any]      ):
              return " ".join(text.split()      )

       def remove_punc(A__			:   Optional[Any]      ):
              __lowerCamelCase  =		set(string.punctuation      )
              return "".join(ch for ch in text if ch not in exclude      )

       def lower(A__			:   Tuple      ):
              return text.lower()

       return white_space_fix(remove_articles(remove_punc(lower(A__      )      )      )      )




def    lowerCamelCase__			(		A__			:   Any    ,     A__			:   Optional[Any]    ,     A__			:   Optional[Any]      ):





       '''simple docstring'''



       __lowerCamelCase,  __lowerCamelCase,  __lowerCamelCase  =		0, 0, 0

       __lowerCamelCase  =		"""Parties""" in qa_id

       # first check if ground truth is empty
       if len(A__      ) == 0:
              if len(A__      ) > 0:
                     fp += len(A__      )  # false positive for each one
       else:
              for ground_truth in ground_truths:
                     assert len(A__      ) > 0
                     # check if there is a match
                     __lowerCamelCase  =		False
                     for pred in predictions:
                            if substr_ok:
                                   __lowerCamelCase  =		get_jaccard(A__    ,     A__      ) >= IOU_THRESH or ground_truth in pred
                            else:
                                   __lowerCamelCase  =		get_jaccard(A__    ,     A__      ) >= IOU_THRESH
                            if is_match:
                                   __lowerCamelCase  =		True

                     if match_found:
                            tp += 1
                     else:
                            fn += 1

        # now also get any fps by looping through preds
              for pred in predictions:
                     # Check if there's a match. if so, don't count (don't want to double count based on the above)
                     # but if there's no match, then this is a false positive.
                     # (Note: we get the true positives in the above loop instead of this loop so that we don't double count
                     # multiple predictions that are matched with the same answer.)
                     __lowerCamelCase  =		False
                     for ground_truth in ground_truths:
                            assert len(A__      ) > 0
                            if substr_ok:
                                   __lowerCamelCase  =		get_jaccard(A__    ,     A__      ) >= IOU_THRESH or ground_truth in pred
                            else:
                                   __lowerCamelCase  =		get_jaccard(A__    ,     A__      ) >= IOU_THRESH
                            if is_match:
                                   __lowerCamelCase  =		True

                     if not match_found:
                            fp += 1

       __lowerCamelCase  =		tp / (tp + fp) if tp + fp > 0 else np.nan
       __lowerCamelCase  =		tp / (tp + fn) if tp + fn > 0 else np.nan

       return precision, recall




def    lowerCamelCase__			(		A__			:   int      ):





       '''simple docstring'''



       __lowerCamelCase  =		precisions[::-1]
       for i in range(1    ,     len(A__      )      ):
              __lowerCamelCase  =		max(precision_best[i - 1]    ,     precision_best[i]      )
       __lowerCamelCase  =		precision_best[::-1]
       return precisions




def    lowerCamelCase__			(		A__			:   str    ,     A__			:   Union[str, Any]      ):





       '''simple docstring'''



       __lowerCamelCase  =		process_precisions(A__      )
       __lowerCamelCase  =		np.trapz(A__    ,     A__      )
       if np.isnan(A__      ):
              return 0
       return aupr




def    lowerCamelCase__			(		A__			:   Optional[Any]    ,     A__			:   List[str]    ,     A__			:   int      ):





       '''simple docstring'''



       __lowerCamelCase  =		process_precisions(A__      )
       __lowerCamelCase  =		0
       for prec, recall in zip(A__    ,     A__      ):
              if recall >= recall_thresh:
                     __lowerCamelCase  =		prec
                     break
       return prec_at_recall




def    lowerCamelCase__			(		A__			:   Optional[Any]    ,     A__			:   List[Any]      ):





       '''simple docstring'''



       return normalize_answer(A__      ) == normalize_answer(A__      )




def    lowerCamelCase__			(		A__			:   Tuple    ,     A__			:   int    ,     A__			:   Dict      ):





       '''simple docstring'''



       __lowerCamelCase  =		0
       for pred in predictions:
              for ground_truth in ground_truths:
                     __lowerCamelCase  =		metric_fn(A__    ,     A__      )
                     if score == 1:  # break the loop when one prediction matches the ground truth
                            break
              if score == 1:
                     break
       return score




def    lowerCamelCase__			(		A__			:   Union[str, Any]    ,     A__			:   Optional[Any]      ):





       '''simple docstring'''



       __lowerCamelCase  =		__lowerCamelCase  =		__lowerCamelCase  =		0
       __lowerCamelCase  =		[]
       __lowerCamelCase  =		[]
       for article in dataset:
              for paragraph in article["paragraphs"]:
                     for qa in paragraph["qas"]:
                            total += 1
                            if qa["id"] not in predictions:
                                   __lowerCamelCase  =		"""Unanswered question """ + qa["""id"""] + """ will receive score 0."""
                                   print(A__    ,     file=sys.stderr      )
                                   continue
                            __lowerCamelCase  =		[x["""text"""] for x in qa["""answers"""]]
                            __lowerCamelCase  =		predictions[qa["""id"""]]
                            __lowerCamelCase,  __lowerCamelCase  =		compute_precision_recall(A__    ,     A__    ,     qa["""id"""]      )

                            precisions.append(A__      )
                            recalls.append(A__      )

                            if precision == 0 and recall == 0:
                                   fa += 0
                            else:
                                   fa += 2 * (precision * recall) / (precision + recall)

                            exact_match += metric_max_over_ground_truths(A__    ,     A__    ,     A__      )

       __lowerCamelCase  =		[x for _, x in sorted(zip(A__    ,     A__      )      )]
       recalls.sort()

       __lowerCamelCase  =		100.0 * fa / total
       __lowerCamelCase  =		100.0 * exact_match / total
       __lowerCamelCase  =		get_aupr(A__    ,     A__      )

       __lowerCamelCase  =		get_prec_at_recall(A__    ,     A__    ,     recall_thresh=0.9      )
       __lowerCamelCase  =		get_prec_at_recall(A__    ,     A__    ,     recall_thresh=0.8      )

       return {
           "exact_match": exact_match,
           "f1": fa,
           "aupr": aupr,
           "prec_at_80_recall": prec_at_aa_recall,
           "prec_at_90_recall": prec_at_aa_recall,
       }


if __name__ == "__main__":
       UpperCAmelCase_   							=      argparse.ArgumentParser(description='Evaluation for CUAD')
       parser.add_argument('dataset_file', help='Dataset file')
       parser.add_argument('prediction_file', help='Prediction File')
       UpperCAmelCase_   							=      parser.parse_args()
       with open(args.dataset_file) as dataset_file:
              UpperCAmelCase_   							=      json.load(dataset_file)
              UpperCAmelCase_   							=      dataset_json['data']
       with open(args.prediction_file) as prediction_file:
              UpperCAmelCase_   							=      json.load(prediction_file)
       print(json.dumps(evaluate(dataset, predictions)))

