



import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
	from PIL import Image

	from transformers.image_utils import load_image
else:


	class 	__snake_case   :
			@staticmethod
			def 						SCREAMING_SNAKE_CASE_					(							*a_    ,**a_						):







							"""simple docstring"""
							pass







	def     UpperCAmelCase_		(					snake_case__					)	->     int:



					"""simple docstring"""





					return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
_lowerCAmelCase	:   int    =   (
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)


@is_pipeline_test
@require_torch
@require_vision
class 	__snake_case   ( unittest.TestCase ):
		SCREAMING_SNAKE_CASE__								=	MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
		@require_pytesseract
		@require_vision
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model=a_    ,tokenizer=a_    ,image_processor=a_						)

						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  list(zip(*apply_tesseract(load_image(a_						)    ,a_    ,''						)						)						)
						lowerCAmelCase__		  =  'What is the placebo?'
						lowerCAmelCase__		  =  [
						    {
						        'image': load_image(a_						),
						        'question': question,
						    },
						    {
						        'image': image,
						        'question': question,
						    },
						    {
						        'image': image,
						        'question': question,
						        'word_boxes': word_boxes,
						    },
						]
						return dqa_pipeline, examples
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  dqa_pipeline(a_    ,top_k=2						)
						self.assertEqual(
						    a_    ,[
						        [
						            {'score': ANY(a_						), 'answer': ANY(a_						), 'start': ANY(a_						), 'end': ANY(a_						)},
						            {'score': ANY(a_						), 'answer': ANY(a_						), 'start': ANY(a_						), 'end': ANY(a_						)},
						        ]
						    ]
						    * 3    ,)
		@require_torch
		@require_detectrona
		@require_pytesseract
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  pipeline('document-question-answering'    ,model='hf-internal-testing/tiny-random-layoutlmv2'						)
						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'How many cats are there?'

						lowerCAmelCase__		  =  [
						    {'score': 0.0001, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
						    {'score': 0.0001, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
						]
						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(nested_simplify(a_    ,decimals=4						)    ,a_						)

						lowerCAmelCase__		  =  dqa_pipeline({'image': image, 'question': question}    ,top_k=2						)
						self.assertEqual(nested_simplify(a_    ,decimals=4						)    ,a_						)

						# This image does not detect ANY text in it, meaning layoutlmv2 should fail.
						# Empty answer probably
						lowerCAmelCase__		  =  './tests/fixtures/tests_samples/COCO/000000039769.png'
						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(a_    ,[]						)

						# We can optionnally pass directly the words and bounding boxes
						lowerCAmelCase__		  =  './tests/fixtures/tests_samples/COCO/000000039769.png'
						lowerCAmelCase__		  =  []
						lowerCAmelCase__		  =  []
						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,words=a_    ,boxes=a_    ,top_k=2						)
						self.assertEqual(a_    ,[]						)
		@slow
		@require_torch
		@require_detectrona
		@require_pytesseract
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'    ,revision='9977165'    ,)
						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'What is the invoice number?'

						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline({'image': image, 'question': question}    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline(
						    [{'image': image, 'question': question}, {'image': image, 'question': question}]    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        [
						            {'score': 0.9944, 'answer': 'us-001', 'start': 16, 'end': 16},
						            {'score': 0.0009, 'answer': 'us-001', 'start': 16, 'end': 16},
						        ],
						    ]
						    * 2    ,)
		@slow
		@require_torch
		@require_detectrona
		@require_pytesseract
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'    ,revision='9977165'    ,max_seq_len=50    ,)
						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'What is the invoice number?'

						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
						        {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline({'image': image, 'question': question}    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
						        {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline(
						    [{'image': image, 'question': question}, {'image': image, 'question': question}]    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        [
						            {'score': 0.9974, 'answer': '1110212019', 'start': 23, 'end': 23},
						            {'score': 0.9948, 'answer': 'us-001', 'start': 16, 'end': 16},
						        ]
						    ]
						    * 2    ,)
		@slow
		@require_torch
		@require_pytesseract
		@require_vision
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  AutoTokenizer.from_pretrained(
						    'impira/layoutlm-document-qa'    ,revision='3dc6de3'    ,add_prefix_space=a_						)
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model='impira/layoutlm-document-qa'    ,tokenizer=a_    ,revision='3dc6de3'    ,)
						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'What is the invoice number?'

						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline({'image': image, 'question': question}    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline(
						    [{'image': image, 'question': question}, {'image': image, 'question': question}]    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        [
						            {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
						            {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
						        ]
						    ]
						    * 2    ,)

						lowerCAmelCase__		  =  list(zip(*apply_tesseract(load_image(a_						)    ,a_    ,''						)						)						)

						# This model should also work if `image` is set to None
						lowerCAmelCase__		  =  dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.4251, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.0819, 'answer': '1110212019', 'start': 23, 'end': 23},
						    ]    ,)
		@slow
		@require_torch
		@require_pytesseract
		@require_vision
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  AutoTokenizer.from_pretrained(
						    'impira/layoutlm-document-qa'    ,revision='3dc6de3'    ,add_prefix_space=a_						)
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model='impira/layoutlm-document-qa'    ,tokenizer=a_    ,revision='3dc6de3'    ,max_seq_len=50    ,)
						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'What is the invoice number?'

						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)

						lowerCAmelCase__		  =  dqa_pipeline(
						    [{'image': image, 'question': question}, {'image': image, 'question': question}]    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        [
						            {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
						            {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
						        ]
						    ]
						    * 2    ,)

						lowerCAmelCase__		  =  list(zip(*apply_tesseract(load_image(a_						)    ,a_    ,''						)						)						)

						# This model should also work if `image` is set to None
						lowerCAmelCase__		  =  dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}    ,top_k=2						)
						self.assertEqual(
						    nested_simplify(a_    ,decimals=4						)    ,[
						        {'score': 0.9999, 'answer': 'us-001', 'start': 16, 'end': 16},
						        {'score': 0.9998, 'answer': 'us-001', 'start': 16, 'end': 16},
						    ]    ,)
		@slow
		@require_torch
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  pipeline(
						    'document-question-answering'    ,model='naver-clova-ix/donut-base-finetuned-docvqa'    ,tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa'						)    ,feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa'    ,)

						lowerCAmelCase__		  =  INVOICE_URL
						lowerCAmelCase__		  =  'What is the invoice number?'
						lowerCAmelCase__		  =  dqa_pipeline(image=a_    ,question=a_    ,top_k=2						)
						self.assertEqual(nested_simplify(a_    ,decimals=4						)    ,[{'answer': 'us-001'}]						)



		@require_tf
		@unittest.skip('Document question answering not implemented in TF'						)
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						pass





from __future__ import annotations

import json

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

_lowerCAmelCase	:   List[str]    =   {"UserAgent": UserAgent().random}







def     UpperCAmelCase_		(					snake_case__					)	->     dict:



				"""simple docstring"""





				lowerCAmelCase__		  =  script.contents[0]
				lowerCAmelCase__		  =  json.loads(data[data.find('{"config"'					) : -1]					)
				return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]


class 	__snake_case   :
		def __init__(							self    ,a_						):







						"""simple docstring"""
						lowerCAmelCase__		  =  f'https://www.instagram.com/{username}/'
						lowerCAmelCase__		  =  self.get_json()
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						lowerCAmelCase__		  =  requests.get(self.url    ,headers=a_						).text
						lowerCAmelCase__		  =  BeautifulSoup(a_    ,'html.parser'						).find_all('script'						)
						try:
										return extract_user_profile(scripts[4]						)
						except (json.decoder.JSONDecodeError, KeyError):
										return extract_user_profile(scripts[3]						)
		def __repr__(							self						):







						"""simple docstring"""
						return f'{self.__class__.__name__}(\'{self.username}\')'
		def __str__(							self						):







						"""simple docstring"""
						return f'{self.fullname} ({self.username}) is {self.biography}'
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["username"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["full_name"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["biography"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["business_email"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["external_url"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_followed_by"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_follow"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["edge_owner_to_timeline_media"]["count"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["profile_pic_url_hd"]
		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["is_verified"]



		@property
		def 						SCREAMING_SNAKE_CASE_					(							self						):







						"""simple docstring"""
						return self.user_data["is_private"]







def     UpperCAmelCase_		(					snake_case__ = "github"					)	->     None:



				"""simple docstring"""





				import os

				if os.environ.get('CI'					):
								return  # test failing on GitHub Actions
				lowerCAmelCase__		  =  InstagramUser(snake_case__					)
				assert instagram_user.user_data
				assert isinstance(instagram_user.user_data    ,			snake_case__					)
				assert instagram_user.username == username
				if username != "github":
								return
				assert instagram_user.fullname == "GitHub"
				assert instagram_user.biography == "Built for developers."
				assert instagram_user.number_of_posts > 150
				assert instagram_user.number_of_followers > 120000
				assert instagram_user.number_of_followings > 15
				assert instagram_user.email == "support@github.com"
				assert instagram_user.website == "https://github.com/readme"
				assert instagram_user.profile_picture_url.startswith('https://instagram.'					)
				assert instagram_user.is_verified is True
				assert instagram_user.is_private is False


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	_lowerCAmelCase	:   Optional[int]    =   InstagramUser("github")
	print(instagram_user)
	print(f"""{instagram_user.number_of_posts = }""")
	print(f"""{instagram_user.number_of_followers = }""")
	print(f"""{instagram_user.number_of_followings = }""")
	print(f"""{instagram_user.email = }""")
	print(f"""{instagram_user.website = }""")
	print(f"""{instagram_user.profile_picture_url = }""")
	print(f"""{instagram_user.is_verified = }""")
	print(f"""{instagram_user.is_private = }""")
