code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class TurnstileTest(AbstractTest): def test_all_params(self): params = { 'sitekey' : '0x4AAAAAAAC3DHQFLr1GavRN', 'url' : 'https://www.site.com/page/', 'action' : 'foo', 'data' : 'bar' } sends = { 'method' : 'turnstile', 'sitekey' : '0x4AAAAAAAC3DHQFLr1GavRN', 'action' : 'foo', 'data' : 'bar', 'pageurl' : 'https://www.site.com/page/', } return self.send_return(sends, self.solver.turnstile, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_turnstile.py
test_turnstile.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class CapyTest(AbstractTest): def test_all_params(self): params = { 'sitekey' : 'PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v', 'url' : 'http://mysite.com/', } sends = { 'method' : 'capy', 'captchakey' : 'PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v', 'pageurl' : 'http://mysite.com/', } return self.send_return(sends, self.solver.capy, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_capy.py
test_capy.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class RecaptchaTest(AbstractTest): def test_v2(self): params = { 'sitekey' : '6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-', 'url' : 'https://mysite.com/page/with/recaptcha', 'invisible' : 1, 'action' : 'verify', 'datas' : 'Crb7VsRAQaBqoaQQtHQQ' } sends = { 'method' : 'userrecaptcha', 'googlekey' : '6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-', 'pageurl' : 'https://mysite.com/page/with/recaptcha', 'invisible': 1, 'enterprise': 0, 'action' : 'verify', 'version' : 'v2', 'data-s' : 'Crb7VsRAQaBqoaQQtHQQ' } return self.send_return(sends, self.solver.recaptcha, **params) def test_v3(self): params = { 'sitekey' : '6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-', 'url' : 'https://mysite.com/page/with/recaptcha', 'invisible' : 1, 'action' : 'verify', 'version' : 'v3', } sends = { 'method' : 'userrecaptcha', 'googlekey' : '6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-', 'pageurl' : 'https://mysite.com/page/with/recaptcha', 'invisible' : 1, 'enterprise': 0, 'action' : 'verify', 'version' : 'v3', } return self.send_return(sends, self.solver.recaptcha, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_recaptcha.py
test_recaptcha.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class KeyCaptchaTest(AbstractTest): def test_all_params(self): params = { 's_s_c_user_id' : 10, 's_s_c_session_id' : '493e52c37c10c2bcdf4a00cbc9ccd1e8', 's_s_c_web_server_sign' : '9006dc725760858e4c0715b835472f22-pz-', 's_s_c_web_server_sign2' : '2ca3abe86d90c6142d5571db98af6714', 'url' : 'https://www.keycaptcha.ru/demo-magnetic/', } sends = { 'method' : 'keycaptcha', 's_s_c_user_id' : 10, 's_s_c_session_id' : '493e52c37c10c2bcdf4a00cbc9ccd1e8', 's_s_c_web_server_sign' : '9006dc725760858e4c0715b835472f22-pz-', 's_s_c_web_server_sign2' : '2ca3abe86d90c6142d5571db98af6714', 'pageurl' : 'https://www.keycaptcha.ru/demo-magnetic/', } return self.send_return(sends, self.solver.keycaptcha, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_keycaptcha.py
test_keycaptcha.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class HcaptchaTest(AbstractTest): def test_all_params(self): params = { 'sitekey' : 'f1ab2cdefa3456789012345b6c78d90e', 'url' : 'https://www.site.com/page/', } sends = { 'method' : 'hcaptcha', 'sitekey' : 'f1ab2cdefa3456789012345b6c78d90e', 'pageurl' : 'https://www.site.com/page/', } return self.send_return(sends, self.solver.hcaptcha, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_hcaptcha.py
test_hcaptcha.py
#!/usr/bin/env python3 import unittest file = '../examples/images/normal.jpg' hint_img = '../examples/images/grid_hint.jpg' try: from .abstract import AbstractTest file = file[3:] hint_img = hint_img[3:] except ImportError: from abstract import AbstractTest class NormalTest(AbstractTest): def test_file(self): sends = {'method': 'post', 'file': file} return self.send_return(sends, self.solver.normal, file=file) # def test_file_params(self): # return self.test_send_return(self.method, self.file, method='post') def test_base64(self): b64 = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' sends = { 'method': 'base64', 'body' : b64, } return self.send_return(sends, self.solver.normal, file=b64) def test_all_params(self): params = { 'numeric' : 4, 'minLen' : 4, 'maxLen' : 20, 'phrase' : 1, 'caseSensitive' : 1, 'calc' : 0, 'lang' : 'en', 'hintImg' : hint_img, 'hintText' : 'Type red symbols only', } sends = { 'files' : {'file': file,'imginstructions': hint_img}, 'method' : 'post', 'numeric' : 4, 'min_len' : 4, 'max_len' : 20, 'phrase' : 1, 'regsense' : 1, 'calc' : 0, 'lang' : 'en', 'textinstructions' : 'Type red symbols only', } # files = { # 'file' : file, # 'imginstructions' : hint, # } return self.send_return(sends, self.solver.normal, file=file, **params) def test_not_found(self): return self.invalid_file(self.solver.normal) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_normal.py
test_normal.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class GeeTest(AbstractTest): def test_all_params(self): params = { 'gt' : 'f2ae6cadcf7886856696502e1d55e00c', 'apiServer' : 'api-na.geetest.com', 'challenge' : '69A21A01-CC7B-B9C6-0F9A-E7FA06677FFC', 'url' : 'https://launches.endclothing.com/distil_r_captcha.html', } sends = { 'method' : 'geetest', 'gt' : 'f2ae6cadcf7886856696502e1d55e00c', 'api_server' : 'api-na.geetest.com', 'challenge' : '69A21A01-CC7B-B9C6-0F9A-E7FA06677FFC', 'pageurl' : 'https://launches.endclothing.com/distil_r_captcha.html', } return self.send_return(sends, self.solver.geetest, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_geetest.py
test_geetest.py
#!/usr/bin/env python3 import unittest files = ['../examples/images/rotate.jpg'] hint_img = '../examples/images/grid_hint.jpg' hint_text = 'Put the images in the correct way up' try: from .abstract import AbstractTest files = [f[3:] for f in files] hint_img = hint_img[3:] except ImportError: from abstract import AbstractTest files_dict = {f'file_{e+1}': f for e, f in enumerate(files)} checks = {'method' : 'rotatecaptcha'} class RotateTest(AbstractTest): def test_single_file(self): sends = {'method': 'post', 'file': files[0], **checks} return self.send_return(sends, self.solver.rotate, files=files[0]) def test_file_param(self): sends = {'method': 'post', 'files': {'file_1': files[0]}, **checks} return self.send_return(sends, self.solver.rotate, files=files[:1]) def test_files_list(self): sends = {'method': 'post', 'files': files_dict, **checks} return self.send_return(sends, self.solver.rotate, files=files) def test_files_dict(self): sends = {'method': 'post', 'files': files_dict, **checks} return self.send_return(sends, self.solver.rotate, files=files_dict) def test_all_params(self): params = { 'angle' : 40, 'lang' : 'en', 'hintImg' : hint_img, 'hintText' : hint_text } sends = { 'method' : 'rotatecaptcha', 'angle' : 40, 'lang' : 'en', 'textinstructions' : hint_text, 'files' : {'file': files[0],'imginstructions': hint_img}, **checks } return self.send_return(sends, self.solver.rotate, file=files[0], **params) def test_not_found(self): return self.invalid_file(self.solver.rotate) def test_too_many(self): return self.too_many_files(self.solver.rotate) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_rotate.py
test_rotate.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class AmazonWAFTest(AbstractTest): def test_all_params(self): params = { 'sitekey' : 'AQIDAHjcYu/GjX+QlghicBgQ/7bFaQZ+m5FKCMDnO+vTbNg96AFsClhVgr5q0UFRdXhhHEwiAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMLMbH8d6uQSrYTraoAgEQgDvtSNxdEyG7Zu393cHyPdWNCZgeIB52+W7fCTI8U5z15z1NdPUdnB1ZHoK7ewpwoSMm5mzkJJld0cnvGw==', 'url' : 'https://www.site.com/page/', 'iv' : 'CgAAYDJb9CAAACAq', 'context' : 'wCho9T9OcETTT8fu1k6+rszr5aGt4eLd+K3mHpV8VbSkjAWJGJx/iQ16RKDCTQBtU5OSeE+SQqoS5iTzhgGtvwgmBbr7X/I+aXaNfb2JRZ8eJ7CnQpM9QRwnv7vGgrGRBGhkh/jaVYmXdy0j0x21s3dCBlA4VN3naDHIweZqkyhXqJBNI1Ep8OMSnhXtPebboB117aBW4IU4XEOii8EE1G4Z7ndWhrNVVXYYwVoxfnSqfYX//CJir6dZfLMbCt5t7NnO8yjsx/YHGVXFVBt2Zrj0ZTxowoYbHU/BKyFaXgUj+ZQ=' } sends = { 'method' : 'amazon_waf', 'sitekey' : 'AQIDAHjcYu/GjX+QlghicBgQ/7bFaQZ+m5FKCMDnO+vTbNg96AFsClhVgr5q0UFRdXhhHEwiAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMLMbH8d6uQSrYTraoAgEQgDvtSNxdEyG7Zu393cHyPdWNCZgeIB52+W7fCTI8U5z15z1NdPUdnB1ZHoK7ewpwoSMm5mzkJJld0cnvGw==', 'iv' : 'CgAAYDJb9CAAACAq', 'context' : 'wCho9T9OcETTT8fu1k6+rszr5aGt4eLd+K3mHpV8VbSkjAWJGJx/iQ16RKDCTQBtU5OSeE+SQqoS5iTzhgGtvwgmBbr7X/I+aXaNfb2JRZ8eJ7CnQpM9QRwnv7vGgrGRBGhkh/jaVYmXdy0j0x21s3dCBlA4VN3naDHIweZqkyhXqJBNI1Ep8OMSnhXtPebboB117aBW4IU4XEOii8EE1G4Z7ndWhrNVVXYYwVoxfnSqfYX//CJir6dZfLMbCt5t7NnO8yjsx/YHGVXFVBt2Zrj0ZTxowoYbHU/BKyFaXgUj+ZQ=', 'pageurl' : 'https://www.site.com/page/', } return self.send_return(sends, self.solver.amazon_waf, **params) if __name__ == '__main__': unittest.main() # sitekey='AQIDAHjcYu/GjX+QlghicBgQ/7bFaQZ+m5FKCMDnO+vTbNg96AFsClhVgr5q0UFRdXhhHEwiAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMLMbH8d6uQSrYTraoAgEQgDvtSNxdEyG7Zu393cHyPdWNCZgeIB52+W7fCTI8U5z15z1NdPUdnB1ZHoK7ewpwoSMm5mzkJJld0cnvGw==', # iv='CgAAYDJb9CAAACAq', # context='wCho9T9OcETTT8fu1k6+rszr5aGt4eLd+K3mHpV8VbSkjAWJGJx/iQ16RKDCTQBtU5OSeE+SQqoS5iTzhgGtvwgmBbr7X/I+aXaNfb2JRZ8eJ7CnQpM9QRwnv7vGgrGRBGhkh/jaVYmXdy0j0x21s3dCBlA4VN3naDHIweZqkyhXqJBNI1Ep8OMSnhXtPebboB117aBW4IU4XEOii8EE1G4Z7ndWhrNVVXYYwVoxfnSqfYX//CJir6dZfLMbCt5t7NnO8yjsx/YHGVXFVBt2Zrj0ZTxowoYbHU/BKyFaXgUj+ZQ=', # url='https://efw47fpad9.execute-api.us-east-1.amazonaws.com/latest',
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_amazon_waf.py
test_amazon_waf.py
#!/usr/bin/env python3 import unittest try: from .abstract import AbstractTest except ImportError: from abstract import AbstractTest class LeminTest(AbstractTest): def test_all_params(self): params = { 'captcha_id' : 'CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d', 'div_id' : 'lemin-cropped-captcha', 'api_server' : 'https://api.leminnow.com/', 'url' : 'http://mysite.com/', } sends = { 'method' : 'lemin', 'captcha_id' : 'CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d', 'div_id' : 'lemin-cropped-captcha', 'api_server' : 'https://api.leminnow.com/', 'pageurl' : 'http://mysite.com/', } return self.send_return(sends, self.solver.lemin, **params) if __name__ == '__main__': unittest.main()
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/tests/test_lemin.py
test_lemin.py
#!/usr/bin/env python3 import os, sys import time import requests from base64 import b64encode try: from .api import ApiClient except ImportError: from api import ApiClient class SolverExceptions(Exception): pass class ValidationException(SolverExceptions): pass class NetworkException(SolverExceptions): pass class ApiException(SolverExceptions): pass class TimeoutException(SolverExceptions): pass class TwoCaptcha(): def __init__(self, apiKey, softId=None, callback=None, defaultTimeout=120, recaptchaTimeout=600, pollingInterval=10, server = '2captcha.com'): self.API_KEY = apiKey self.soft_id = softId self.callback = callback self.default_timeout = defaultTimeout self.recaptcha_timeout = recaptchaTimeout self.polling_interval = pollingInterval self.api_client = ApiClient(post_url = str(server)) self.max_files = 9 self.exceptions = SolverExceptions def normal(self, file, **kwargs): ''' Wrapper for solving normal captcha (image) Required: file (image, base64, or url) Optional params: phrase numeric minLen maxLen phrase caseSensitive calc lang hintText hintImg softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' method = self.get_method(file) result = self.solve(**method, **kwargs) return result def text(self, text, **kwargs): ''' Wrapper for solving text captcha Required: text Optional params: lang softId callback ''' result = self.solve(text=text, method='post', **kwargs) return result def recaptcha(self, sitekey, url, version='v2', enterprise=0, **kwargs): ''' Wrapper for solving recaptcha (v2, v3) Required: sitekey url Optional params: invisible version enterprise action score softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' params = { 'googlekey': sitekey, 'url': url, 'method': 'userrecaptcha', 'version': version, 'enterprise': enterprise, **kwargs, } result = self.solve(timeout=self.recaptcha_timeout, **params) return result def funcaptcha(self, sitekey, url, **kwargs): ''' Wrapper for solving funcaptcha Required: sitekey url Optional params: surl userAgent softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) **{'data[key]': 'anyStringValue'} ''' result = self.solve(publickey=sitekey, url=url, method='funcaptcha', **kwargs) return result def geetest(self, gt, challenge, url, **kwargs): ''' Wrapper for solving geetest captcha Required: gt challenge url Optional params: apiServer softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' result = self.solve(gt=gt, challenge=challenge, url=url, method='geetest', **kwargs) return result def hcaptcha(self, sitekey, url, **kwargs): ''' Wrapper for solving hcaptcha Required: sitekey url Optional params: invisible data softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' result = self.solve(sitekey=sitekey, url=url, method='hcaptcha', **kwargs) return result def keycaptcha(self, s_s_c_user_id, s_s_c_session_id, s_s_c_web_server_sign, s_s_c_web_server_sign2, url, **kwargs): ''' Wrapper for solving Required: s_s_c_user_id s_s_c_session_id s_s_c_web_server_sign s_s_c_web_server_sign2 url Optional params: softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' params = { 's_s_c_user_id': s_s_c_user_id, 's_s_c_session_id': s_s_c_session_id, 's_s_c_web_server_sign': s_s_c_web_server_sign, 's_s_c_web_server_sign2': s_s_c_web_server_sign2, 'url': url, 'method': 'keycaptcha', **kwargs, } result = self.solve(**params) return result def capy(self, sitekey, url, **kwargs): ''' Wrapper for solving capy Required: sitekey url Optional params: softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' result = self.solve(captchakey=sitekey, url=url, method='capy', **kwargs) return result def grid(self, file, **kwargs): ''' Wrapper for solving grid captcha (image) Required: file (image or base64) Optional params: rows cols previousId canSkip lang hintImg hintText softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' method = self.get_method(file) params = { 'recaptcha': 1, **method, **kwargs, } result = self.solve(**params) return result def canvas(self, file, **kwargs): ''' Wrapper for solving canvas captcha (image) Required: file (image or base64) Optional params: previousId canSkip lang hintImg hintText softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' if not ('hintText' in kwargs or 'hintImg' in kwargs): raise ValidationException( 'parameters required: hintText and/or hintImg') method = self.get_method(file) params = { 'recaptcha': 1, 'canvas': 1, **method, **kwargs, } result = self.solve(**params) return result def coordinates(self, file, **kwargs): ''' Wrapper for solving coordinates captcha (image) Required: file (image or base64) Optional params: hintImg hintText lang softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' method = self.get_method(file) params = { 'coordinatescaptcha': 1, **method, **kwargs, } result = self.solve(**params) return result def rotate(self, files, **kwargs): ''' Wrapper for solving rotate captcha (image) Required: files (images) Optional params: angle lang hintImg hintText softId callback proxy = {'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) ''' if isinstance(files, str): file = self.get_method(files)['file'] result = self.solve(file=file, method='rotatecaptcha', **kwargs) return result elif isinstance(files, dict): files = list(files.values()) files = self.extract_files(files) result = self.solve(files=files, method='rotatecaptcha', **kwargs) return result def geetest_v4(self, captcha_id, url, **kwargs): ''' Wrapper for solving geetest_v4 captcha Required: captcha_id url Optional params: ''' result = self.solve(captcha_id=captcha_id, url=url, method='geetest_v4', **kwargs) return result def lemin(self, captcha_id, div_id, url, **kwargs): ''' Wrapper for solving Lemin Cropped Captcha Required: captcha_id div_id url Optional params: ''' result = self.solve(captcha_id=captcha_id, div_id=div_id, url=url, method='lemin', **kwargs) return result def turnstile(self, sitekey, url, **kwargs): ''' Wrapper for solving Cloudflare Turnstile Required: sitekey url Optional params: action data ''' result = self.solve(sitekey=sitekey, url=url, method='turnstile', **kwargs) return result def amazon_waf(self, sitekey, iv, context, url, **kwargs): ''' Wrapper for solving Amazon WAF Required: sitekey iv context url Optional params: ''' result = self.solve(sitekey=sitekey, iv=iv, context=context, url=url, method='amazon_waf', **kwargs) return result def solve(self, timeout=0, polling_interval=0, **kwargs): ''' sends captcha, receives result Parameters ---------- timeout : float polling_interval : int **kwargs : all captcha params Returns ------- result : string ''' id_ = self.send(**kwargs) result = {'captchaId': id_} if self.callback is None: timeout = float(timeout or self.default_timeout) sleep = int(polling_interval or self.polling_interval) code = self.wait_result(id_, timeout, sleep) result.update({'code': code}) return result def wait_result(self, id_, timeout, polling_interval): max_wait = time.time() + timeout while time.time() < max_wait: try: return self.get_result(id_) except NetworkException: time.sleep(polling_interval) raise TimeoutException(f'timeout {timeout} exceeded') def get_method(self, file): if not file: raise ValidationException('File required') if not '.' in file and len(file) > 50: return {'method': 'base64', 'body': file} if file.startswith('http'): img_resp = requests.get(file) if img_resp.status_code != 200: raise ValidationException(f'File could not be downloaded from url: {file}') return {'method': 'base64', 'body': b64encode(img_resp.content).decode('utf-8')} if not os.path.exists(file): raise ValidationException(f'File not found: {file}') return {'method': 'post', 'file': file} def send(self, **kwargs): params = self.default_params(kwargs) params = self.rename_params(params) params, files = self.check_hint_img(params) response = self.api_client.in_(files=files, **params) if not response.startswith('OK|'): raise ApiException(f'cannot recognize response {response}') return response[3:] def get_result(self, id_): response = self.api_client.res(key=self.API_KEY, action='get', id=id_) if response == 'CAPCHA_NOT_READY': raise NetworkException if not response.startswith('OK|'): raise ApiException(f'cannot recognize response {response}') return response[3:] def balance(self): ''' get my balance Returns ------- balance : float ''' response = self.api_client.res(key=self.API_KEY, action='getbalance') return float(response) def report(self, id_, correct): ''' report of solved captcha: good/bad Parameters ---------- id_ : captcha ID correct : True/False Returns ------- None. ''' rep = 'reportgood' if correct else 'reportbad' self.api_client.res(key=self.API_KEY, action=rep, id=id_) return def rename_params(self, params): replace = { 'caseSensitive': 'regsense', 'minLen': 'min_len', 'maxLen': 'max_len', 'minLength': 'min_len', 'maxLength': 'max_len', 'hintText': 'textinstructions', 'hintImg': 'imginstructions', 'url': 'pageurl', 'score': 'min_score', 'text': 'textcaptcha', 'rows': 'recaptcharows', 'cols': 'recaptchacols', 'previousId': 'previousID', 'canSkip': 'can_no_answer', 'apiServer': 'api_server', 'softId': 'soft_id', 'callback': 'pingback', 'datas': 'data-s', } new_params = { v: params.pop(k) for k, v in replace.items() if k in params } proxy = params.pop('proxy', '') proxy and new_params.update({ 'proxy': proxy['uri'], 'proxytype': proxy['type'] }) new_params.update(params) return new_params def default_params(self, params): params.update({'key': self.API_KEY}) callback = params.pop('callback', self.callback) soft_id = params.pop('softId', self.soft_id) if callback: params.update({'callback': callback}) if soft_id: params.update({'softId': soft_id}) self.has_callback = bool(callback) return params def extract_files(self, files): if len(files) > self.max_files: raise ValidationException( f'Too many files (max: {self.max_files})') not_exists = [f for f in files if not (os.path.exists(f))] if not_exists: raise ValidationException(f'File not found: {not_exists}') files = {f'file_{e+1}': f for e, f in enumerate(files)} return files def check_hint_img(self, params): hint = params.pop('imginstructions', None) files = params.pop('files', {}) if not hint: return params, files if not '.' in hint and len(hint) > 50: return params, files if not os.path.exists(hint): raise ValidationException(f'File not found: {hint}') if not files: files = {'file': params.pop('file', {})} files.update({'imginstructions': hint}) return params, files if __name__ == '__main__': key = sys.argv[1] sol = TwoCaptcha(key)
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/twocaptcha/solver.py
solver.py
#!/usr/bin/env python3 import requests class NetworkException(Exception): pass class ApiException(Exception): pass class ApiClient(): def __init__(self, post_url = '2captcha.com'): self.post_url = post_url def in_(self, files={}, **kwargs): ''' sends POST-request (files and/or params) to solve captcha Parameters ---------- files : TYPE, optional DESCRIPTION. The default is {}. **kwargs : TYPE DESCRIPTION. Raises ------ NetworkException DESCRIPTION. ApiException DESCRIPTION. Returns ------- resp : TYPE DESCRIPTION. ''' try: current_url = 'https://'+self.post_url+'/in.php' if files: files = {key: open(path, 'rb') for key, path in files.items()} resp = requests.post(current_url, data=kwargs, files=files) [f.close() for f in files.values()] elif 'file' in kwargs: with open(kwargs.pop('file'), 'rb') as f: resp = requests.post(current_url, data=kwargs, files={'file': f}) else: resp = requests.post(current_url, data=kwargs) except requests.RequestException as e: raise NetworkException(e) if resp.status_code != 200: raise NetworkException(f'bad response: {resp.status_code}') resp = resp.content.decode('utf-8') if 'ERROR' in resp: raise ApiException(resp) return resp def res(self, **kwargs): ''' sends additional GET-requests (solved captcha, balance, report etc.) Parameters ---------- **kwargs : TYPE DESCRIPTION. Raises ------ NetworkException DESCRIPTION. ApiException DESCRIPTION. Returns ------- resp : TYPE DESCRIPTION. ''' try: current_url_out = 'https://'+self.post_url+'/res.php' resp = requests.get(current_url_out, params=kwargs) if resp.status_code != 200: raise NetworkException(f'bad response: {resp.status_code}') resp = resp.content.decode('utf-8') if 'ERROR' in resp: raise ApiException(resp) except requests.RequestException as e: raise NetworkException(e) return resp
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/twocaptcha/api.py
api.py
from .api import ApiClient from .solver import (TwoCaptcha, SolverExceptions, ValidationException, NetworkException, ApiException, TimeoutException) __version__ = '1.2.1'
2captcha-python
/2captcha-python-1.2.1.tar.gz/2captcha-python-1.2.1/twocaptcha/__init__.py
__init__.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=120, pollingInterval=5) try: result = solver.coordinates('./images/grid_2.jpg', lang='en', hintImg='./images/grid_hint.jpg', hintText='Select all images with an Orange') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/coordinates_options.py
coordinates_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) !!!! try: result = solver.keycaptcha( s_s_c_user_id=15, s_s_c_session_id='faa8cc1697c962ad4b859aa472f5d992', s_s_c_web_server_sign='4f84e4fe41cf688d8d94361489ecd75c-pz-', s_s_c_web_server_sign2='a9af97bb0a645eec495f2527e431a21b', url='https://www.keycaptcha.com/products/') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/keycaptcha.py
keycaptcha.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.hcaptcha( sitekey='3ceb8624-1970-4e6b-91d5-70317b70b651', url='https://2captcha.com/demo/hcaptcha?difficulty=easy', ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/hcaptcha.py
hcaptcha.py
import sys import os from base64 import b64encode sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) with open('images/canvas.jpg', 'rb') as f: b64 = b64encode(f.read()).decode('utf-8') try: result = solver.canvas(b64, hintText='Draw around apple') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/canvas_base64.py
canvas_base64.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=30, pollingInterval=5) try: result = solver.capy(sitekey='PUZZLE_Cz04hZLjuZRMYC3ee10C32D3uNms5w', url='https://www.mysite.com/captcha/', api_server="https://jp.api.capy.me/", softId=33112) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/capy_options.py
capy_options.py
import sys '../../' in sys.path or sys.path.append('../../../') from twocaptcha import TwoCaptcha sol = TwoCaptcha('YOUR_API_KEY', defaultTimeout=120) try: result = sol.keycaptcha(s_s_c_user_id = 10, s_s_c_session_id = '493e52c37c10c2bcdf4a00cbc9ccd1e8', s_s_c_web_server_sign = '9006dc725760858e4c0715b835472f22-pz-', s_s_c_web_server_sign2 = '2ca3abe86d90c6142d5571db98af6714', url = 'https://www.keycaptcha.ru/demo-magnetic/', proxy = { 'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'}) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/keycaptcha_options.py
keycaptcha_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.coordinates('./images/grid.jpg') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/coordinates.py
coordinates.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') config = { 'server': '2captcha.com', # can be also set to 'rucaptcha.com' 'apiKey': api_key, 'softId': 123, # 'callback': 'https://your.site/result-receiver', # if set, sovler with just return captchaId, not polling API for the answer 'defaultTimeout': 120, 'recaptchaTimeout': 600, 'pollingInterval': 10, } solver = TwoCaptcha(**config) try: result = solver.recaptcha( sitekey='6LfDxboZAAAAAD6GHukjvUy6lszoeG3H4nQW57b6', url='https://2captcha.com/demo/recaptcha-v2-invisible?level=low', invisible=1, enterprise=0 # proxy={ # 'type': 'HTTPS', # 'uri': 'login:password@IP_address:PORT' # } ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/recaptcha_v2_options.py
recaptcha_v2_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=120, pollingInterval=5, server='2captcha.com') try: result = solver.canvas( './images/canvas.jpg', previousId=0, canSkip=0, lang='en', hintImg='./images/canvas_hint.jpg', hintText='Draw around apple', ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/canvas_options.py
canvas_options.py
import sys import os import requests sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=300, pollingInterval=10) resp = requests.get("https://www.mysite.com/distil_r_captcha_challenge") challenge = resp.content.decode('utf-8').split(';')[0] try: result = solver.geetest( gt='f3bf6dbdcf7886856696502e1d55e00c', apiServer='api-na.geetest.com', challenge=challenge, url='https://www.mysite.com/distil_r_captcha.html', # proxy={ # 'type': 'HTTPS', # 'uri': 'login:password@IP_address:PORT' # } ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/geetest_options.py
geetest_options.py
import sys import os from base64 import b64encode sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) with open('images/grid.jpg', 'rb') as f: b64 = b64encode(f.read()).decode('utf-8') try: result = solver.coordinates(b64) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/coordinates_base64.py
coordinates_base64.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=100, pollingInterval=12) try: result = solver.grid( file='images/grid_2.jpg', rows=3, cols=3, previousId=0, canSkip=0, lang='en', hintImg='./images/grid_hint.jpg', # hintText='Select all images with an Orange', ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/grid_options.py
grid_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.rotate('./images/rotate.jpg') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/rotate.py
rotate.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') config = { 'server': '2captcha.com', # can be also set to 'rucaptcha.com' 'apiKey': api_key, 'softId': 123, # 'callback': 'https://your.site/result-receiver', # if set, sovler with just return captchaId, not polling API for the answer 'defaultTimeout': 120, 'recaptchaTimeout': 600, 'pollingInterval': 10, } solver = TwoCaptcha(**config) try: result = solver.recaptcha( sitekey='6LfdxboZAAAAAMtnONIt4DJ8J1t4wMC-kVG02zIO', url='https://2captcha.com/demo/recaptcha-v3', version='v3', enterprise=0, action='verify', score=0.7 # proxy={ # 'type': 'HTTPS', # 'uri': 'login:password@IP_address:PORT' # } ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/recaptcha_v3_options.py
recaptcha_v3_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=30, pollingInterval=5) try: result = solver.normal( './images/normal_2.jpg', numeric=4, minLen=4, maxLen=20, phrase=0, caseSensitive=0, calc=0, lang='en', # hintImg='./images/normal_hint.jpg', # hintText='Type red symbols only', ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/normal_options.py
normal_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=100, pollingInterval=10) try: result = solver.rotate( ['images/rotate.jpg', 'images/rotate_2.jpg', 'images/rotate_3.jpg'], angle=40, lang='en', # hintImg = 'images/rotate_hint.jpg' hintText='Put the images in the correct way up') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/rotate_options.py
rotate_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') config = { 'server': '2captcha.com', # can be also set to 'rucaptcha.com' 'apiKey': api_key, 'softId': 123, # 'callback': 'https://your.site/result-receiver', # if set, sovler with just return captchaId, not polling API for the answer 'defaultTimeout': 120, 'recaptchaTimeout': 600, 'pollingInterval': 10, } solver = TwoCaptcha(**config) try: result = solver.hcaptcha(sitekey='3ceb8624-1970-4e6b-91d5-70317b70b651', url='https://2captcha.com/demo/hcaptcha?difficulty=easy', # proxy={ # 'type': 'HTTPS', # 'uri': 'login:password@IP_address:PORT' # } ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/hcaptcha_options.py
hcaptcha_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.grid('./images/grid_2.jpg', hintText='Select all images with an Orange', rows=3, cols=3) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/grid.py
grid.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.funcaptcha(sitekey='69A21A01-CC7B-B9C6-0F9A-E7FA06677FFC', url='https://mysite.com/page/with/funcaptcha', surl='https://client-api.arkoselabs.com') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/funcaptcha.py
funcaptcha.py
import sys import os from base64 import b64encode sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) with open('images/grid_2.jpg', 'rb') as f: b64 = b64encode(f.read()).decode('utf-8') try: result = solver.grid(b64, hintText='Select all images with an Orange', rows=3, cols=3) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/grid_base64.py
grid_base64.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.recaptcha( sitekey='6LfdxboZAAAAAMtnONIt4DJ8J1t4wMC-kVG02zIO', url='https://2captcha.com/demo/recaptcha-v3', action='login', version='v3') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/recaptcha_v3.py
recaptcha_v3.py
import sys import os import requests sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) resp = requests.get("https://www.mysite.com/distil_r_captcha_challenge") challenge = resp.content.decode('utf-8').split(';')[0] try: result = solver.geetest(gt='f3bf6dbdcf7886856696502e1d55e00c', apiServer='api-na.geetest.com', challenge=challenge, url='https://www.mysite.com/distil_r_captcha.html') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/geetest.py
geetest.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.text('If tomorrow is Saturday, what day is today?') except Exception as e: sys.exit(e) else: print(result) sys.exit('result: ' + str(result))
2captcha-solver
/examples/text.py
text.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.canvas('./images/canvas.jpg', hintText='Draw around apple') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/canvas.py
canvas.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=40, pollingInterval=10) try: result = solver.text('If tomorrow is Saturday, what day is today?', lang='en') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/text_options.py
text_options.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.capy( sitekey='PUZZLE_Cz04hZLjuZRMYC3ee10C32D3uNms5w', url='https://www.mysite.com/page/captcha/', api_server="https://jp.api.capy.me/", ) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/capy.py
capy.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.normal('./images/normal.jpg') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/normal.py
normal.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) try: result = solver.recaptcha( sitekey='6LfDxboZAAAAAD6GHukjvUy6lszoeG3H4nQW57b6', url='https://2captcha.com/demo/recaptcha-v2-invisible?level=low') except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/recaptcha_v2.py
recaptcha_v2.py
import sys import os from base64 import b64encode sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key) with open('images/normal.jpg', 'rb') as f: b64 = b64encode(f.read()).decode('utf-8') try: result = solver.normal(b64) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/normal_base64.py
normal_base64.py
import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from twocaptcha import TwoCaptcha # in this example we store the API key inside environment variables that can be set like: # export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS # set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows # you can just set the API key directly to it's value like: # api_key="1abc234de56fab7c89012d34e56fa7b8" api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY') solver = TwoCaptcha(api_key, defaultTimeout=180, pollingInterval=15) try: result = solver.funcaptcha( sitekey='FB18D9DB-BAFF-DDAC-A33B-6CF22267BC0A', url='https://mysite.com/page/with/funcaptcha', surl='https://client-api.arkoselabs.com', userAgent= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36', **{'data[key]': 'value'}, #optional data param used by some websites proxy={ 'type': 'HTTP', 'uri': 'login:password@123.123.123.123:8080' }) except Exception as e: sys.exit(e) else: sys.exit('result: ' + str(result))
2captcha-solver
/examples/funcaptcha_options.py
funcaptcha_options.py
# 2ch-downloader Download all files of 2ch.hk thread. ## Installation ``` sh pip install 2ch-downloader ``` ## Usage ``` usage: 2ch-downloader [-h] [-d DIRECTORY] [--max-directory-name-length LENGTH] URL positional arguments: URL Thread url options: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY Download directory --max-directory-name-length LENGTH Max thread directory name length, 128 by default ```
2ch-downloader
/2ch-downloader-0.0.3.tar.gz/2ch-downloader-0.0.3/README.md
README.md
#!/usr/bin/env python3 __prog__ = "2ch-downloader" __desc__ = "Download all files of 2ch.hk thread." __version__ = "0.0.3" import argparse import html import json import os import re import sys from dataclasses import dataclass from pathlib import Path import requests @dataclass class File: name: str url: str size: int id: str def download_thread_media(url: str, path: Path, max_directory_name_length: int) -> None: BASE_URL = "https://2ch.hk" api_url = url.replace(".html", ".json") response = json.loads(requests.get(api_url).text) thread = response["threads"][0] board = response["board"]["name"] thread_id = int(response["current_thread"]) thread_name = html.unescape(thread["posts"][0]["subject"]) directory_name = f'{board} {thread_id} {thread_name.replace("/", "_")}' print(f"Thread {directory_name}") if len(directory_name) > max_directory_name_length: directory_name = directory_name[:max_directory_name_length] path = path / directory_name os.makedirs(path, exist_ok=True) os.chdir(path) files: list[File] = [] for post in thread["posts"]: if post["files"]: for file in post["files"]: basename, extension = os.path.splitext(file["name"]) files.append( File( file["fullname"] or f'Sticker{extension}', BASE_URL + file["path"], file["size"], basename, ) ) for file in files: download_file(file) def download_file(file: File) -> None: filename = f"{file.id} {file.name}" # Иногда ни размер файла, ни его хеш, отдаваемые api, не соответствуют действительности # Проверять их бессмысленно if os.path.exists(filename): print(f"'{filename}' has already been downloaded", file=sys.stderr) else: print(f"Downloading '{filename}' ({file.size} KB)", file=sys.stderr) r = requests.get(file.url) with open(filename, "wb") as f: f.write(r.content) def thread_url(url: str) -> str: thread_url_regex = re.compile( r"(?:https?:\/\/)?2ch.hk\/[a-z]+\/res\/[0-9]+.html", flags=re.I ) if not thread_url_regex.match(url): raise ValueError("Provided url is not a 2ch.hk thread url") return url def main(): parser = argparse.ArgumentParser(prog=__prog__, description=__desc__) parser.add_argument( "url", metavar="URL", type=thread_url, help="Thread url", ) parser.add_argument( "-d", "--directory", type=str, default=".", help="Download directory", ) parser.add_argument( "--max-directory-name-length", metavar="LENGTH", type=int, default=128, help="Max thread directory name length, 128 by default", ) args = parser.parse_args() download_thread_media( args.url, Path(args.directory), args.max_directory_name_length ) if __name__ == "__main__": main()
2ch-downloader
/2ch-downloader-0.0.3.tar.gz/2ch-downloader-0.0.3/_2ch_downloader.py
_2ch_downloader.py
import setuptools from _2ch_downloader import __desc__, __version__ with open("README.md", "r", encoding="utf-8") as f: long_description = f.read() setuptools.setup( name="2ch-downloader", version=__version__, py_modules=["_2ch_downloader"], author="Layerex", author_email="layerex@dismail.de", description=__desc__, long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Layerex/2ch-downloader", packages=setuptools.find_packages(), classifiers=[ "Development Status :: 6 - Mature", "Environment :: Web Environment", "Programming Language :: Python :: 3", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", "Topic :: Utilities", ], entry_points={ "console_scripts": [ "2ch-downloader = _2ch_downloader:main", ], }, install_requires=["requests"], )
2ch-downloader
/2ch-downloader-0.0.3.tar.gz/2ch-downloader-0.0.3/setup.py
setup.py
# 2D 2D is a project with 1 goal - make programming 2D games as easy as possible. Want to make 3D games? Check out [3D](https://pypi.org/project/3D), the other project for 3D games!
2d
/2d-0.1.1.tar.gz/2d-0.1.1/README.md
README.md
# 2D Utils [![PyPI release](https://github.com/erlete/2dutils/actions/workflows/python-publish.yml/badge.svg)](https://github.com/erlete/2dutils/actions/workflows/python-publish.yml) A collection of 2D utilities for coordinate representation and manipulation. ## Features The following features are currently implemented: * `Coordinate2D` - A custom 2D coordinate representation based on the built-in `tuple` class, but with extended functionality. * `Circumcenter` - A class for calculating the circumcenter and circumradius of three coordinates. ## Installation ### macOS/UNIX ```bash git clone https://github.com/erlete/2d-utils ``` **Note: this package is not yet available on PyPI, but it will be really soon.** ## Usage Once the package has been installed, its modules can be easily imported into custom programs via the `import` statement. ```python from coordinate import Coordinate2D from circumcenter import Circumcenter ```
2dutils
/2dutils-1.2.0.tar.gz/2dutils-1.2.0/README.md
README.md
"""Circumcenter class container module. This module contains the Circumcenter class, which is used to calculate the circumcenter of a triangle, given its three vertices as 2D coordinates. Note: By default, this module uses the Coordinate2D class from the `coordinate` module. However, said class does not present great difference from the builtin `tuple` class, so this change should not pose any major inconvenience. Author: Paulo Sanchez (@erlete) """ from itertools import combinations from math import sqrt from coordinate import Coordinate2D class Circumcenter: """Class for triangle calculation. This class is used to calculate the circumcenter of a triangle, given its three vertices as 2D coordinates. Args: a (Coordinate2D): First vertex of the triangle. b (Coordinate2D): Second vertex of the triangle. c (Coordinate2D): Third vertex of the triangle. Attributes: a (Coordinate2D): First vertex of the triangle. b (Coordinate2D): Second vertex of the triangle. c (Coordinate2D): Third vertex of the triangle. circumcenter (Coordinate2D): The circumcenter of the triangle. radius (float): The radius of the circumcircle of the triangle. """ def __init__(self, a: Coordinate2D, b: Coordinate2D, c: Coordinate2D) -> None: # The initial setting variable allows value validation via attribute # setters but prevents automatic recalculation of the circumcenter # and circumradius. self._initial_setting = False self._a = a self._b = b self._c = c self._initial_setting = True self._calculate() # Initial calculation: @property def a(self) -> Coordinate2D: """First vertex of the triangle. Returns: Coordinate2D: First vertex of the triangle. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ return self._a @a.setter def a(self, value: Coordinate2D) -> None: """First vertex of the triangle. Args: value (Coordinate2D): First vertex of the triangle. Raises: TypeError: If the value is not a Coordinate2D object. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ if not isinstance(value, Coordinate2D): raise TypeError("a must be a Coordinate2D instance") self._a = value if not self._initial_setting: self._calculate() @property def b(self) -> Coordinate2D: """Second vertex of the triangle. Returns: Coordinate2D: Second vertex of the triangle. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ return self._b @b.setter def b(self, value: Coordinate2D) -> None: """Second vertex of the triangle. Args: value (Coordinate2D): Second vertex of the triangle. Raises: TypeError: If the value is not a Coordinate2D object. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ if not isinstance(value, Coordinate2D): raise TypeError("b must be a Coordinate2D instance") self._b = value if not self._initial_setting: self._calculate() @property def c(self) -> Coordinate2D: """Third vertex of the triangle. Returns: Coordinate2D: Third vertex of the triangle. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ return self._c @c.setter def c(self, value: Coordinate2D) -> None: """Third vertex of the triangle. Args: value (Coordinate2D): Third vertex of the triangle. Raises: TypeError: If the value is not a Coordinate2D object. Note: If the value of the vertex is changed, the circumcenter and radius of the triangle are recalculated. """ if not isinstance(value, Coordinate2D): raise TypeError("c must be a Coordinate2D instance") self._c = value if not self._initial_setting: self._calculate() @property def circumcenter(self) -> Coordinate2D: """Circumcenter of the triangle. Returns: Coordinate2D: The circumcenter of the triangle. """ return self._circumcenter @property def circumradius(self) -> float: """Radius of the circumcircle of the triangle. Returns: float: The radius of the circumcircle of the triangle. """ return self._circumradius def _ensure_non_collinear(self) -> None: """Ensures that the triangle is not collinear. This method computes the determinant of the matrix formed by the coordinates of the triangle's vertices. If the determinant is zero, the triangle is collinear, and the circumcenter and circumradius cannot be calculated. Raises: ValueError: If the triangle is collinear. """ if not (self._a.x * (self._b.y - self._c.y) + self._b.x * (self._c.y - self._a.y) + self._c.x * (self._a.y - self._b.y)): raise ValueError("The triangle is collinear") def _calculate(self) -> None: """Calculates the circumcenter and radius of the triangle.""" self._ensure_non_collinear() if any(v[1] - v[0] for v in combinations( (self._a, self._b, self._c), 2)): # Vertical alignment prevention: if not (self._b - self._a).x: self._a, self._c = self._c, self._a if not (self._c - self._a).x: self._a, self._b = self._b, self._a # Segment displacement: displacement = { "ab": Coordinate2D( self.b.x - self.a.x, self.b.y - self.a.y ), "ac": Coordinate2D( self.c.x - self.a.x, self.c.y - self.a.y ) } # Unitary vectors: unitary = { "ab": Coordinate2D( displacement["ab"].y / sqrt( displacement["ab"].x ** 2 + displacement["ab"].y ** 2 ), -displacement["ab"].x / sqrt( displacement["ab"].x ** 2 + displacement["ab"].y ** 2 ) ), "ac": Coordinate2D( displacement["ac"].y / sqrt( displacement["ac"].x ** 2 + displacement["ac"].y ** 2 ), -displacement["ac"].x / sqrt( displacement["ac"].x ** 2 + displacement["ac"].y ** 2 ) ) } # V-vector for vertical intersection: vertical = { "ab": Coordinate2D( unitary["ab"].x / unitary["ab"].y, 1 ), "ac": Coordinate2D( -(unitary["ac"].x / unitary["ac"].y), 1 ) } # Midpoint setting: midpoint = { "ab": Coordinate2D( displacement["ab"].x / 2 + self.a.x, displacement["ab"].y / 2 + self.a.y ), "ac": Coordinate2D( displacement["ac"].x / 2 + self.a.x, displacement["ac"].y / 2 + self.a.y ) } # Midpoint height equivalence: intersection = Coordinate2D( midpoint["ab"].x + ( (midpoint["ac"].y - midpoint["ab"].y) / unitary["ab"].y ) * unitary["ab"].x, midpoint["ac"].y ) # Circumcenter calculation: self._circumcenter = Coordinate2D( intersection.x + ( (midpoint["ac"].x - intersection.x) / (vertical["ab"].x + vertical["ac"].x) ) * vertical["ab"].x, intersection.y + ( midpoint["ac"].x - intersection.x ) / ( vertical["ab"].x + vertical["ac"].x ) ) # Circumradius calculation: self._circumradius = sqrt( (self.a.x - self._circumcenter.x) ** 2 + (self.a.y - self._circumcenter.y) ** 2 )
2dutils
/2dutils-1.2.0.tar.gz/2dutils-1.2.0/src/circumcenter.py
circumcenter.py
"""Coordinate2D class container module. This module contains the Coordinate2D class, which is used to represent a 2D coordinate. It is used by all classes in the `2d-utils` package and presents many similarities to the builtin `tuple` class. Author: Paulo Sanchez (@erlete) """ from __future__ import annotations from math import ceil, floor, trunc from typing import Generator class Coordinate2D: """Represents a pair of real-value, two dimensional coordinates. This class represents a two-dimensional coordinate. Its main purpose is to serve as a normalized conversion format for data going in and out of the scripts contained in the project. Parameters: ----------- - x: float The x-coordinate. - y: float The y-coordinate. """ NUMERICAL = (int, float) SEQUENTIAL = (tuple, list, set) def __init__(self, x_value: float, y_value: float) -> None: self.x: float = float(x_value) self.y: float = float(y_value) @property def x(self) -> float: return self._x @x.setter def x(self, value) -> None: if not isinstance(value, (int, float)): raise TypeError("x must be an int or float") self._x = value @property def y(self) -> float: return self._y @y.setter def y(self, value) -> None: if not isinstance(value, (int, float)): raise TypeError("y must be an int or float") self._y = value def __add__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x + value.x, self._y + value.y) def __sub__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x - value.x, self._y - value.y) def __mul__(self, value) -> Coordinate2D: if isinstance(value, Coordinate2D): return Coordinate2D(self._x * value.x, self._y * value.y) elif isinstance(value, self.NUMERICAL): return Coordinate2D(self._x * value, self._y * value) elif isinstance(value, self.SEQUENTIAL) and len(value) >= 2: return Coordinate2D(self._x * value[0], self._y * value[1]) raise TypeError("value must be a Coordinate2D, a numerical type, or a" "sequential type with at least 2 elements.") def __truediv__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x / value, self._y / value) def __floordiv__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x // value, self._y // value) def __mod__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x % value, self._y % value) def __pow__(self, value) -> Coordinate2D: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate2D.") return Coordinate2D(self._x ** value, self._y ** value) def __neg__(self) -> Coordinate2D: return Coordinate2D(-self._x, -self._y) def __pos__(self) -> Coordinate2D: return Coordinate2D(+self._x, +self._y) def __abs__(self) -> Coordinate2D: return Coordinate2D(abs(self._x), abs(self._y)) def __invert__(self) -> Coordinate2D: return Coordinate2D(~self._x, ~self._y) def __round__(self, n: int = 0) -> Coordinate2D: if not isinstance(n, int): raise TypeError("n must be an int.") return Coordinate2D(round(self._x, n), round(self._y, n)) def __floor__(self) -> Coordinate2D: return Coordinate2D(floor(self._x), floor(self._y)) def __ceil__(self) -> Coordinate2D: return Coordinate2D(ceil(self._x), ceil(self._y)) def __trunc__(self) -> Coordinate2D: return Coordinate2D(trunc(self._x), trunc(self._y)) def __lt__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x < value.x and self._y < value.y def __le__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x <= value.x and self._y <= value.y def __gt__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x > value.x and self._y > value.y def __ge__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x >= value.x and self._y >= value.y def __eq__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x == value.x and self._y == value.y def __ne__(self, value) -> bool: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x != value.x or self._y != value.y def __str__(self) -> str: return f"Coordinate2D({self._x}, {self._y})" def __repr__(self) -> str: return f"Coordinate2D({self._x}, {self._y})" def __hash__(self) -> int: return hash((self._x, self._y)) def __bool__(self) -> bool: return self._x != 0 or self._y != 0 def __len__(self) -> int: return 2 def __getitem__(self, index) -> float: if index == 0: return self._x elif index == 1: return self._y else: raise IndexError("index must be 0 or 1") def __setitem__(self, index, value) -> None: if index == 0: self._x = value elif index == 1: self._y = value else: raise IndexError("index must be 0 or 1") def __iter__(self) -> Generator[float, None, None]: yield self._x yield self._y def __reversed__(self) -> Generator[float, None, None]: yield self._y yield self._x def __getattr__(self, name) -> float: if name == 'x': return self._x elif name == 'y': return self._y else: raise AttributeError(f"{name} is not an attribute") def __delattr__(self, name) -> None: if name == 'x': del self._x elif name == 'y': del self._y else: raise AttributeError(f"{name} is not an attribute") def __getstate__(self) -> tuple[float, float]: return self._x, self._y def __setstate__(self, state) -> None: self._x, self._y = state def __reduce__(self) -> tuple[Coordinate2D, tuple[float, float]]: return self.__class__, (self._x, self._y) def __copy__(self) -> Coordinate2D: return self.__class__(self._x, self._y) def __bytes__(self) -> bytes: return bytes(self._x) + bytes(self._y) def __int__(self) -> int: return int(self._x) + int(self._y) def __float__(self) -> float: return float(self._x) + float(self._y) def __complex__(self) -> complex: return complex(self._x) + complex(self._y) def __oct__(self) -> str: return oct(self._x) + oct(self._y) def __hex__(self) -> str: return hex(self._x) + hex(self._y) def __index__(self) -> float: return self._x + self._y def __coerce__(self, value) -> tuple[float, float]: if not isinstance(value, Coordinate2D): raise TypeError("value must be a Coordinate.") return self._x, value.x def __format__(self, format_spec) -> str: return format(self._x, format_spec) + format(self._y, format_spec)
2dutils
/2dutils-1.2.0.tar.gz/2dutils-1.2.0/src/coordinate.py
coordinate.py
# 2dwavesim This is a project that simulates waves on 2D plates/rooms. Given boundaries (or walls) and points where oscillation will be forced, this will simulate the resulting wavemodes! Currently it supports setting the attenuation properties of individual boundaries, multiple forcing points based on either data or a function, and any wall shape you want. It also supports variable time and space steps and spans (as long as you keep numerically stable!), as well as custom wavespeed and attenuation on the material. ![example](https://github.com/cooperhatfield/2dwavesim/blob/main/exampleimages/example.webp) TODO: - add tests - frequency-dependant wall transmission values - 3D?? ## Usage There are two main Classes: `Room(ds, width, height,*, walls=[], physics_params={})` <ul> This creates an instance of a `Room` class, which contains any walls or sources of the system. `ds` is a float which defines the unit of distance between two grid points. `width` and `height` and floats which define the dimentions of the grid. If they are not exact multiples of `ds`, then they are upper bounds on the number of points above the nearest multiple. `walls` is a list of `Wall` objects. This can be optionally set after construction as well. `physics_params` is a dict with structure `{'wavespeed':float, 'attenuation':float}`. Wavespeed represents the speed of the propigating wave on the room's medium, and attenuation represents the attenuation factor of waves on the medium. By defaut, wavespeed is assumed to be 343 units/s and attenuation is assumed to be $2^{-2}$ units $^{-1}$. **`Room.add_source_func(loc, func)`** <ul> Add a source based on a function. `loc` is the room-specific coordinate of the source. Note: unless `ds=1`, this is not the same as the list indices of the point in the room. `func` is a function taking a float (the time) and outputing a float (the value of the wave at that time). This should be something like `lambda t: np.sin(t)`, for example. </ul> **`Room.add_source_data(loc, data)`** <ul> Add a source based on a list of values. Careful! Make sure you use a `dt` value that matches the table data, as an entry of the data list will be used on every time tick. For example, if you make the data table represent the value of the wave every 200ms, then be sure to set `dt` to 200ms as well when you run the simulation. If there are less points in the list of values than there are time steps, then a value of 0 is used for all time steps past the last data point. `loc` is the room-specific coordinate of the source. Note: unless `ds=1`, this is not the same as the list indices of the point in the room. `data` is a list of floats (the value of the wave at that time). This should be something like `np.sin(np.arange(0, 10, 0.2))`, for example. </ul> **`Room.add_walls(walls)`** <ul> Add walls to the system after constructing the Room object. `walls` is a list of `Wall` objects to add the the system. </ul> **`Room.create_mask()`** <ul> Create a mask for the values of the room based on the currently set walls. This is automatically done when running the simulation, but it can be run beforehand if you want to plot the mask for visualization. </ul> **`Room.get_mask()`** <ul> Returns a 2D array of the wall mask as currently calculated. </ul> **`Room.run(dt, t_final)`** <ul> Calculate the wave propagation from the set sources and using the set walls. This will simulate from `t=0` to `t_final` at `dt` time steps. If `t_final` isn't an exact multiple of `dt`, then it acts like an upper bound. `dt` a float giving the time step for the simulation. A smaller value means more time resolution. WARNING: Numerical stability will almost certainly be lost if this is not set to satisfy the [CFL Condition](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition), namely $\frac{u*dt}{ds} \leq C_{max}$ where $u$ is the `wavespeed` and $c_{max}$ is approximately 1 for the numerical method being used. `t_final` a float giving an upper limit for the amount of time to be simulated. A higher value will take more time to simulate, and will likely just repeat the steady state after a certain point in time... </ul> </ul> `Wall(endpoint1, endpoint2, transmission)` <ul> This creates an instance of a `Wall` class, which contains the wall's endpoints and transmission factor. `endpoint1` and `endpoint2` are tuple2 or 2-list2 of floats giving the position of each end of the wall in the room-specific coordinates. Note: unless `ds=1`, this is not the same as the list indices of the point in the room. `transmission` is a float in [0,1] which defines the proportion of wave amplitude able to penetrate the wall. If 0, then all energy is reflected back inwards, and if 1 then the wall "isn't there". </ul> ## Visualization The `visualization` module contains a few functions for visualizing results, or processing results into an easily displayed format. **`animate(data, *, filepath='', frame_space=10, walls=[])`** <ul> Automatically animate the given data using `matplotlib.animation.ArtistAnimation`. The animation file can optionally be saved to a file. `data` is a 3D array of waveform over time, which is the output from running the simulation. `filename` is the name and path of output file. Leave this blank to not save. Output formats are those supported by `matplotlib.animation.ArtistAnimation`, which is at least ".gif" and ".webp". `frame_space` is the temporal resolution of resulting animation. Make sure this isn't too small! `walls` is to optionally include the walls in the animation. They won't be visible if this isn't included. </ul> **`get_steady_state_index(data, *, sample_points, rms_tolerance=0.1, window_size=0.1)`** <ul> This function calculates the windowed RMS of the given points over time. This data is compared to the RMS value at the end of the simulation. Then the latest time index where all point RMS's are within a tolerance to the final RMS is taken as the time index where steady-state is reached. `data` is a 3D array of waveform over time, which is the output from running the simulation. `sample_points` is a list of points in the room which will be checked for RMS. `rms_tolerance` is a float in [0, 1] defining the limit on the amount the RMS is allowed to change from the final value and still be considered steady-state. `window_size` is a float in [0, 1] defining the percent of total points to consider in the window. </ul> **`get_standing_waves(data, *, steady_state_kwargs=None)`** <ul> This function calculates when the steady state begins, and returns a 2D array which is the average of the absolute value of all of the rooms points across all steady state times. `data` is a 3D array of waveform over time, which is the output from running the simulation. `steady_state_kwargs` is a dict of the keyword arguments to pass to `get_steady_state_index`. If `None`, then the default parameters and a sample point at the middle of the room are used. </ul>
2dwavesim
/2dwavesim-1.0.0.tar.gz/2dwavesim-1.0.0/README.md
README.md
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name='2dwavesim', version='1.0.0', author='Cooper Hatfield', author_email='cooperhatfield@yahoo.ca', description='Simulate waves on 2D surfaces with arbitrary shape/size!', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/cooperhatfield/2dwavesim', project_urls = { "Bug Tracker": "https://github.com/cooperhatfield/2dwavesim/issues" }, license='', packages=['2dwavesim'], install_requires=['numpy', 'tqdm'], )
2dwavesim
/2dwavesim-1.0.0.tar.gz/2dwavesim-1.0.0/setup.py
setup.py
# 2dxPlay Play konami 2dx files from the command line. Install with pip and run it from anywhere. `pip install 2dxPlay` ### Usage: ``` 2dxplay infile.2dx ``` If the file contains more than one wav, it will play all tracks sequentially. Press Ctrl+C to pause and enter a track number to jump to, or `q` to quit. ###Tip: Play any 2dx file just by double clicking on it: Right click on a 2dx file, choose Open With > Look for another app on this PC. Navigate to your python installation where 2dxPlay.exe is installed. (I use python 3.7, so pip installed it in `%appdata%\Local\Programs\Python\Python37\Scripts`). Check the "Always use this app" box and profit. ![img.png](img.png)
2dxPlay
/2dxPlay-1.0.1.tar.gz/2dxPlay-1.0.1/README.md
README.md
import os from distutils.core import setup import setuptools def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='2dxPlay', version='1.0.1', packages=['twodxPlay'], entry_points=''' [console_scripts] 2dxplay=twodxPlay.main:main ''', keywords=['2dx'], url='https://github.com/camprevail/2dxPlay', license='MIT', author='camprevail', author_email='cam.anderson573@gmail.com', description='Play a .2dx file.', long_description=read('README.md'), long_description_content_type="text/markdown", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=["pygame", "setuptools"], )
2dxPlay
/2dxPlay-1.0.1.tar.gz/2dxPlay-1.0.1/setup.py
setup.py
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" from os import path from pygame import mixer from twodxPlay.twodx import Twodx import sys, traceback from datetime import timedelta import struct import argparse version='V1.0.1' parser = argparse.ArgumentParser(description='A command line app for playing and extracting konami 2dx audio files.') parser.add_argument('infile') parser.add_argument('-e', '--extract', nargs='?', const='all', help='Extract the wav files. Optionally specify a number, a comma-separated list of numbers or a range such as 10-20.' ' Don\'t use spaces, and NOTE that extracted wav files will start at 0.wav. Example: 2dxplay -e 1,4-8,10 infile.2dx') parser.add_argument('-o', '--output-dir', default='output', help='Directory to extract files to. Will be created if not exists. Default is ./output/') if len(sys.argv) <= 1: print(f"2dxPlay {version}") parser.print_help() sys.exit(1) args = parser.parse_args() mixer.init() infile = args.infile outdir = args.output_dir try: twodx_file = Twodx(path.abspath(infile)) except struct.error: traceback.print_exc() print("Probably not a 2dx file.") sys.exit(1) except: traceback.print_exc() sys.exit(1) current_track = 1 # function from bemaniutils/afputils. def parse_intlist(data): ints = [] for chunk in data.split(","): chunk = chunk.strip() if '-' in chunk: start, end = chunk.split('-', 1) start_int = int(start.strip()) end_int = int(end.strip()) ints.extend(range(start_int, end_int + 1)) else: ints.append(int(chunk)) return sorted(set(ints)) def extract(data=None): if outdir != '.' and not os.path.exists(outdir): os.mkdir(outdir) if args.extract == 'all': for i in range(twodx_file.file_count): wav = twodx_file.load(i) print(f"Writing {i+1}/{twodx_file.file_count} wavs to {outdir}") with open(f"{outdir}/{i}.wav", 'wb') as f: f.write(wav.getbuffer()) else: if data: ints = parse_intlist(data) else: ints = parse_intlist(args.extract) for i in ints: wav = twodx_file.load(i-1) print(f"Writing {i-1}.wav to {outdir}") with open(f"{args.output_dir}/{i-1}.wav", 'wb') as f: f.write(wav.getbuffer()) def main(): if args.extract: extract() sys.exit() global current_track try: while current_track-1 < twodx_file.file_count: wav = twodx_file.load(current_track-1) sound = mixer.Sound(wav) channel = sound.play() length = timedelta(seconds=int(sound.get_length())) print(f"Playing: {infile} Track {current_track}/{twodx_file.file_count} Length: {length}") while channel.get_busy(): pass current_track += 1 except KeyboardInterrupt: mixer.stop() while "the answer is invalid": try: reply = str(input('Enter track number to jump to, e [track(s) to extract], or q to quit: ')).lower().strip() except (EOFError, KeyboardInterrupt): sys.exit(0) if reply == 'q': sys.exit(0) if reply[0] == 'e': ints = reply.split() if len(reply) > 1: extract(reply.split()[1]) else: continue if reply.isdigit() and int(reply) in range(1, twodx_file.file_count + 1): current_track = int(reply) main() except Exception: traceback.print_exc() sys.exit(1) if __name__ == "__main__": main()
2dxPlay
/2dxPlay-1.0.1.tar.gz/2dxPlay-1.0.1/twodxPlay/main.py
main.py
import struct from io import BytesIO # 2dx file structure ported from https://github.com/mon/2dxTools class Twodx: def __init__(self, path): self.path = path try: with open(self.path, 'rb') as f: self.name = f.read(16) self.header_size = struct.unpack('I', f.read(4))[0] self.file_count = struct.unpack('I', f.read(4))[0] f.seek(48, 1) self.file_offsets = [struct.unpack('I', f.read(4))[0] for i in range(self.file_count)] except: raise def load(self, file: int): with open(self.path, 'rb') as f: try: f.seek(self.file_offsets[file]) except IndexError: print(f'Error: Track id [{file}] out of range. Exiting.') exit() dx = f.read(4) header_size = struct.unpack('I', f.read(4))[0] # Should be "2DX9"; wav_size = struct.unpack('I', f.read(4))[0] # Always 24 bytes, includes dx chars unk1 = struct.unpack('h', f.read(2))[0] # Always 0x3231 track_id = struct.unpack('h', f.read(2))[0] # Always -1 for previews, 0-7 for song + effected versions, 9 to 11 used for a few effects unk2 = struct.unpack('h', f.read(2))[0] # All 64, except song selection change 'click' is 40 attenuation = struct.unpack('h', f.read(2))[0] # 0-127 for varying quietness loop_point = struct.unpack('I', f.read(4))[0] # Sample to loop at * 4 f.seek(self.file_offsets[file] + header_size) wav = BytesIO(f.read(wav_size)) return wav
2dxPlay
/2dxPlay-1.0.1.tar.gz/2dxPlay-1.0.1/twodxPlay/twodx.py
twodx.py
from setuptools import setup, find_packages setup( name='2fa', version='0.0.1', description='A command-line 2-factor authentication manager', long_description='', url='https://github.com/seiyanuta/2fa', scripts=['2fa'], install_requires=['pyqrcode'], packages=find_packages(), classifiers = [ 'Operating System :: POSIX', 'Environment :: Console', 'Topic :: Utilities' ] )
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/setup.py
setup.py
from pyotp.otp import OTP from pyotp import utils class HOTP(OTP): def at(self, count): """ Generates the OTP for the given count @param [Integer] count counter @returns [Integer] OTP """ return self.generate_otp(count) def verify(self, otp, counter): """ Verifies the OTP passed in against the current time OTP @param [String/Integer] otp the OTP to check against @param [Integer] counter the counter of the OTP """ return utils.strings_equal(str(otp), str(self.at(counter))) def provisioning_uri(self, name, initial_count=0, issuer_name=None): """ Returns the provisioning URI for the OTP This can then be encoded in a QR Code and used to provision the Google Authenticator app @param [String] name of the account @param [Integer] initial_count starting counter value, defaults to 0 @param [String] the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator @return [String] provisioning uri """ return utils.build_uri( self.secret, name, initial_count=initial_count, issuer_name=issuer_name, )
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/pyotp/hotp.py
hotp.py
import base64 import hashlib import hmac class OTP(object): def __init__(self, s, digits=6, digest=hashlib.sha1): """ @param [String] secret in the form of base32 @option options digits [Integer] (6) Number of integers in the OTP Google Authenticate only supports 6 currently @option options digest [Callable] (hashlib.sha1) Digest used in the HMAC Google Authenticate only supports 'sha1' currently @returns [OTP] OTP instantiation """ self.digits = digits self.digest = digest self.secret = s def generate_otp(self, input): """ @param [Integer] input the number used seed the HMAC Usually either the counter, or the computed integer based on the Unix timestamp """ hmac_hash = hmac.new( self.byte_secret(), self.int_to_bytestring(input), self.digest, ).digest() hmac_hash = bytearray(hmac_hash) offset = hmac_hash[-1] & 0xf code = ((hmac_hash[offset] & 0x7f) << 24 | (hmac_hash[offset + 1] & 0xff) << 16 | (hmac_hash[offset + 2] & 0xff) << 8 | (hmac_hash[offset + 3] & 0xff)) str_code = str(code % 10 ** self.digits) while len(str_code) < self.digits: str_code = '0' + str_code return str_code def byte_secret(self): missing_padding = len(self.secret) % 8 if missing_padding != 0: self.secret += '=' * (8 - missing_padding) return base64.b32decode(self.secret, casefold=True) @staticmethod def int_to_bytestring(i, padding=8): """ Turns an integer to the OATH specified bytestring, which is fed to the HMAC along with the secret """ result = bytearray() while i != 0: result.append(i & 0xFF) i >>= 8 # It's necessary to convert the final result from bytearray to bytes because # the hmac functions in python 2.6 and 3.3 don't work with bytearray return bytes(bytearray(reversed(result)).rjust(padding, b'\0'))
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/pyotp/otp.py
otp.py
import datetime import time from pyotp import utils from pyotp.otp import OTP class TOTP(OTP): def __init__(self, *args, **kwargs): """ @option options [Integer] interval (30) the time interval in seconds for OTP This defaults to 30 which is standard. """ self.interval = kwargs.pop('interval', 30) super(TOTP, self).__init__(*args, **kwargs) def at(self, for_time, counter_offset=0): """ Accepts either a Unix timestamp integer or a Time object. Time objects will be adjusted to UTC automatically @param [Time/Integer] time the time to generate an OTP for @param [Integer] counter_offset an amount of ticks to add to the time counter """ if not isinstance(for_time, datetime.datetime): for_time = datetime.datetime.fromtimestamp(int(for_time)) return self.generate_otp(self.timecode(for_time) + counter_offset) def now(self): """ Generate the current time OTP @return [Integer] the OTP as an integer """ return self.generate_otp(self.timecode(datetime.datetime.now())) def verify(self, otp, for_time=None, valid_window=0): """ Verifies the OTP passed in against the current time OTP @param [String/Integer] otp the OTP to check against @param [Integer] valid_window extends the validity to this many counter ticks before and after the current one """ if for_time is None: for_time = datetime.datetime.now() if valid_window: for i in range(-valid_window, valid_window + 1): if utils.strings_equal(str(otp), str(self.at(for_time, i))): return True return False return utils.strings_equal(str(otp), str(self.at(for_time))) def provisioning_uri(self, name, issuer_name=None): """ Returns the provisioning URI for the OTP This can then be encoded in a QR Code and used to provision the Google Authenticator app @param [String] name of the account @return [String] provisioning uri """ return utils.build_uri(self.secret, name, issuer_name=issuer_name) def timecode(self, for_time): i = time.mktime(for_time.timetuple()) return int(i / self.interval)
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/pyotp/totp.py
totp.py
from __future__ import print_function, unicode_literals, division, absolute_import import unicodedata try: from urllib.parse import quote except ImportError: from urllib import quote def build_uri(secret, name, initial_count=None, issuer_name=None): """ Returns the provisioning URI for the OTP; works for either TOTP or HOTP. This can then be encoded in a QR Code and used to provision the Google Authenticator app. For module-internal use. See also: http://code.google.com/p/google-authenticator/wiki/KeyUriFormat @param [String] the hotp/totp secret used to generate the URI @param [String] name of the account @param [Integer] initial_count starting counter value, defaults to None. If none, the OTP type will be assumed as TOTP. @param [String] the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator @return [String] provisioning uri """ # initial_count may be 0 as a valid param is_initial_count_present = (initial_count is not None) otp_type = 'hotp' if is_initial_count_present else 'totp' base = 'otpauth://%s/' % otp_type if issuer_name: issuer_name = quote(issuer_name) base += '%s:' % issuer_name uri = '%(base)s%(name)s?secret=%(secret)s' % { 'name': quote(name, safe='@'), 'secret': secret, 'base': base, } if is_initial_count_present: uri += '&counter=%s' % initial_count if issuer_name: uri += '&issuer=%s' % issuer_name return uri def strings_equal(s1, s2): """ Timing-attack resistant string comparison. Normal comparison using == will short-circuit on the first mismatching character. This avoids that by scanning the whole string, though we still reveal to a timing attack whether the strings are the same length. """ s1 = unicodedata.normalize('NFKC', s1) s2 = unicodedata.normalize('NFKC', s2) try: # Python 3.3+ and 2.7.7+ include a timing-attack-resistant # comparison function, which is probably more reliable than ours. # Use it if available. from hmac import compare_digest return compare_digest(s1, s2) except ImportError: pass if len(s1) != len(s2): return False differences = 0 for c1, c2 in zip(s1, s2): differences |= ord(c1) ^ ord(c2) return differences == 0
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/pyotp/utils.py
utils.py
from __future__ import print_function, unicode_literals, division, absolute_import import random as _random from pyotp.hotp import HOTP from pyotp.otp import OTP from pyotp.totp import TOTP from . import utils def random_base32(length=16, random=_random.SystemRandom(), chars=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')): return ''.join( random.choice(chars) for _ in range(length) )
2fa
/2fa-0.0.1.tar.gz/2fa-0.0.1/pyotp/__init__.py
__init__.py
import time import threading import urwid import argparse import random from feeds.display import FeedsTreeBrowser from feeds.utils import * from feeds.input_mod import * f = None def insert_feeds(feeds): global q, f try: all_src = [] while True: s = q.get(timeout=7) content = s.preview() all_src.append(s) # added new check for None if content is None: continue f.init_data(content) q.queue.clear() except Exception as e: pass finally: f.done = True def _start(): global q, f, progress # cli parser = argparse.ArgumentParser(prog='2feeds') group = parser.add_mutually_exclusive_group() group.add_argument('-a', '--add', action='store_true', help='add a new feed') group.add_argument('-l', '--list', action='store_true', help='list saved feeds') group.add_argument('-r', '--remove', action='store_true', help='remove a feed from your collection') group.add_argument('-c', '--clear', action='store_true', help='clear feed collection and/or clear viewing cache') args = parser.parse_args() cli = False if args.add or args.list or args.remove or args.clear: cli = True if args.add: addLink() elif args.list: listSavedSites() elif args.remove: delete_feed() elif args.clear: clear_data() if cli: exit() feeds = getParam('url') random.shuffle(feeds) feeds = tuple(feeds) if len(feeds) == 0: print('add some feeds using -a option.') exit(-1) # get feeds progress = set(getProgress()) request_feeds = threading.Thread( target=get_feeds_from_url, args=(feeds, progress,)) request_feeds.start() # init display f = FeedsTreeBrowser() # grab feeds from queue add_feed = threading.Thread(target=insert_feeds, args=(feeds,)) add_feed.start() # run event loop links = f.main() if links != []: saveProgress(links) request_feeds.join() add_feed.join() if __name__ == "__main__": _start()
2feeds
/2feeds-1.0.210-py3-none-any.whl/feeds/main.py
main.py
import os import re import json import time DIR_BASE = os.path.dirname(os.path.abspath(__file__)) dir_path = DIR_BASE + "/.app_data" udata_path = dir_path + "/udata.dat" ucache_path = dir_path + "/ucache.dat" regex = re.compile( r'^(?:http|ftp)s?://' ) def checkFiles(): if not os.path.isdir(dir_path): os.makedirs(dir_path) if not os.path.exists(udata_path): with open(udata_path, 'w') as f: f.write('[]') if not os.path.exists(ucache_path): with open(ucache_path, 'w') as f: f.write('[]') def addLink(): checkFiles() links = getOldLinks() link_set = set([x['url'] for x in links]) link = input('Paste RSS link here: ') if re.match(regex, link) is None: print("Not a valid url") exit() title = input('Site-name: ') data = { 'url': link, 'title': title, 'time': time.time() } if data['url'] in link_set: print('Already added, exiting') exit() links.append(data) with open(udata_path, 'w') as f: json.dump(links, f) def getOldLinks(): with open(udata_path, 'r') as f: content = f.read() data = json.loads(content) return data def listSavedSites(): sites = getParam('title') if len(sites) == 0: print('Empty collection. Please update') exit() for x in sites: print(' x ' + x) def getParam(param): checkFiles() links_dict = getOldLinks() result = [] for x in links_dict: result.append(x[param]) return result def updateParam(param, item): checkFiles() links_dict = getOldLinks() if len(links_dict) == 0: print('Nothing to update') exit() valid = [] for x in links_dict: if item != x[param]: valid.append(x) with open(udata_path, 'w') as f: json.dump(valid, f) def delete_feed(): listSavedSites() item = input('Enter site-name: ') updateParam('title', item) def getProgress(): checkFiles() with open(ucache_path, 'r') as f: content = f.read() data = json.loads(content) return data def saveProgress(url): checkFiles() links = getProgress() links.extend(url) with open(ucache_path, 'w') as f: json.dump(list(set(links)), f) def clear_data(): choice = input('would you like to clear viewing cache? (y/n): ') if choice in ('y', "Y", "yes", "Yes"): with open(ucache_path, 'w') as f: f.write('[]') choice = input('would you like to clear feed sources? (y/n): ') if choice in ('y', "Y", "yes", "Yes"): with open(udata_path, 'w') as f: f.write('[]')
2feeds
/2feeds-1.0.210-py3-none-any.whl/feeds/input_mod.py
input_mod.py
import queue import threading import feedparser from html.parser import HTMLParser q = queue.Queue() class MLStripper(HTMLParser): def __init__(self): self.reset() self.strict = False self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data().strip() class RSS_parser: def __init__(self, url, progress): self.url = url self.stories = [] self.init(progress) self.pos = 0 def __len__(self): return len(self.stories) def init(self, progress): p = feedparser.parse(self.url) exception = p.get('bozo_exception', None) if exception is not None: exit(-1) # exit if no internet connection; no attempt to reconnect for i in range(len(p.entries)): url = p.entries[i].link if url not in progress: self.stories.append( {"name": strip_tags(p.entries[i].title), "url": url, "children": [{"name": strip_tags(p.entries[i].description)}]}) def preview(self): # added return if self.pos > len(self.stories): return None count = 0 end = len(self.stories) if self.pos + \ 3 > len(self.stories) else self.pos + 3 for i in range(self.pos, end): count += 1 result = self.stories[self.pos:end] self.pos += count return result # add dependency ? def get_feeds_from_url(urls, progress): for url in urls: try: r = RSS_parser(url, progress) if len(r) == 0: continue q.put(r) except Exception as e: pass # is it okay to pass ? def check_if_empty(all_feeds): if len(list(filter(lambda x: x.pos >= len(x.stories), all_feeds))) == len( all_feeds ): return True return False
2feeds
/2feeds-1.0.210-py3-none-any.whl/feeds/utils.py
utils.py
import urwid import time import threading import webbrowser state = { 'expanded': {}, 'isFlagged': {} } class FeedTreeWidget(urwid.TreeWidget): """ Display widget for leaf nodes """ unexpanded_icon = urwid.AttrMap(urwid.TreeWidget.unexpanded_icon, 'dirmark') expanded_icon = urwid.AttrMap(urwid.TreeWidget.expanded_icon, 'dirmark') indent_cols = 4 def __init__(self, node, is_expanded=None, is_flagged=None): self.__super.__init__(node) if self.get_node()._parent is not None: self.keypress(None, "-") if is_expanded is not None: if is_expanded: self.keypress(None, "+") else: self.keypress(None, "-") self._w = urwid.AttrWrap(self._w, None) if is_flagged is not None: self.flagged = is_flagged else: self.flagged = False self.update_w() def update_w(self): """Update the attributes of self.widget based on self.flagged. """ if self.flagged: self._w.attr = 'flagged focus' # 'flagged' self._w.focus_attr = 'flagged focus' else: self._w.attr = 'body' self._w.focus_attr = 'focus' def get_display_text(self): return self.get_node().get_value()['name'] def get_feed_url(self): return self.get_node().get_value()['url'] def selectable(self): """ Allow selection of non-leaf nodes so children may be (un)expanded """ return not self.is_leaf and self.get_node()._parent is not None def mouse_event(self, size, event, button, col, row, focus): if self.is_leaf or event != 'mouse press' or button != 1 or self.get_node()._parent is None: return False if row == 0 and col == self.get_indent_cols(): self.expanded = not self.expanded self.update_expanded_icon() return True return False def unhandled_keys(self, size, key): """ Override this method to intercept keystrokes in subclasses. Default behavior: Toggle flagged on space, ignore other keys. """ if key in (" ", "enter"): if key == "enter": self.flagged = True else: self.flagged = not self.flagged self.update_w() return key def keypress(self, size, key): """Handle expand & collapse requests (non-leaf nodes)""" if self.is_leaf: return key if key in ("+", "right"): self.expanded = True self.update_expanded_icon() elif key in ("-", "left"): self.expanded = False self.update_expanded_icon() elif key in (" ", "enter"): return self.unhandled_keys(size, key) elif self._w.selectable(): return self.__super.keypress(size, key) else: return key def load_inner_widget(self): if self.is_leaf: return urwid.AttrMap(urwid.Text(self.get_display_text()), 'summary') else: return urwid.Text(self.get_display_text()) def get_indented_widget(self): widget = self.get_inner_widget() div = urwid.Divider() if not self.is_leaf: widget = urwid.Columns([('fixed', 1, [self.unexpanded_icon, self.expanded_icon][self.expanded]), widget], dividechars=1) else: widget = urwid.Pile([widget, div]) indent_cols = self.get_indent_cols() return urwid.Padding(widget, width=('relative', 100), left=indent_cols, right=indent_cols) class Node(urwid.TreeNode): """ Data storage object for leaf nodes """ def load_widget(self): return FeedTreeWidget(self) class FeedParentNode(urwid.ParentNode): """ Data storage object for interior/parent nodes """ def __init__(self, value, parent=None, key=None, depth=None): urwid.TreeNode.__init__( self, value, parent=parent, key=key, depth=depth) self._child_keys = None self._children = {} self.is_expanded = None self.is_flagged = None def load_widget(self): return FeedTreeWidget(self, self.is_expanded, self.is_flagged) def load_child_keys(self): data = self.get_value() return range(len(data['children'])) def load_child_node(self, key): """Return either an Node or ParentNode""" childdata = self.get_value()['children'][key] childdepth = self.get_depth() + 1 if 'children' in childdata: childclass = FeedParentNode else: childclass = Node return childclass(childdata, parent=self, key=key, depth=childdepth) def append_child_node(self, data): self._value["children"].extend(data["children"]) saved_links = [] class CustomTree(urwid.TreeListBox): def unhandled_input(self, size, input): """Handle macro-navigation keys""" if input == 'left': return input elif input == '-': self.collapse_focus_parent(size) elif input == "enter": widget, pos = self.body.get_focus() url = widget.get_feed_url() webbrowser.open(url) self.add_link(url) elif input == " ": widget, pos = self.body.get_focus() url = widget.get_feed_url() self.add_or_remove_link(url) else: return input def add_link(self, url): if url not in saved_links: saved_links.append(url) def add_or_remove_link(self, url): if url not in saved_links: saved_links.append(url) else: saved_links.pop(saved_links.index(url)) class FeedsTreeBrowser: palette = [ ('body', 'white', 'black'), ('dirmark', 'light red', 'black', 'bold'), # ('title', 'default,bold', 'default', 'bold'), ('key', 'light cyan', 'black'), ('focus', 'light gray', 'dark blue', 'standout'), ('title', 'default,bold', 'default', 'bold'), ('summary', 'black', 'light gray'), # ('flagged', 'black', 'dark green', ('bold', 'underline')), ('flagged', 'black', 'light green'), ('flagged focus', 'black', 'dark cyan', ('bold', 'standout', 'underline')), # ('foot', 'light gray', 'black'), # ('flag', 'dark gray', 'light gray'), # ('error', 'dark red', 'light gray'), ] footer_text = [ ('title', ""), "", ('key', "UP"), ",", ('key', "DOWN"), ",", # ('key', "PAGE UP"), ",", ('key', "PAGE DOWN"), " ", ('key', "+"), ",", ('key', "-"), ",", ('key', "RIGHT"), ",", ('key', "LEFT"), " ", ('key', "ENTER"), ",", ('key', "SPACE"), " ", ('key', "Q"), ] def __init__(self, data=None): self.header = urwid.Text("2Feeds", align="left") self.footer = urwid.AttrMap(urwid.Text(self.footer_text), 'foot') self.start = True self.done = False def init_data(self, data): if self.start: self.topnode = FeedParentNode(None) d_ = {"name": "/", "children": []} d_["children"].extend(data) self.topnode._value = d_ self.tw = urwid.TreeWalker(self.topnode) self.listbox = CustomTree(self.tw) self.start = False else: d_ = self.topnode._value d_["children"].extend(data) self.topnode = FeedParentNode(d_) def generate_frame(self): return urwid.Padding(urwid.Frame( urwid.AttrMap(self.listbox, 'body'), header=urwid.AttrMap(self.header, 'title'), footer=self.footer), left=1, right=2) def store_state(self): node = self.loop.widget.base_widget.body.base_widget._body.focus parent = node.get_parent() keys = parent.get_child_keys() for key in keys: state['expanded'][key] = parent.get_child_widget(key).expanded state['isFlagged'][key] = parent.get_child_widget(key).flagged def restore_state(self): keys = self.topnode.get_child_keys() prev_len = len(state['expanded']) for i, key in enumerate(keys): _ = self.topnode.get_child_node(key) if i < prev_len: self.topnode._children[key].is_expanded = state['expanded'][key] self.topnode._children[key].is_flagged = state['isFlagged'][key] def refresh(self, _loop, _data): """ Redraw screen; TODO: is there a better way? """ global stop_adding node = self.tw.get_focus()[1] key = node.get_key() self.store_state() self.restore_state() self.tw = urwid.TreeWalker(self.topnode.get_child_node(key)) # self.loop.widget.base_widget.body.base_widget._body = self.tw self.listbox = CustomTree(self.tw) self.loop.widget.base_widget.body = self.listbox if not self.done: self.loop.set_alarm_in(1, self.refresh) def main(self): """Run the program.""" try: count = 0 while not hasattr(self, 'listbox'): time.sleep(1) count += 1 if count == 15: # print('time exceeded') raise Exception('time exceeded') continue self.frame = urwid.AttrMap(self.generate_frame(), 'body') self.loop = urwid.MainLoop(self.frame, self.palette, unhandled_input=self.unhandled_input) self.loop.set_alarm_in(1, self.refresh) self.loop.run() except Exception as e: err_msg = """error occured:\n- check internet connection\n- add more sources""" print(err_msg) exit(-1) finally: return saved_links def unhandled_input(self, k): if k in ('q', 'Q'): raise urwid.ExitMainLoop()
2feeds
/2feeds-1.0.210-py3-none-any.whl/feeds/display.py
display.py
# -*- coding: utf-8 -*- """ python-2gis ============ A Python library for accessing the 2gis API """ from setuptools import setup, find_packages setup( name='2gis', version='1.3.1', author='svartalf', author_email='self@svartalf.info', url='https://github.com/svartalf/python-2gis', description='2gis library for Python', long_description=__doc__, license='BSD', packages=find_packages(), install_requires=('requests', 'six'), test_suite='tests', classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', ), )
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/setup.py
setup.py
try: import urlparse except ImportError: # Python 3 from urllib import parse as urlparse try: import unittest2 as unittest except ImportError: import unittest import mock import dgis from tests import MockGetRequest class MainTest(unittest.TestCase): def setUp(self): self.blank_response = { 'response_code': '200', } def test(self): api = dgis.API('1234567890') def validate(url): parts = urlparse.urlparse(url) query = urlparse.parse_qs(parts[4]) self.assertEqual(api.version, query['version'][0]) self.assertEqual(api.key, query['key'][0]) self.assertEqual(parts[1], api.host) validator = MockGetRequest(validate, self.blank_response) with mock.patch('requests.get', validator): api.project_list()
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/tests/main.py
main.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os try: import urlparse except ImportError: # Python 3 from urllib import parse as urlparse try: import unittest2 as unittest except ImportError: import unittest import mock import dgis from tests import MockGetRequest, load_response, skip_if_no_api_key class RubricatorTest(unittest.TestCase): def setUp(self): # From the `http://api.2gis.ru/doc/firms/list/rubricator/'_ self.response = load_response('rubricator.json') @unittest.skipIf(False, '') def test(self): api = dgis.API('1234567890') def validate(url): parts = urlparse.urlparse(url) query = urlparse.parse_qs(parts[4]) self.assertIn('where', query) # Boolean value should be converted into a integer self.assertIn('show_children', query) self.assertEqual('1', query['show_children'][0]) validator = MockGetRequest(validate, self.response) with mock.patch('requests.get', validator): api.rubricator(where='Иркутск', show_children=True) @skip_if_no_api_key def test_real(self): api = dgis.API(os.environ['DGIS_KEY']) response = api.rubricator(where='Иркутск', show_children=True) self.assertEqual(int(response['total']), len(response['result']))
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/tests/rubricator.py
rubricator.py
import os import json import functools try: import unittest2 as unittest except ImportError: import unittest def skip_if_no_api_key(func): wrapper = unittest.skipIf('DGIS_KEY' not in os.environ, 'Set environment variable DGIS_KEY to test real requests') return wrapper(func) class MockResponse(object): """Mock replacement for a response object returned by a `requests.get` function""" def __init__(self, json): self._json = json @property def json(self): return self._json @property def text(self): """This property is used only with a `register_views` parameter, so we can freely return a '1' text, which means, that view had been registered""" return '1' class MockGetRequest(object): """Mock replacement for a `requests.get` function""" def __init__(self, validator, json): self.validator = validator self.json = json def __call__(self, url): self.validator(url) return MockResponse(self.json) def load_response(filename): try: f = open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'responses', filename)) return json.load(f) finally: f.close()
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/tests/__init__.py
__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os try: import urlparse except ImportError: # Python 3 from urllib import parse as urlparse try: import unittest2 as unittest except ImportError: import unittest import mock import dgis from tests import MockGetRequest, load_response, skip_if_no_api_key class ProjectListTest(unittest.TestCase): def setUp(self): # From the `http://api.2gis.ru/doc/firms/list/project-list/'_ self.response = load_response('project_list.json') def test(self): api = dgis.API('1234567890') def validate(url): parts = urlparse.urlparse(url) query = urlparse.parse_qs(parts[4]) # Assert that there is no more any parameters self.assertEqual(len(query), 3) validator = MockGetRequest(validate, self.response) with mock.patch('requests.get', validator): api.project_list() @skip_if_no_api_key def test_real(self): api = dgis.API(os.environ['DGIS_KEY']) response = api.project_list() self.assertGreater(response['total'], 0) self.assertEqual(response['total'], len(response['result']))
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/tests/project_list.py
project_list.py
# -*- coding: utf-8 -*- import six def force_text(s, encoding='utf-8', errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. Based on the `django.utils.encoding.smart_str' (https://github.com/django/django/blob/master/django/utils/encoding.py) """ if not isinstance(s, six.string_types): try: return str(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return ' '.join([force_text(arg, encoding, errors) for arg in s]) return unicode(s).encode(encoding, errors) elif isinstance(s, six.text_type): return s.encode(encoding, errors) elif s and encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: return s
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/dgis/utils.py
utils.py
# -*- coding: utf-8 -*- import inspect try: import urlparse except ImportError: # Python 3 from urllib import parse as urlparse try: from urllib import urlencode except ImportError: # Python 3 from urllib.parse import urlencode import requests from dgis.exceptions import DgisError from dgis.utils import force_text __all__ = ('bind_api',) def __init__(self, api): self.api = api def execute(self, *args, **kwargs): # Build GET parameters for query parameters = {} # Both positional for idx, arg in enumerate(args): if arg is None: continue try: parameters[self.allowed_param[idx]] = force_text(arg) except IndexError: raise ValueError('Too many parameters supplied') # And keyword parameters for key, arg in kwargs.items(): if arg is None: continue if key in parameters: raise ValueError('Multiple values for parameter %s supplied' % key) parameters[key] = force_text(arg) parameters.update({ 'key': self.api.key, 'version': self.api.version, 'output': 'json', }) url = urlparse.urlunparse(['http', self.api.host, self.path, None, urlencode(parameters), None]) response = requests.get(url).json if inspect.ismethod(response): response = response() if response['response_code'] != '200': raise DgisError(int(response['response_code']), response['error_message'], response['error_code']) # Register view if required if self.register_views and self.api.register_views: if requests.get(response['register_bc_url']).text == '0': raise DgisError(404, 'View registration cannot be processed', 'registerViewFailed') return response def bind_api(**config): properties = { 'path': config['path'], 'method': config.get('method', 'GET'), 'allowed_param': config['allowed_param'], 'register_views': config.get('register_views', False), '__init__': __init__, 'execute': execute, } cls = type('API%sMethod' % config['path'].title().replace('/', ''), (object,), properties) def _call(api, *args, **kwargs): return cls(api).execute(*args, **kwargs) return _call
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/dgis/binder.py
binder.py
# -*- coding: utf-8 _-*- from dgis.binder import bind_api __version__ = '1.3.1' class API(object): """2GIS API""" def __init__(self, key, host='catalog.api.2gis.ru', version='1.3', register_views=True): """ Parameters:: key : user API key host : base URL for queries version : API version for working register_views : send information to stats server about a firm profile viewing """ self.key = key self.host = host self.version = version self.register_views = register_views """Projects lists http://api.2gis.ru/doc/firms/list/project-list/ """ project_list = bind_api( path='/project/list', allowed_param=[], ) """List of the project cities http://api.2gis.ru/doc/firms/list/city-list/ """ city_list = bind_api( path='/city/list', allowed_param=['where', 'project_id'] ) def rubricator(self, **kwargs): """Rubrics search http://api.2gis.ru/doc/firms/list/rubricator/ """ # `show_children' parameter must be an integer kwargs['show_children'] = int(kwargs.pop('show_children', False)) return self._rubricator(**kwargs) _rubricator = bind_api( path='/rubricator', allowed_param=['where', 'id', 'parent_id', 'show_children', 'sort'], ) def search(self, **kwargs): """Firms search http://api.2gis.ru/doc/firms/searches/search/ """ point = kwargs.pop('point', False) if point: kwargs['point'] = '%s,%s' % (point[0], point[1]) bound = kwargs.pop('bound', False) if bound: kwargs['bound[point1]'] = bound[0] kwargs['bound[point2]'] = bound[1] filters = kwargs.pop('filters', False) if filters: for k, v in filters.items(): kwargs['filters[%s]' % k] = v return self._search(**kwargs) _search = bind_api( path='/search', allowed_param=['what', 'where', 'point', 'radius', 'bound', 'page', 'pagesize', 'sort', 'filters'], ) def search_in_rubric(self, **kwargs): """Firms search in rubric http://api.2gis.ru/doc/firms/searches/searchinrubric/ """ point = kwargs.pop('point', False) if point: kwargs['point'] = '%s,%s' % point bound = kwargs.pop('bound', False) if bound: kwargs['bound[point1]'] = bound[0] kwargs['bound[point2]'] = bound[1] filters = kwargs.pop('filters', False) if filters: for k, v in filters.items(): kwargs['filters[%s]' % k] = v return self._search_in_rubric(**kwargs) _search_in_rubric = bind_api( path='/searchinrubric', allowed_param=['what', 'where', 'point', 'radius', 'bound', 'page', 'pagesize', 'sort', 'filters'], ) """Firm filials http://api.2gis.ru/doc/firms/searches/firmsbyfilialid/ """ firms_by_filial_id = bind_api( path='/firmsByFilialId', allowed_param=['firmid', 'page' 'pagesize'], ) """Adverts search http://api.2gis.ru/doc/firms/searches/adssearch/ """ ads_search = bind_api( path='/ads/search', allowed_param=['what', 'where', 'format', 'page', 'pagesize'], ) """Firm profile http://api.2gis.ru/doc/firms/profiles/profile/ """ profile = bind_api( path='/profile', allowed_param=['id', 'hash'], register_views=True, ) def geo_search(self, **kwargs): """Geo search http://api.2gis.ru/doc/geo/search/ """ if 'types' in kwargs: kwargs['types'] = ','.join(kwargs['types']) bound = kwargs.pop('bound', False) if bound: kwargs['bound[point1]'] = bound[0] kwargs['bound[point2]'] = bound[1] return self._geo_search(**kwargs) _geo_search = bind_api( path='/geo/search', allowed_param=['q', 'types', 'radius', 'limit', 'project', 'bound', 'format'], ) """Information about a geo object""" geo_get = bind_api( path='/geo/search', allowed_param=['id', ], )
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/dgis/__init__.py
__init__.py
# -*- coding: utf-8 -*- class DgisError(Exception): """2Gis API error""" def __init__(self, code, message, error_code): self.code = code self.message = message self.error_code = error_code def __str__(self): return self.message
2gis
/2gis-1.3.1.tar.gz/2gis-1.3.1/dgis/exceptions.py
exceptions.py
# Python 2ip Module **2ip** allows you to make requests to the 2ip.me API to retrieve provider/geographic information for IP addresses. Requests are (optionally, on by default) cached to prevent unnecessary API lookups when possible. ## Installation Install the module from PyPI: ```bash python3 -m pip install 2ip ``` ## Methods The following methods are available. ### TwoIP (Initialisation) When initialising the 2ip module the following parameters may be specified: * *Optional* `key`: The API key to use for lookups. If no API key defined the API lookups will use the rate limited free API. ### geo The geographic lookup method accepts the following parameters: * *Required* `ip`: The IP address to lookup. * *Optional* `format` {**json**,xml}: The output format for the request. `json` will return a dict and `xml` will return a string. * *Optional* `force` {True,**False**}: Force an API lookup even if there is a cache entry. * *Optional* `cache` {**True**,False}: Allow the lookup result to be cached. ### provider The provider lookup method accepts the following parameters: * *Required* `ip`: The IP address to lookup. * *Optional* `format` {**json**,xml}: The output format for the request. `json` will return a dict and `xml` will return a string. * *Optional* `force` {True,**False**}: Force an API lookup even if there is a cache entry. * *Optional* `cache` {**True**,False}: Allow the lookup result to be cached. ## Examples Some example scripts are included in the [examples](examples/) directory. ### Provider API Retrieve provider information for the IP address `192.0.2.0` as a `dict`: ```python >>> from twoip import TwoIP >>> twoip = TwoIP(key = None) >>> twoip.provider(ip = '192.0.2.0') {'ip': '192.0.2.0', 'ip_range_end': '3221226239', 'ip_range_start': '3221225984', 'mask': '24', 'name_ripe': 'Reserved AS', 'name_rus': '', 'route': '192.0.2.0'} ``` Retrieve provider information for the IP address `192.0.2.0` as a XML string: ```python >>> from twoip import TwoIP >>> twoip = TwoIP(key = None) >>> twoip.provider(ip = '192.0.2.0', format = 'xml') '<?xml version="1.0" encoding="UTF-8"?>\n<provider_api><ip>192.0.2.0</ip><name_ripe>Reserved AS</name_ripe><name_rus></name_rus><ip_range_start>3221225984</ip_range_start><ip_range_end>3221226239</ip_range_end><route>192.0.2.0</route><mask>24</mask></provider_api>' ``` ### Geographic API Retrieve geographic information for the IP address `8.8.8.8` as a `dict`: ```python >>> from twoip import TwoIP >>> twoip = TwoIP(key = None) >>> twoip.geo(ip = '8.8.8.8') {'city': 'Mountain view', 'country': 'United states of america', 'country_code': 'US', 'country_rus': 'США', 'country_ua': 'США', 'ip': '8.8.8.8', 'latitude': '37.405992', 'longitude': '-122.078515', 'region': 'California', 'region_rus': 'Калифорния', 'region_ua': 'Каліфорнія', 'time_zone': '-08:00', 'zip_code': '94043'} ``` Retrieve geographic information for the IP address `8.8.8.8` as a XML string: ```python >>> from twoip import TwoIP >>> twoip = TwoIP(key = None) >>> twoip.geo(ip = '8.8.8.8', format = 'xml') '<?xml version="1.0" encoding="UTF-8"?>\n<geo_api><ip>8.8.8.8</ip><country_code>US</country_code><country>United states of america</country><country_rus>США</country_rus><country_ua>США</country_ua><region>California</region><region_rus>Калифорния</region_rus><region_ua>Каліфорнія</region_ua><city>Mountain view</city><latitude>37.405992</latitude><longitude>-122.078515</longitude><zip_code>94043</zip_code><time_zone>-08:00</time_zone></geo_api>' ``` ## Roadmap/Todo - [ ] Support for email API - [ ] Support for MAC address API - [ ] Support for hosting API - [x] Option to retrieve data as XML - [ ] Unit tests - [x] Deduplicate handler to retrieve information from API
2ip
/2ip-0.0.2.tar.gz/2ip-0.0.2/README.md
README.md
#!/usr/bin/env python import os import sys from codecs import open from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) # 'setup.py publish' shortcut. if sys.argv[-1] == 'publish': os.system('python3 setup.py sdist bdist_wheel') os.system('python3 -m twine upload dist/*') sys.exit() about = {} with open(os.path.join(here, 'twoip', '__version__.py'), 'r', 'utf-8') as f: exec(f.read(), about) with open('README.md', 'r', 'utf-8') as f: readme = f.read() with open('requirements.txt', 'r', 'utf-8') as f: requires = f.read().splitlines() test_requirements = [ 'pytest' ] # If username is in the version file, append it to the package name if '__username__' in about: name = f'{about["__title__"]}-{about["__username__"]}' else: name = about['__title__'] setup( name=name, version=about['__version__'], description=about['__description__'], long_description=readme, long_description_content_type='text/markdown', author=about['__author__'], author_email=about['__author_email__'], url=about['__url__'], packages=find_packages(exclude=('tests',)), include_package_data=True, python_requires='>= 3.6', install_requires=requires, tests_require=test_requirements, license=about['__license__'], classifiers=[ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
2ip
/2ip-0.0.2.tar.gz/2ip-0.0.2/setup.py
setup.py
__title__ = '2ip' __description__ = '2ip.me API Client.' __url__ = 'https://github.com/python-modules/2ip' __version__ = '0.0.2' __author__ = 'gbe0' __author_email__ = 'python@gbe0.com' __license__ = 'MIT' __copyright__ = 'Copyright 2021 gbe0'
2ip
/2ip-0.0.2.tar.gz/2ip-0.0.2/twoip/__version__.py
__version__.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import requests from ipaddress import ip_address from typing import Optional, Union class TwoIP(object): """ 2ip.me API client """ # The API URL api = 'https://api.2ip.me' # List of available API endpoints endpoints = { 'ip': { 'geo': { 'format': [ 'json', 'xml' ], 'description': 'Geographic information for IP addresses', }, 'provider': { 'format': [ 'json', 'xml' ], 'description': 'Provider information for IP addresses', }, }, } def __init__(self, key: Optional[str] = None) -> object: """Set up new 2ip.me API client. Parameters ---------- key : str, optional Optional API key to use for requests to the API Returns ------- TwoIP : object The TwoIP API object Examples -------- >>> twoip = TwoIP(key = None) """ # Set API key self.__key = key # Create empty cache self.__cache = {} for endpoint_type in self.endpoints: for type in self.endpoints[endpoint_type]: self.__cache[type] = {} for format in self.endpoints[endpoint_type][type]['format']: self.__cache[type][format] = {} # Debugging if key: logging.debug(f'Setup of new TwoIP object') else: logging.debug(f'Setup of new TwoIP object (No API key used - rate limits will apply)') @staticmethod def __api_request(url: str, params: Optional[dict] = None) -> object: """Send request to the 2ip API and return the requests object. Parameters ---------- url : str The URL to send request to params : dict, Optional Optional GET parameters to add to the request Returns ------- object The requests object Raises ------ RuntimeError If the API request fails """ # Send the request try: req = requests.request(method = 'GET', url = url, params = params) except Exception as e: raise RuntimeError('API request failed') from e # Make sure API request didn't result in rate limit if req.status_code == 429: raise RuntimeError(f'API has reached rate limit; retry in an hour or use an API key') # Make sure response code is fine if req.status_code != 200: raise RuntimeError(f'Received unexpected response code "{req.status_code}" from API') # Return the requests object return req def __api_param(self, params: dict) -> dict: """Add API key to the list of parameters for the API request if available. Parameters ---------- params : dict The parameters to add API key to Returns ------- dict The built parameter list """ # Add API key if available if self.__key: params['key'] = self.__key # Return params return params @staticmethod def __test_ip(ip: str) -> bool: """Test if the IP address provided is really an IP address. Parameters ---------- params : ip The IP address to test Returns ------- bool True if the string provided is an IP address or False if it is not an IP address """ logging.debug(f'Testing if "{ip}" is a valid IP address') # Check for exception when creating an ip_address object try: ip_address(ip) except Exception as e: logging.error(f'Could not validate string "{ip}" as an IP address: {e}') return False # IP provided is valid return True def __execute_ip(self, ip: str, format: str, type: str) -> Union[dict, str]: """Execute an API lookup for an IP address based provider (geographic information or provider information) Parameters ---------- ip : str The IP address to lookup format : {'json', 'xml'} The format for which results should be returned - json results will be returned as a dict type : {'geo','provider'} The API type to lookup ('geo' for geographic information or 'provider' for provider information) Returns ------- dict or str The lookup result in either dict format (for JSON lookups) or string format (for XML lookups) """ # Make sure there is an endpoint for the requested type if not self.endpoints['ip'][type]: raise ValueError(f'Invalid lookup type "{type}" requested') # Make sure that the format selected is valid if format not in self.endpoints['ip'][type]['format']: raise ValueError(f'The "{type}" API endpoint does not support the requested format "{format}"') # Build the API URL that the request will be made to url = f'{self.api}/{type}.{format}' # Set the parameters for the request (this will add the API key if available) params = self.__api_param({'ip': ip}) # Send API request try: response = self.__api_request(url = url, params = params) except Exception as e: logging.error('Failed to send API request: {e}') raise RuntimeError('Could not run API lookup') from e # Make sure content type of the response is expected if response.headers.get('Content-Type') != f'application/{format}': if response.headers.get('Content-Type'): raise RuntimeError(f'Expecting Content-Type header "application/{format}" but got "{req.headers.get("Content-Type")}"') else: raise RuntimeError(f'API request did not provide any Content-Type header') # If the format requests is XML, return it immediately otherwise attempt to parse the json response into a dict if format == 'xml': return response.text elif format == 'json': try: json = response.json() except Exception as e: raise RuntimeError('Exception parsing response from API as json') from e return json else: raise RuntimeError(f'No output handler configured for the output format "{format}"') def geo(self, ip: str, format: str = 'json', force: bool = False, cache: bool = True) -> Union[dict, str]: """Perform a Geographic information lookup to the 2ip API. By default, lookups will be cached. Subsequent lookups will use the cache (unless disabled) to prevent excessive API requests. Parameters ---------- ip : str The IP address to lookup format : {'xml','json'} The requested output format - JSON will result in a dict otherwise XML will result in a str force : bool, default = False Force request to be sent to the API even if the lookup has already been cached cache: bool, default = True Allow caching of the request (cache can still be bypassed by using the force parameter) Returns ------- dict or str The response from API in either a dictionary (if the format is set to json) or a string (if the format is set to XML) Raises ------ ValueError Invalid IP address or invalid output format requested RuntimeError API request failure Examples -------- >>> twoip = TwoIP(key = '12345678') >>> twoip.geo(ip = '192.0.2.0') {'ip': '192.0.2.0', 'country_code': '-', 'country': '-', 'country_rus': 'Неизвестно', 'country_ua': 'Невідомо', 'region': '-', 'region_rus': 'Неизвестно', 'region_ua': 'Невідомо', 'city': '-', 'city_rus': 'Неизвестно', 'city_ua': 'Невідомо', 'zip_code': '-', 'time_zone': '-'} """ # Make sure IP address provided is valid if self.__test_ip(ip = ip): logging.debug(f'2ip geo API lookup request for IP "{ip}" (force: {force})') else: raise ValueError(f'Could not run geo lookup for invalid IP address "{ip}"') # If the lookup is cached and this is not a forced lookup, return the cached result if ip in self.__cache['geo'][format]: logging.debug(f'Cached API entry available for IP "{ip}"') if force: logging.debug('Cached entry will be ignored for lookup; proceeding with API request') else: logging.debug('Cached entry will be returned; use the force parameter to force API request') return self.__cache['geo'][format][ip] # Run the request response = self.__execute_ip(ip = ip, format = format, type = 'geo') # Cache the response if allowed if cache: self.__cache['geo'][format][ip] = response # Return response return response def provider(self, ip: str, format: str = 'json', force: bool = False, cache: bool = True) -> Union[dict, str]: """Perform a provider information lookup to the 2ip API. By default, lookups will be cached. Subsequent lookups will use the cache (unless disabled) to prevent excessive API requests. Parameters ---------- ip : str The IP address to lookup format : {'xml','json'} The requested output format - JSON will result in a dict otherwise XML will result in a str force : bool, default = False Force request to be sent to the API even if the lookup has already been cached cache: bool, default = True Allow caching of the request (cache can still be bypassed by using the force parameter) Returns ------- dict or str The response from API in either a dictionary (if the format is set to json) or a string (if the format is set to XML) Raises ------ ValueError Invalid IP address or invalid output format requested RuntimeError API request failure Examples -------- >>> twoip = TwoIP(key = '12345678') >>> twoip.provider(ip = '192.0.2.0') {'ip': '192.0.2.0', 'name_ripe': 'Reserved AS', 'name_rus': '', 'ip_range_start': '3221225984', 'ip_range_end': '3221226239', 'route': '192.0.2.0', 'mask': '24'} """ # Make sure IP address provided is valid if self.__test_ip(ip = ip): logging.debug(f'2ip provider API lookup request for IP "{ip}" (force: {force})') else: raise ValueError(f'Could not run provider lookup for invalid IP address "{ip}"') # If the lookup is cached and this is not a forced lookup, return the cached result if ip in self.__cache['provider'][format]: logging.debug(f'Cached API entry available for IP "{ip}"') if force: logging.debug('Cached entry will be ignored for lookup; proceeding with API request') else: logging.debug('Cached entry will be returned; use the force parameter to force API request') return self.__cache['provider'][format][ip] # Run the request response = self.__execute_ip(ip = ip, format = format, type = 'provider') # Cache the response if allowed if cache: self.__cache['provider'][format][ip] = response # Return response return response
2ip
/2ip-0.0.2.tar.gz/2ip-0.0.2/twoip/twoip.py
twoip.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python API client for 2ip.me This API client will send requests for various information to 2ip.me and provide a response in either XML or JSON. """ # Import logging import logging from logging import NullHandler # Import TwoIP class from .twoip import TwoIP # Set default logging handler to avoid "No handler found" warnings. logging.getLogger(__name__).addHandler(NullHandler()) # Set default logging format logging.basicConfig( format='%(asctime)s,%(msecs)03d %(levelname)-7s [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d:%H:%M:%S', level=logging.WARN, ) " Do nothing if running module directly " if __name__ == '__main__': raise RuntimeError('This module contains functions for use in other modules; do not use it directly.')
2ip
/2ip-0.0.2.tar.gz/2ip-0.0.2/twoip/__init__.py
__init__.py
from setuptools import find_packages, setup setup( name = '2jjtt6cwa6', packages=find_packages(), version = '0.1', description = '', author = '', author_email = '', url = '', keywords = [], classifiers = [], )
2jjtt6cwa6
/2jjtt6cwa6-0.1.tar.gz/2jjtt6cwa6-0.1/setup.py
setup.py
########## 2lazy2rest ########## A simple way to produce short-to-medium document using *reStructuredText* Multi-format themes Render the same document in HTML, ODT, PDF keeping the main visual identity Unified interface - Tired of switching between rst2* tools having different arguments or behavior ? - Would like to not lose *code-blocks* or some rendering options switching the output format ? This tool try to address this Make your own theme TODO: templates will be customizable easily (say, probably colors only) How to use it ############# Dependencies ============ You'll need **rst2pdf** to use all the features, other rst2* tools are coming from docutils. Using ===== .. code-block:: console mkrst [-h] [--html] [--pdf] [--odt] [--theme THEME] [--themes-dir THEMES_DIR] FILE optional arguments: -h, --help show this help message and exit --html Generate HTML output --pdf Generate PDF output --odt Generate ODT output --theme THEME Use a different theme --themes-dir THEMES_DIR Change the folder searched for theme .. code-block:: console popo:~/2lazy2rest% ./mkrst test_page.rst --html --pdf Using ./themes/default html: test_page.html pdf: test_page.pdf Customizing =========== Make a copy of ``themes/default``, edit to your needs the copy and use the **--theme** option with the name of your copy, that's All ! Example ------- .. code-block:: console popo:~/2lazy2rest% cp -r themes/default themes/red popo:~/2lazy2rest% sed -si 's/#FEFEFE/red/g' themes/red/html/stylesheet.css popo:~/2lazy2rest% ./mkrst test_page.rst --html --theme red Issues ###### - ODT style is unfinished - PDF & HTML still needs more ReST coverage - No skin generation from template yet
2lazy2rest
/2lazy2rest-0.2.2.tar.gz/2lazy2rest-0.2.2/README.rst
README.rst
#!/usr/bin/env python from __future__ import absolute_import, print_function import argparse import importlib.util import os import subprocess import mkrst_themes THEMES_DIR = os.path.dirname(mkrst_themes.__file__) THEME = "default" SUPPORTED_FORMATS = "html pdf odt".split() DEBUG = "DEBUG" in os.environ class CommandExecutor: GENERAL_OPTIONS = ["--syntax-highlight=short", "--smart-quotes=yes"] def __init__(self, opts: argparse.Namespace): self._src: str = opts.input self._verbose: bool = opts.verbose self._extensions: str = opts.ext def set_theme(self, path: str, name: str) -> None: if os.path.exists(name): self.theme_dir = os.path.abspath(name) else: self.theme_dir = os.path.join(path, name) print("Using %s" % self.theme_dir) def _list_resources(self, origin: str, extension: str) -> list[str]: r = [] for fname in os.listdir(os.path.join(self.theme_dir, origin)): if fname.endswith(extension): r.append(os.path.join(self.theme_dir, origin, fname)) r.sort() if DEBUG: print("List(*%s) = %s" % (extension, ", ".join(r))) return r def get_output(self, fmt: str) -> str: return self._src.rsplit(".", 1)[0] + "." + fmt def __execute(self, args: list[str]) -> None | tuple[bytes, bytes]: if DEBUG: print("Executing %s" % " ".join(args)) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() def show_result() -> None: print("\nStdout:") print(out.decode("utf-8").strip()) print("\nStderr:") print(err.decode("utf-8").strip()) if proc.returncode == 0: if self._verbose: show_result() return (out, err) else: print(" PROBLEM! ".center(80, "#")) show_result() return None def make_pdf(self) -> None: out = self.get_output("pdf") opts = [o for o in self.GENERAL_OPTIONS if "syntax" not in o] opts += ["--font-path", os.path.join(self.theme_dir, "fonts")] args = [ "rst2pdf", "--fit-background-mode=scale", "--use-floating-images", "--real-footnotes", "-e", "preprocess", ] + opts for style in self._list_resources("pdf", ".yaml"): args.extend(("-s", style)) if self._extensions: args.extend(("-e", self._extensions)) args.extend(("-o", out, self._src)) if self.__execute(args): print(out) def make_odt(self) -> None: out = self.get_output("odt") css = self._list_resources("odt", "odt")[0] args = ["rst2odt"] + self.GENERAL_OPTIONS + ["--add-syntax-highlighting", "--stylesheet", css, self._src, out] if self.__execute(args): print(out) def make_html(self) -> None: out = self.get_output("html") css = ",".join(self._list_resources("html", "css")) args = ["rst2html"] + self.GENERAL_OPTIONS + ["--embed-stylesheet", "--stylesheet-path", css, self._src, out] if self.__execute(args): print(out) # post process links = os.path.join(self.theme_dir, "html", "links.html") if os.path.exists(links): data = open(out).read() data = data.replace("<html>", "<html>\n" + open(links).read()) open(out, "w").write(data) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="store_true", help="Display commands' output") parser.add_argument( "input", type=str, metavar="FILE", nargs="?", help="The .rst or .txt file to convert", ) for fmt in SUPPORTED_FORMATS: parser.add_argument("--%s" % fmt, action="store_true", help="Generate %s output" % fmt.upper()) parser.add_argument("-t", "--theme", type=str, default=THEME, help="Use a different theme") parser.add_argument( "--themes-dir", type=str, default=THEMES_DIR, help="Change the folder searched for theme", ) parser.add_argument("--ext", type=str, default="", help="Load docutils extensions (coma separated)") parser.add_argument("-l", "--list", action="store_true", help="List available themes") args = parser.parse_args() cmd = CommandExecutor(args) cmd.set_theme(args.themes_dir, args.theme) if args.list: for t in os.listdir(THEMES_DIR): if t[0] not in "_." and os.path.isdir(os.path.join(THEMES_DIR, t)): print(t) elif not any(getattr(args, fmt) for fmt in SUPPORTED_FORMATS): print("No action ! Give one or more --(%s)" % "|".join(SUPPORTED_FORMATS)) else: if not args.input: print("No input file !") else: for fmt in SUPPORTED_FORMATS: if getattr(args, fmt): fn = getattr(cmd, "make_%s" % fmt) print(" %5s: " % fmt, end="") fn() if __name__ == "__main__": main()
2lazy2rest
/2lazy2rest-0.2.2.tar.gz/2lazy2rest-0.2.2/mkrst/__init__.py
__init__.py
from distutils.core import setup setup( # Application name: name="2mp3", # Version number (initial): version="0.1.0", # Application author details: author="komuW", author_email="komuw05@gmail.com", # Packages packages=["2mp3"], # Include additional files into the package include_package_data=True, # Details url="http://pypi.python.org/pypi/2mp3_v010/", # # license="LICENSE.txt", description="convert your media files to mp3", # long_description=open("README.txt").read(), # Dependent packages (distributions) install_requires=[ "envoy", ], )
2mp3
/2mp3-0.1.0.tar.gz/2mp3-0.1.0/setup.py
setup.py
import subprocess import sys from collections import namedtuple from setuptools import setup, find_packages classifiers = """\ Intended Audience :: End Users/Desktop License :: OSI Approved :: MIT License Programming Language :: Python Topic :: Multimedia :: Video :: Conversion Operating System :: Unix """ try: p = subprocess.Popen( ['git', 'describe', '--tags'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False ) p.wait() except: p = namedtuple('Process', 'returncode')(1) if p.returncode == 0: version = p.communicate()[0].strip().decode() with open('.version', 'w+') as version_file: version_file.write(version) else: with open('.version', 'r') as version_file: version = version_file.readline().strip() requirements = ['sh', 'progressbar2', 'pymediainfo'] if sys.version_info[0] == 3: requirements.extend(['beautifulsoup4', 'lxml']) setup( name='2mp4', version=version, url='https://github.com/skonakov/2mp4.git', download_url='https://github.com/skonakov/2mp4/tarball/' + version, license='MIT', description='Simple utility to convert your video files into mp4s.', author='Sergey Konakov', author_email='skonakov@gmail.com', packages=find_packages('src'), package_dir={'': 'src'}, package_data={'': ['../../.version']}, install_requires=requirements, zip_safe=False, entry_points="""\ [console_scripts] 2mp4 = 2mp4.2mp4:main """, classifiers=filter(None, classifiers.split('\n')), #long_description=read('README.rst') + '\n\n' + read('CHANGES'), #extras_require={'test': []} )
2mp4
/2mp4-0.2.1.tar.gz/2mp4-0.2.1/setup.py
setup.py
This is a continually-updated market data analysis machine learning transformer model intended for summarizing & interpreting market & economic data. To use: 1. gh repo clone sscla1/2op_ai 2. install requirements.txt wherever running your application 3. import statement: from 2op_ai import ai_pipeline 4. use case for summarizer & interpreter def summarize_text(self, text): """ Summarizes the provided text. Args: text (str): The text to be summarized. Returns: str: The summarized text. """ try: # Perform text summarization using AI pipeline summary = self.ai_pipeline(text, max_length=600)[0]['summary_text'] return summary except Exception as e: logging.error(f"An error occurred when trying to summarize text: {e}") return "" def generate_interpretation(self, summary): """ Generates interpretation for the summary using the AI pipeline. Args: summary (str): The summary to generate interpretation for. Returns: str or None: The generated interpretation or None if an error occurs. """ logging.info("Attempting to generate interpretation.") try: input_text = "Explain the provided data, its affect on the market, and specific sectors, in layman's terms, in 300 words or less: " + summary interpretation = self.ai(input_text, max_length=300, do_sample=True)[0]['generated_text'] return interpretation except Exception as e: logging.error(f"An error occurred when trying to generate interpretation: {e}") return None
2op-ai
/2op_ai-0.1.tar.gz/2op_ai-0.1/README.md
README.md
from setuptools import setup, find_packages setup( name='2op_ai', version='0.1', description='A package for fine-tuning and utilizing the 2op_ai model', author='Your Name', author_email='sscla-ops@outlook.com', url='https://github.com/sscla1/2op_ai', packages=find_packages(), install_requires=[ 'torch', 'transformers', 'pandas', 'nbformat', 'chardet', ], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', # Modify as needed 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], keywords='machine-learning transformers fine-tuning ai', )
2op-ai
/2op_ai-0.1.tar.gz/2op_ai-0.1/setup.py
setup.py
import logging import os import pandas as pd import nbformat from nbconvert import PythonExporter import chardet import pdb class DataProcessor: def __init__(self, data_dir): # Initialize the data directory and logger self.data_dir = data_dir self.logger = self.setup_logging() def setup_logging(self): # Set up logging with both console and file handlers logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) log_file_path = os.path.join(self.data_dir, "data_processing.log") file_handler = logging.FileHandler(log_file_path) file_handler.setFormatter(formatter) logger.addHandler(file_handler) return logger def export_notebook_to_script(self, notebook_path, script_path): # Export Jupyter Notebook to a Python script nb = nbformat.read(notebook_path, as_version=nbformat.NO_CONVERT) exporter = PythonExporter() python_code, _ = exporter.from_notebook_node(nb) with open(script_path, "w") as f: f.write(python_code) def load_csv(self, file_path, encoding='utf-8', dtype=None): # Load CSV file with error handling for different encodings try: with open(file_path, 'rb') as f: result = chardet.detect(f.read()) file_encoding = result['encoding'] return pd.read_csv(file_path, encoding=file_encoding, dtype=dtype, low_memory=False) except UnicodeDecodeError: self.logger.warning(f"UnicodeDecodeError encountered while loading CSV '{file_path}' with encoding '{encoding}'. Trying 'latin-1' encoding.") try: return pd.read_csv(file_path, encoding='latin-1', dtype=dtype, low_memory=False) except Exception as e: self.logger.error(f"Error loading CSV '{file_path}' with 'latin-1' encoding: {e}") return None except Exception as e: self.logger.error(f"Error loading CSV '{file_path}': {e}") return None def load_excel(self, file_path, encoding='utf-8'): # Load Excel file with error handling for different encodings try: return pd.read_excel(file_path, engine='openpyxl') except UnicodeDecodeError: self.logger.warning(f"UnicodeDecodeError encountered while loading Excel '{file_path}' with encoding '{encoding}'. Trying 'latin-1' encoding.") try: return pd.read_excel(file_path, engine='openpyxl', encoding='latin-1') except Exception as e: self.logger.error(f"Error loading Excel '{file_path}' with 'latin-1' encoding: {e}") return None except Exception as e: self.logger.error(f"Error loading Excel '{file_path}': {e}") return None def process_sroie_files(self, directory): # Process SROIE files from the given directory sroie_data = [] for root, _, files in os.walk(directory): for file in files: if file.endswith('.txt'): file_path = os.path.join(root, file) try: with open(file_path, 'rb') as txt_file: raw_data = txt_file.read() detected_encoding = chardet.detect(raw_data)['encoding'] text_data = raw_data.decode(detected_encoding) sroie_data.append(text_data) except Exception as e: self.logger.error(f"Error reading '{file_path}': {e}") sroie_df = pd.DataFrame({'data': sroie_data}) return sroie_df def process_data(self): # Process various data files and concatenate them into a single dataset try: breakpoint() root_dir = os.path.join(self.data_dir) # Load files currency_data = self.load_csv(os.path.join(root_dir, 'currency.csv')) fortune500_data = self.load_csv(os.path.join(root_dir, 'fortune500.csv')) msft_data = self.load_csv(os.path.join(root_dir, 'msft.csv')) snp_data = self.load_csv(os.path.join(root_dir, 's&p.csv')) balancesheets_data = self.load_csv(os.path.join(root_dir, 'bank_fail', 'balancesheets.csv')) banklist_data = self.load_csv(os.path.join(root_dir, 'bank_fail', 'banklist.csv')) final_datasets_dir = os.path.join(root_dir, 'income', 'final_datasets') final_datasets_files = [ 'Final_32_region_deciles_1958-2015.csv', 'Final_Global_Income_Distribution.csv', 'Final_Historical_data_ISO.csv' ] final_datasets_data = pd.concat( [pd.read_csv(os.path.join(final_datasets_dir, file)) for file in final_datasets_files] ) input_data_dir = os.path.join(root_dir, 'income', 'input_data') input_data_files = [ 'WDI_GINI_data.csv' ] input_data = pd.concat( [pd.read_csv(os.path.join(input_data_dir, file)) for file in input_data_files] ) mapping_files_dir = os.path.join(root_dir, 'income', 'mapping_files') mapping_files_files = [ 'GCAM_region_names.csv', 'WIDER_mapping_file.csv' ] mapping_files = pd.concat( [pd.read_csv(os.path.join(mapping_files_dir, file)) for file in mapping_files_files] ) train_dataset = pd.concat([currency_data, fortune500_data, msft_data, snp_data, balancesheets_data, banklist_data, final_datasets_data, input_data, mapping_files]) etfs_dir = os.path.join(root_dir, 'nasdaq', 'etfs') etfs_files = [file for file in os.listdir(etfs_dir) if file.endswith('.csv')] etfs_data = pd.concat([pd.read_csv(os.path.join(etfs_dir, file)) for file in etfs_files]) stocks_dir = os.path.join(root_dir, 'nasdaq', 'stocks') stocks_files = [file for file in os.listdir(stocks_dir) if file.endswith('.csv')] stocks_data = pd.concat([pd.read_csv(os.path.join(stocks_dir, file)) for file in stocks_files]) symbols_valid_meta_data = self.load_csv(os.path.join(root_dir, 'nasdaq', 'symbols_valid_meta.csv')) train_dataset = pd.concat([train_dataset, etfs_data, stocks_data, symbols_valid_meta_data]) news_dir = os.path.join(root_dir, 'news') news_files = [file for file in os.listdir(news_dir) if file.endswith('.csv')] news_data = pd.concat([pd.read_csv(os.path.join(news_dir, file)) for file in news_files]) train_dataset = pd.concat([train_dataset, news_data]) prediction_dir = os.path.join(root_dir, 'prediction') prediction_files = [file for file in os.listdir(prediction_dir) if file.endswith('.csv')] prediction_data = pd.concat([pd.read_csv(os.path.join(prediction_dir, file)) for file in prediction_files]) train_dataset = pd.concat([train_dataset, prediction_data]) sroie_dir = os.path.join(root_dir, 'sroie') sroie_df = self.process_sroie_files(sroie_dir) breakpoint() train_dataset = pd.concat([train_dataset, sroie_df]) # Concatenate sroie_df with the train_dataset self.logger.info("Data processing completed successfully.") return train_dataset except Exception as e: self.logger.error(f"An error occurred during data processing: {e}") return None if __name__ == "__main__": script_dir = os.path.dirname(os.path.abspath(__file__)) project_dir = os.path.dirname(script_dir) data_dir = os.path.join(project_dir, "training_data") data_processor = DataProcessor(data_dir) currency_data = data_processor.load_csv(os.path.join(data_processor.data_dir, 'currency.csv')) print("Currency Data:", currency_data) fortune500_data = data_processor.load_csv(os.path.join(data_processor.data_dir, 'fortune500.csv')) print("Fortune500 Data:", fortune500_data) msft_data = data_processor.load_csv(os.path.join(data_processor.data_dir, 'msft.csv')) print("MSFT Data:", msft_data) snp_data = data_processor.load_csv(os.path.join(data_processor.data_dir, 's&p.csv')) print("S&P Data:", snp_data) breakpoint() trained_dataset = data_processor.process_data() if trained_dataset is not None: print("Data processing completed successfully.") trained_dataset.to_csv(os.path.join(data_dir, "trained_dataset.csv"), index=False) else: print("Data processing failed.")
2op-ai
/2op_ai-0.1.tar.gz/2op_ai-0.1/src/processing.py
processing.py
import os import logging import torch from transformers import AutoTokenizer, AutoModelForCausalLM from processing import DataProcessor from finetuning import finetune_model def main(): # Get the directory of the currently executing script script_dir = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") try: # Instantiate the tokenizer and model tokenizer = AutoTokenizer.from_pretrained("Salesforce/xgen-7b-8k-base", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("Salesforce/xgen-7b-8k-base", torch_dtype=torch.bfloat16) # Set up fine-tuning parameters num_epochs = 10 batch_size = 16 learning_rate = 1e-5 # Construct the project directory path using the script's directory project_dir = os.path.dirname(script_dir) data_dir = os.path.join(project_dir, "training_data") print("Instantiating DataProcessor...") data_processor = DataProcessor(data_dir) print("Processing data...") trained_dataset = data_processor.process_data() # Only train dataset for fine-tuning if trained_dataset is not None: # Calculate validation dataset (val_dataset) for fine-tuning val_dataset = trained_dataset.sample(frac=0.2, random_state=42) trained_dataset.to_csv(os.path.join(data_dir, "trained_dataset.csv"), index=False) else: logging.error("Data processing failed.") return # Fine-tune the model using the imported function print("Fine-tuning model...") finetune_model(model, trained_dataset, val_dataset, num_epochs, batch_size, learning_rate) logging.info("Fine-tuning completed successfully.") # Example usage for aipipeline, summarizer, and interpreter from transformers import pipeline, TextGenerationPipeline # Create an AI pipeline aipipeline = pipeline("text-generation", model=model, tokenizer=tokenizer) # Summarizer summarizer = TextGenerationPipeline(model=model, tokenizer=tokenizer) # Interpreter def interpret(text): inputs = tokenizer(text, return_tensors="pt") outputs = model(**inputs) predicted_class = torch.argmax(outputs.logits, dim=-1).item() return predicted_class except Exception as e: logging.error(f"An error occurred: {e}") raise if __name__ == "__main__": main()
2op-ai
/2op_ai-0.1.tar.gz/2op_ai-0.1/src/main.py
main.py
import logging import os import torch from transformers import AutoTokenizer, AutoModelForCausalLM from processing import DataProcessor logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") def finetune_model(model, train_dataset, val_dataset, num_epochs, batch_size, learning_rate): try: # Instantiate the tokenizer with the unk_token set tokenizer = AutoTokenizer.from_pretrained( "Salesforce/xgen-7b-8k-base", unk_token="<unk>", # Set the unk_token trust_remote_code=True ) # Enable token tracing tokenizer._tokenizer.enable_tracing() # Set up the optimizer and loss function, data loaders, and fine-tuning loop optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate) loss_fn = torch.nn.CrossEntropyLoss() train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size) # Fine-tuning loop for epoch in range(num_epochs): model.train() for inputs, labels in train_loader: optimizer.zero_grad() # Tokenize the text using the tokenizer tokenized_inputs = tokenizer(inputs, return_tensors="pt", padding=True, truncation=True) outputs = model(**tokenized_inputs) logits = outputs.logits loss = loss_fn(logits, labels) loss.backward() optimizer.step() model.eval() with torch.no_grad(): total_loss = 0.0 total_correct = 0 total_samples = 0 for inputs, labels in val_loader: # Tokenize the text using the tokenizer tokenized_inputs = tokenizer(inputs, return_tensors="pt", padding=True, truncation=True) outputs = model(**tokenized_inputs) logits = outputs.logits loss = loss_fn(logits, labels) total_loss += loss.item() _, predicted = torch.max(logits, 1) total_correct += (predicted == labels).sum().item() total_samples += labels.size(0) # Calculate val_loss and val_accuracy val_loss = total_loss / len(val_loader) val_accuracy = total_correct / total_samples logging.info(f"Epoch {epoch+1}: Val Loss = {val_loss:.4f}, Val Accuracy = {val_accuracy:.4f}") # Disable token tracing tokenizer._tokenizer.disable_tracing() except Exception as e: logging.error(f"An error occurred during fine-tuning: {e}") raise if __name__ == "__main__": # Get the directory of the currently executing script script_dir = os.path.dirname(os.path.abspath(__file__)) # Construct the project directory path using the script's directory project_dir = os.path.dirname(script_dir) data_dir = os.path.join(project_dir, "training_data") # Construct the data directory path # Instantiate the DataProcessor class data_processor = DataProcessor(data_dir) # Load and process the datasets trained_dataset = data_processor.process_data() if trained_dataset is not None: # Calculate batch size and learning rate batch_size = 32 num_samples = len(trained_dataset) num_epochs = 5 learning_rate = 1e-4 # Calculate validation dataset (val_dataset) for fine-tuning val_dataset = trained_dataset.sample(frac=0.2, random_state=42) # Instantiate the model for fine-tuning model = AutoModelForCausalLM.from_pretrained("Salesforce/xgen-7b-8k-base") # Fine-tune the model using the train_dataset and val_dataset finetune_model(model, trained_dataset, val_dataset, num_epochs, batch_size, learning_rate) logging.info("Fine-tuning completed successfully.") else: logging.error("Data processing failed.")
2op-ai
/2op_ai-0.1.tar.gz/2op_ai-0.1/src/finetuning.py
finetuning.py
from setuptools import setup import ast import os def version(): """Return version string.""" with open(os.path.join('lib2or3', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s setup(name='2or3', version=version(), description='Writes a single byte to stdout (either "2" or "3") classifying a Python file using heuristics, giving priority to 3 if unclear', url='https://github.com/thomasballinger/2or3', author='Thomas Ballinger', author_email='thomasballinger@gmail.com', license='MIT', packages=['lib2or3'], scripts=['scripts/2or3', 'scripts/ispy2', 'scripts/ispy3'])
2or3
/2or3-0.1.0.tar.gz/2or3-0.1.0/setup.py
setup.py
__version__ = '0.1.0' import os import sys import re # TODO use ast # TODO use 2to3 # TODO use pyflakes def classify_string(s): "Returns 2 or 3 based on a string s of Python source code, defaulting to 3" first_line = s.splitlines()[0] if '#!' in first_line: if 'python3' in first_line: return 3 elif 'python2' in first_line: return 2 if 'yield from' in s: return 3 if 'Error, e' in s: return 2 if 'xrange' in s: return 2 if (re.search(r'''u"[^"]*"[.]decode''', s) or re.search(r'''u'[^']*'[.]decode''', s) or re.search(r'''b"[^"]*"[.]encode''', s) or re.search(r'''b'[^']*'[.]encode''', s)): return 2 return 3 def has_pycache(filename): "Returns bool for if there exists a __pycache__ directory next to a file" neighbors = os.listdir(os.path.dirname(os.path.abspath(filename))) if '__pycache__' in neighbors: return True else: return False def pycache_classify(filename): """Returns 3, 2, or None for prediction from __pycache__ directory prefers 3 if both found, returns None if neither found""" dirname, name = os.path.split(os.path.abspath(filename)) neighbors = os.listdir(dirname) if '__pycache__' in neighbors: classifications = [ n[-6:-5] for n in os.listdir(os.path.join(dirname, '__pycache__')) if n.split('.', 1)[0] == name.split('.', 1)[0]] if '3' in classifications: return 3 elif '2' in classifications: return 2 return None def classify(filename): r = pycache_classify(filename) if r: return r return classify_string(open(filename).read()) def main(error_if_not=None): """Writes 2 or 3 and a newline to stdout, uses exit code for error_if_not""" r = classify(sys.argv[-1]) print r if error_if_not is not None: sys.exit(0 if r == error_if_not else r) if __name__ == '__main__': main()
2or3
/2or3-0.1.0.tar.gz/2or3-0.1.0/lib2or3/__init__.py
__init__.py
from tuprolog import Info from tuprolog.core import * from tuprolog.core.comparators import * from tuprolog.core.exception import * from tuprolog.core.formatters import * from tuprolog.core.operators import * from tuprolog.core.visitors import * from tuprolog.core.parsing import * from tuprolog.unify import * from tuprolog.unify.exception import * from tuprolog.theory import * from tuprolog.theory.parsing import * from tuprolog.solve import * from tuprolog.solve.exception import * from tuprolog.solve.exception.error import * from tuprolog.solve.exception.warning import * from tuprolog.solve.channel import * from tuprolog.solve.flags import * from tuprolog.solve.function import * from tuprolog.solve.primitive import * from tuprolog.solve.sideffcts import * from tuprolog.solve.library import * from tuprolog.solve.library.exception import * from tuprolog.solve.data import * from tuprolog.solve.stdlib import * from tuprolog.solve.stdlib.primitive import * from tuprolog.solve.stdlib.rule import * from tuprolog.solve.stdlib.function import * from tuprolog.solve.classic import * from tuprolog.solve.prolog import * from tuprolog.solve.plp import * from tuprolog.solve.problog import * from tuprolog.solve.problog.operators import * import code code.interact(local=locals()) input()
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/__main__.py
__main__.py
from typing import Iterable, Mapping, TypeVar, Union, Callable T = TypeVar('T') R = TypeVar('R') def iterable_or_varargs( args: Union[Iterable[T], Iterable[Iterable[T]]], dispatch: Callable[[Iterable[T]], R] = lambda x: x ) -> R: assert isinstance(args, Iterable) if len(args) == 1: item = args[0] if isinstance(item, Iterable): return dispatch(item) else: return dispatch([item]) else: return dispatch(args) def dict_or_keyword_args( dictionary: Mapping[str, T], kwargs: Mapping[str, T], dispatch: Callable[[Mapping[str, T]], R] = lambda x: x ) -> R: all_data = dict() for k in dictionary: all_data[k] = dictionary[k] for k in kwargs: all_data[k] = kwargs[k] return dispatch(all_data) def and_then(continuation): def call_and_then_continue(function): def wrapper(*args, **kwargs): result = function(*args, **kwargs) return continuation(result) return wrapper return call_and_then_continue def apply_to_result(consumer): def call_and_then_apply(function): def wrapper(*args, **kwargs): result = function(*args, **kwargs) consumer(result) return result return wrapper return call_and_then_apply
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/pyutils.py
pyutils.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import java.io as _jio # noinspection PyUnresolvedReferences import java.nio.file as _jnio_file from io import IOBase, SEEK_SET from typing import Union InputStream = _jio.InputStream Reader = _jio.Reader InputStreamReader = _jio.InputStreamReader BufferedReader = _jio.BufferedReader Files = _jnio_file.Files Paths = _jnio_file.Paths @jpype.JImplementationFor("java.io.InputStream") class _JvmInputStream: def __jclass_init__(cls): IOBase.register(cls) @jpype.JOverride def close(self): self._closed = True self.close_() @property def closed(self): if hasattr(self, '_closed'): return self._closed else: return False def fileno(self): raise OSError("This IOBase is backed by an instance of <java.io.InputStream>") def flush(self): pass def isatty(self): return False def readable(self): return True def seekable(self): return False def writable(self): return False def _buffer(self): if not hasattr(self, '_buffered'): self._buffered = BufferedReader(InputStreamReader(self)) def readline(self, size=-1): self._buffer() self._buffered.readLine() def readlines(self, hint=-1): self._buffer() stream = self._buffered.read.lines() if hint >= 0: stream = stream.limit(hint) return list(stream) def seek(self, offset: int, whence=SEEK_SET): raise OSError("This IOBase is backed by an instance of <java.io.InputStream>") def tell(self): raise OSError("This IOBase is backed by an instance of <java.io.InputStream>") def truncate(self, size=None): raise OSError("This IOBase is backed by an instance of <java.io.InputStream>") def writelines(self): raise OSError("This IOBase is backed by an instance of <java.io.InputStream>") def open_file(path: str) -> InputStream: return Files.newInputStream(Paths.get(path)) def ensure_input_steam(input: Union[str, InputStream]) -> InputStream: if isinstance(input, str): return open_file(input) elif isinstance(input, InputStream): return input else: raise TypeError("Invalid type: " + type(input)) logger.debug("Configure JVM-specific IO extensions")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/jvmioutils.py
jvmioutils.py
import logging # noinspection PyUnresolvedReferences import jpype import jpype.imports from .libs import CLASSPATH logging.basicConfig(level=logging.WARN) logger = logging.getLogger('tuprolog') jars = [str(j.resolve()) for j in CLASSPATH.glob('*.jar')] jpype.startJVM(classpath=jars) # noinspection PyUnresolvedReferences from it.unibo import tuprolog as _tuprolog Info = _tuprolog.Info JVM_VERSION = '.'.join(map(str, jpype.getJVMVersion())) logger.info("Started JVM v" + JVM_VERSION + " with classpath: " + str(jars)) logger.info("Using 2P-Kt v" + str(Info.VERSION))
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/__init__.py
__init__.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyProtectedMember from _jpype import _JObject as JObjectClass # noinspection PyUnresolvedReferences import java.util as _jutils # noinspection PyUnresolvedReferences import java.lang as _jlang # noinspection PyUnresolvedReferences import kotlin as _kotlin # noinspection PyUnresolvedReferences import kotlin.sequences as _ksequences # noinspection PyUnresolvedReferences import it.unibo.tuprolog.utils as _tuprolog_utils from typing import Iterable as PyIterable from typing import Iterator as PyIterator from typing import Mapping, MutableMapping, Callable, Any from .jvmioutils import * Arrays = _jutils.Arrays ArrayList = _jutils.ArrayList Iterator = _jutils.Iterator Map = _jutils.Map NoSuchElementException = _jutils.NoSuchElementException Iterable = _jlang.Iterable JavaSystem = _jlang.System Object = _jlang.Object Pair = _kotlin.Pair Triple = _kotlin.Triple Sequence = _ksequences.Sequence SequencesKt = _ksequences.SequencesKt PyUtils = _tuprolog_utils.PyUtils def protect_iterable(iterable: Iterable) -> Iterable: return PyUtils.iterable(iterable) @jpype.JImplements("java.util.Iterator", deferred=True) class _IteratorAdapter(object): def __init__(self, iterator): assert isinstance(iterator, PyIterator) self._iterator = iterator self._queue = None @jpype.JOverride def hasNext(self): if self._queue is None: try: self._queue = [next(self._iterator)] return True except StopIteration: return False elif len(self._queue) > 0: return True else: try: self._queue.append(next(self._iterator)) return True except StopIteration: return False @jpype.JOverride def next(self): if self.hasNext(): return self._queue.pop(0) else: raise NoSuchElementException() @jpype.JImplements("java.lang.Iterable", deferred=True) class _IterableAdapter(object): def __init__(self, iterable): assert isinstance(iterable, PyIterable) self._iterable = iterable @jpype.JOverride def iterator(self): return _IteratorAdapter(iter(self._iterable)) def kpair(items: PyIterable) -> Pair: if isinstance(items, Pair): return items i = iter(items) first = next(i) second = next(i) return Pair(first, second) @jpype.JConversion("kotlin.Pair", instanceof=PyIterable, excludes=str) def _kt_pair_covert(jcls, obj): return kpair(obj) def ktriple(items: PyIterable) -> Triple: if isinstance(items, Triple): return items i = iter(items) first = next(i) second = next(i) third = next(i) return Triple(first, second, third) @jpype.JConversion("kotlin.Triple", instanceof=PyIterable, excludes=str) def _kt_triple_covert(jcls, obj): return ktriple(obj) def jlist(iterable: PyIterable) -> Iterable: assert isinstance(iterable, PyIterable) if isinstance(iterable, list): return Arrays.asList(iterable) lst = ArrayList() for item in iterable: lst.add(item) return lst def jiterable(iterable: PyIterable) -> Iterable: assert isinstance(iterable, PyIterable) return _IterableAdapter(iterable) @jpype.JConversion("java.lang.Iterable", instanceof=PyIterable, excludes=str) def _java_iterable_convert(jcls, obj): return jiterable(obj) def jarray(type, rank: int = 1): return jpype.JArray(type, rank) def jiterator(iterator: PyIterator) -> Iterator: assert isinstance(iterator, PyIterator) return _IteratorAdapter(iterator) def jmap(dictionary: Mapping) -> Map: assert isinstance(dictionary, Mapping) return Map@dictionary def _java_obj_repr(java_object: Object) -> str: return str(java_object.toString()) # replaces the default __repr__ implementation for java objects, making them use _java_obj_repr JObjectClass.__repr__ = _java_obj_repr @jpype.JImplementationFor("kotlin.sequences.Sequence") class _KtSequence: def __jclass_init__(self): PyIterable.register(self) def __iter__(self): return protect_iterable(self).iterator() def ksequence(iterable: PyIterable) -> Sequence: return SequencesKt.asSequence(jiterable(iterable)) @jpype.JConversion("kotlin.sequences.Sequence", instanceof=PyIterable, excludes=str) def _kt_sequence_convert(jcls, obj): return ksequence(obj) @jpype.JImplementationFor("java.util.stream.Stream") class _JvmStream: def __jclass_init__(self): PyIterable.register(self) def __iter__(self): return self.iterator() @jpype.JImplementationFor("java.lang.Comparable") class _JvmComparable: def __jclass_init__(self): pass def __lt__(self, other): return self.compareTo(other) < 0 def __gt__(self, other): return self.compareTo(other) > 0 def __le__(self, other): return self.compareTo(other) <= 0 def __ge__(self, other): return self.compareTo(other) >= 0 @jpype.JImplementationFor("java.lang.Throwable") class _JvmThrowable: def __jclass_init__(self): pass @property def message(self): return self.getMessage() @property def localized_message(self): return self.getLocalizedMessage() @property def cause(self): return self.getCause() class _KtFunction(Callable): def __init__(self, arity: int, function: Callable): self._function = function self._arity = arity def invoke(self, *args): assert len(args) == self._arity return self._function(*args) def __call__(self, *args): return self.invoke(*args) _kt_function_classes: MutableMapping[int, Any] = dict() def kfunction(arity: int): if arity not in _kt_function_classes: @jpype.JImplements("kotlin.jvm.functions.Function" + str(arity), deferred=True) class _KtFunctionN(_KtFunction): def __init__(self, f): super().__init__(arity, f) @jpype.JOverride def invoke(self, *args): return super().invoke(*args) _kt_function_classes[arity] = _KtFunctionN return _kt_function_classes[arity] logger.debug("Configure JVM-specific extensions")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/jvmutils.py
jvmutils.py
from tuprolog import logger import jpype @jpype.JImplementationFor("it.unibo.tuprolog.unify.Unificator") class _KtUnificator: def __jclass_init__(cls): pass @property def context(self): return self.getContext() logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.unify.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/unify/_ktadapt.py
_ktadapt.py
from tuprolog import logger # noinspection PyUnresolvedReferences import jpype.imports # noinspection PyUnresolvedReferences import it.unibo.tuprolog.unify as _unify from tuprolog.core import Term, Substitution from ._ktadapt import * Unificator = _unify.Unificator def strict_unificator(context: Substitution = None) -> Unificator: if context is None: return Unificator.strict() else: return Unificator.strict(context) def naive_unificator(context: Substitution = None) -> Unificator: if context is None: return Unificator.naive() else: return Unificator.naive(context) def cached_unificator(unificator: Unificator, cache_size: int = Unificator.DEFAULT_CACHE_CAPACITY) -> Unificator: return Unificator.cached(unificator, cache_size) def unificator(context: Substitution = None) -> Unificator: return cached_unificator(strict_unificator(context)) DEFAULT_UNIFICATOR = Unificator.getDefault() def mgu(x: Term, y: Term, occur_check: bool = True) -> Substitution: return DEFAULT_UNIFICATOR.mgu(x, y, occur_check) def unify(x: Term, y: Term, occur_check: bool = True) -> Term: return DEFAULT_UNIFICATOR.unify(x, y, occur_check) def match(x: Term, y: Term, occur_check: bool = True) -> bool: return DEFAULT_UNIFICATOR.match(x, y, occur_check) logger.debug("Loaded JVM classes from it.unibo.tuprolog.unify.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/unify/__init__.py
__init__.py
from tuprolog import logger import jpype @jpype.JImplementationFor("it.unibo.tuprolog.unify.exception.NoUnifyException") class _KtNoUnifyException: def __jclass_init__(cls): pass @property def term1(self): return self.getTerm1() @property def term2(self): return self.getTerm2() logger.debug("Configure Kotlin adapters for types in it.unibo.tuprolog.unify.exception.*")
2ppy
/2ppy-0.4.0-py3-none-any.whl/tuprolog/unify/exception/_ktadapt.py
_ktadapt.py