Saravanan666/pypi-org huggingface dataset:
Package: object_cacher
Simple cacher for your objects. Store copy of objects in memory (or pickle in file) and returns copy of that objects. Function arguments it is a cache key.>>> from object_cacher import ObjectCacher
>>> @ObjectCacher(timeout=5)
... def test(*args):
...     print ('Real call')
...     return args
...
>>> test(1,2,3)
Real call
(1, 2, 3)>>> test(1,2,3)
(1, 2, 3)>>> test(1,2,3,4)
Real call
(1, 2, 3, 4)>>> test(1,2,3,4)
... (1, 2, 3, 4)Makes cache for results of hard functions or methods.
For example you have remote RESTful api with a lot of dictionaries. You may cache it:>>> from urllib import urlopen
>>> from object_cacher import ObjectCacher
>>> @ObjectCacher(timeout=60)
... def get_api():
...     print "This real call"
...     return urlopen('https://api.github.com/').read()
...
>>> get_api()
This real call
'{"current_user_url":"https://api.github.com/user", ...'
>>> get_api()
'{"current_user_url":"https://api.github.com/user", ...'As result you made http request only once.For methods you may use it like this:>>> from urllib import urlopen
>>> from object_cacher import ObjectCacher
>>> class API(object):
...     @ObjectCacher(timeout=60, ignore_self=True)
...     def get_methods(self):
...         print "Real call"
...         return urlopen('https://api.github.com/').read()
...
>>> a = API()
>>> a.get_methods()
Real call
'{"current_user_url":"https://api.github.com/user", ...'
>>> b = API()
>>> b.get_methods()
'{"current_user_url":"https://api.github.com/user", ...'If ignore_self parameter is set, cache will be shared by all instances. Otherwise cache for instances will be split.Also you may use persistent cache.
The “ObjectPersistentCacher” class-decorator makes file-based pickle-serialized cache storage.
When you want to keep cache after rerun you must determine cache id:>>> from urllib import urlopen
>>> from object_cacher import ObjectCacher
>>> class API(object):
...     @ObjectPersistentCacher(timeout=60, ignore_self=True, oid='com.github.api.listofmethods')
...     def get_methods(self):
...         print "Real call"
...         return urlopen('https://api.github.com/').read()
...
>>> a = API()
>>> a.get_methods()
Real call
'{"current_user_url":"https://api.github.com/user", ...'
>>> b = API()
>>> b.get_methods()
'{"current_user_url":"https://api.github.com/user", ...'That is keep cache after rerun.You may change cache dir for ObjectPersistentCacher via changing ‘CACHE_DIR’ class-property.>>> ObjectPersistentCacher.CACHE_DIR = '/var/tmp/my_cache'InstallationYou may install from pypipip install object_cacheror manualpython setup.py install
Package: object-clerk
A wrapper for the following boto3 s3 client operations with connection retry and checksum verification:get_objecthead_objectupload_fileobjcopy_objectdelete_objectlist_objects_v2FeaturesRetry connection failuresConfirm checksum of uploaded and retrieved objectsMove objectConstrained interface to support simple CRUD operations for objects in existing bucketsConfigurationThe following environment variables configure the object clerk.VariableDescriptionTypeDefaultMULTIPART_THRESHOLDThreshold in bytes at which uploads are broken into multiple parts for upload.  Impacts the checksum stored in the eTagSTR524288000S3_CLIENT_CONFIGBoto Core Client Configurationhttps://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.htmlDefaults reflect capturing the retry of failed operations at a higher level.JSON`json {"connect_timeout": 60, "read_timeout": 60, "retries": {"max_attempts": 0}} `S3_UPLOAD_CONFIGTransfer Configuration applied to uploadshttps://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/s3.html#boto3.s3.transfer.TransferConfigmultipart_threshold and multipart_chunksize are set by the MULTIPART_THRESHOLD environment variable.  Values for these keys in
the S3_UPLOAD_CONFIG will be discarded.JSON`json {} `S3_DOWNLOAD_CONFIGTransfer Configuration applied to downloadshttps://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/s3.html#boto3.s3.transfer.TransferConfigJSON`json {} `Installationpipinstallobject-clerkExamplesInitializeclerk=ObjectClerk(host=127.0.0.1,port=8080,access_key=12342,secret_key=12342,retry_delay=1,retry_backoff=1,retry_jitter=(1,3),retry_max_delay=5,retry_tries=3,use_ssl=False)'Get Object# with checksum verifiedbytes_response=clerk.get_object("bucket","object_key")# without checksum verifiedbytes_response=clerk.get_object("bucket","object_key",verify_checksum=False)Delete Objectclerk.delete_object("bucket","object_key")Get Object Infodict_response=clerk.get_object_info("bucket","object_key")Copy Object# with checksum verifiedclerk.copy_object("source_bucket","source_object_key","destination_bucket","destination_object_key",)# without checksum verifiedclerk.copy_object("source_bucket","source_object_key","destination_bucket","destination_object_key",verify_checksum=False)Upload Object# with checksum verifiedwithopen("file",mode='rb')asf:clerk.upload_object(f,"bucket","object_key")# without checksum verifiedwithopen("file",mode='rb')asf:clerk.upload_object(f,"bucket","object_key",verify_checksum=False)Move Object# with checksum verifiedclerk.move_object("source_bucket","source_object_key","destination_bucket","destination_object_key",)# without checksum verifiedclerk.move_object("source_bucket","source_object_key","destination_bucket","destination_object_key",verify_checksum=False)List Objectclerk.list_objects("bucket_name",1000)Testgitclonegit@bitbucket.org:swiant/object_store_wrapper.gitpipinstall-e.exportHOST=<host>exportPORT=<port>exportACCESS_KEY=<access_key>exportSECRET_KEY=<secret_key>pytest-vobject_clerk
Package: object-colors
Object-oriented library for stylizing terminal outputInstallation$pipinstallobject-colorsUsageImport theColorobject fromobject_colors>>>fromobject_colorsimportColorArgs can be provided as strings or as indices corresponding to their index in an ANSI escape sequence>>>Color(effect="bold",fore="red",back="green")Color(effect=1,fore=1,back=2,objects())The following would yield the same result>>>Color(effect=1,fore=1,back=2)Color(effect=1,fore=1,back=2,objects())The above options are part of the below mapping>>>fori,cinenumerate(Color.colors):...print(i,c)0black1red2green3yellow4blue5magenta6cyan7white>>>fori,einenumerate(Color.effects):...print(i,e)0none1bold2dim3italic4underline5blink6blinking7negative8empty9strikethroughTo configure the current object eithereffect,fore, orbackcan be providedThey must be anint,str, orNonetype>>>c=Color()>>>c.set(effect="bold",fore="red",back="red")>>>cColor(effect=1,fore=1,back=1,objects())Create new objects with by providing adictobject with any keyword argumentUsesetto set multiple parameters>>>c=Color()>>>c.set(bold_green=dict(effect="bold",fore="green"))>>>cColor(effect=None,fore=None,back=None,objects(bold_green))Returnstrortupleusingget>>>c=Color()>>>c.set(red=dict(fore="red"))>>>c.set(yellow=dict(fore="yellow"))>>>f"{c.red.get('*')}{c.yellow.get('Warning')}"'\x1b[31m*\x1b[0;0m\x1b[33mWarning\x1b[0;0m'>>>c=Color()>>>c.set(red=dict(fore="red"))>>>xyz=c.red.get("x","y","z")>>>xyz('\x1b[31mx\x1b[0;0m','\x1b[31my\x1b[0;0m','\x1b[31mz\x1b[0;0m')>>>x,y,z=xyz>>>f"{x}{y}{z}"'\x1b[31mx\x1b[0;0m\x1b[31my\x1b[0;0m\x1b[31mz\x1b[0;0m'Print the result usingprint>>>c=Color(effect="bold",fore="cyan")>>># doctest strips ansi codes from print>>>c.print("bold cyan")# '\x1b[1;36mbold cyan\x1b[0;0m'boldcyanLoad alleffect,fore, orbackelements usingpopulate()>>>c=Color()>>>c.populate("fore")>>>cColor(effect=None,fore=None,back=None,objects(black,red,green,yellow,blue,magenta,cyan,white))>>>c=Color()>>>c.set(red=dict(fore="red"))>>>c.red.populate("effect")>>>c.redColor(effect=None,fore=1,back=None,objects(none,bold,dim,italic,underline,blink,blinking,negative,empty,strikethrough))>>># doctest strips ansi codes from print>>>c.red.strikethrough.print("strikethrough red")# '\x1b[9;31mstrikethrough red\x1b[0;0m'strikethroughred
Package: object-condensation
Object Condensation Loss Functions and UtilitiesThe Object Condensation loss -developed by Jan Kieseler- is now being
used by several groups in high energy physics for both track reconstruction and
shower reconstruction in calorimeters.Several implementations of this idea already exist, but often they are
maintained by very few people. This repository aims to provide an easy to use
implementation for both the TensorFlow and PyTorch backend.Existing Implementations:cms-pepr[TensorFlow]mlpf[PyTorch]gnn-tracking[PyTorch]Installationpython3-mpipinstall-e'object_condensation[pytorch]'# orpython3-mpipinstall-e'object_condensation[tensorflow]'Development setupFor the development setup, clone this repository and also add thedevandtestingextra options, e.g.,python3-mpipinstall-e'.[pytorch,dev,testing]'Please also install pre-commit:python3-mpipinstallpre-commit
pre-commitinstall# in top-level directory of repositoryConventionsImplementations[!NOTE]
For a comparison of the performance of the different implementations,see the docs.Defaultcondensation_lossis a straightforward implementation that is easy to read and
to verify. It is used as baseline.pytorch APItensorflow APITigercondensation_loss_tigersaves memory by "masking instead of multiplying".
Consider the repulsive loss: It is an aggregation of potentials between
condensation points (CPs) and individual nodes. If these potentials are taken to
be hinge lossesrelu(1-dist), then they vanish for most CP-node pairs
(assuming a sufficiently well-trained model).Compare now the following two implementation strategies (wheredistis the
CP-node distance matrix):# Simplified by assuming that all points belong to repulsive potential# Strategy 1v_rep=sum(relu(1-dist))# Strategy 2 (tiger)rep_mask=dist<1v_rep=sum((1-dist)[rep_mask])In strategy 1, pytorch will keep all elements ofdistin memory for
backpropagation (even though most of therelu-differentials will be 0). In
strategy 2 (because the mask is detached from the computational graph), the
number of elements to backpropagate with will be greatly reduced.However, there is still one problem: What if our latent space collapses at some
point (or at the beginning of the training)? This would result in batches with a
greatly increased memory consumption, possibly crashing the run. To counter
this, an additional parametermax_n_repis introduced. If the number of
repulsive pairs (rep_mask.sum()in the example above) exceedsmax_n_rep,
thenrep_maskwill samplemax_n_repelements and upweight them byn_rep/max_n_rep. To check whether this approximation is being used,condensation_loss_tigerwill returnn_repin addition to the losses.pytorch API
Package: objectdaddy
Object DaddyA simple, python-based object recognizer, basically an implementation of yolo-v3-tiny. This package is used for personal projects; I don't maintain it, so use at your own risk, and feel free to fork.UsageBasic usage is as follows. This project is built to work with rtsparty (also on pypi).You can get and recognize one frame using the following:fromrtspartyimportStreamfromobjectdaddyimportDaddystream=Stream()daddy=Daddy()frame=stream.get_frame()results,frame=daddy.process_frame(frame)fordetectioninresults:detection.identify()For continuous recognition, use the following code.fromrtspartyimportStreamfromobjectdaddyimportDaddystream=Stream()daddy=Daddy()try:whileTrue:frame=stream.get_frame()ifstream.is_frame_empty(frame):continuedaddy.process_frame(frame)fordetectionindaddy.get_current_detections():ifnotdetection.has_been_processed_downstream:detection.identify()detection.has_been_processed_downstream=TrueexceptKeyboardInterrupt:passThe code makes the attempt to recognize objects across multiple frames, and keep a list of objects in memory accessed with the get_current_detections() function.NotesThis package supports only CPU-based inference.
Package: object-detection-fastai
ObjectDetectionSome experiments with object detection in PyTorch andFastAi.
This repo is created for educational reasons and to get a deeper understanding ofRetinaNetand object detection general. If you like it, please let me know, if you find any bugs or tips for improvements also.Installpip install object-detection-fastaiTest:Coco ColabImage annotationThis paper describes the EXACT-Server in-depth, EXACT enables you to annotate your data and train an object detection model with this repository. Please cite if you use this tool in your research:Marzahl et al.EXACT: A collaboration toolset for algorithm-aided annotation of almost everything@misc{marzahl2020exact,
    title={EXACT: A collaboration toolset for algorithm-aided annotation of almost everything},
    author={Christian Marzahl and Marc Aubreville and Christof A. Bertram and Jennifer Maier and Christian Bergler and Christine KrÃ¶ger and JÃ¶rn Voigt and Robert Klopfleisch and Andreas Maier},
    year={2020},
    eprint={2004.14595},
    archivePrefix={arXiv},
    primaryClass={cs.HC}
}Update old code# Old imports:fromhelper.object_detection_helperimport*fromloss.RetinaNetFocalLossimportRetinaNetFocalLossfrommodels.RetinaNetimportRetinaNetfromcallbacks.callbacksimportBBLossMetrics,BBMetrics,PascalVOCMetric# New importsfromobject_detection_fastai.helper.object_detection_helperimport*fromobject_detection_fastai.loss.RetinaNetFocalLossimportRetinaNetFocalLossfromobject_detection_fastai.models.RetinaNetimportRetinaNetfromobject_detection_fastai.callbacks.callbacksimportBBLossMetrics,BBMetrics,PascalVOCMetricThe basline for this notebook was created bySylvain Guggerfrom FastAiDevNotebook. Thank you very much, it was a great starting point and I'm a big fan off your work.Publications using this code:[x]Deep Learning-Based Quantification of Pulmonary Hemosiderophages in Cytology SlidesExamples:Medical imagesCoco subsetCoco ColabResults:Features:[x] Coco Metric at train time via callback[x] Flexibility# use the feature map sizes 32,18,8,4 with 32 channels and two conv layers for detection and classificationRetinaNet(encoder,n_classes=data.train_ds.c,n_anchors=18,sizes=[32,16,8,4],chs=32,final_bias=-4.,n_conv=2)'''(classifier): Sequential((0): Sequential((0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(1): ReLU())(1): Sequential((0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(1): ReLU())(2): Conv2d(32, 18, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)))# use the feature map sizes 32 with 8 channels and three conv layers for detection and classificationRetinaNet(encoder,n_classes=data.train_ds.c,n_anchors=3,sizes=[32],chs=8,final_bias=-4.,n_conv=3)[x] Debug anchor matches for training.On the left image we see objects that are represented by anchors.
On the right objects with no corresponding anchors for training.The size of the smallest anchors should be further decreased to match the small objects on the right image.
Package: object-detection-metrics
This project was forked fromrafaelpadilla/Object-Detection-Metrics.Development ofobject_detection_metricshappens on GitHub:https://github.com/yfpeng/object_detection_metricsThe latestobject_detection_metrics releasesare available overpypi.Getting startedInstallingobject_detection_metrics$pipinstallobject_detection_metricsReading COCO filefrompodmimportcoco_decoderwithopen('tests/sample/groundtruths_coco.json')asfp:gold_dataset=coco_decoder.load_true_object_detection_dataset(fp)PASCAL VOC Metricsfrompodmimportcoco_decoderfrompodm.metricsimportget_pascal_voc_metrics,MetricPerClass,get_bounding_boxeswithopen('tests/sample/groundtruths_coco.json')asfp:gold_dataset=coco_decoder.load_true_object_detection_dataset(fp)withopen('tests/sample/detections_coco.json')asfp:pred_dataset=coco_decoder.load_pred_object_detection_dataset(fp,gold_dataset)gt_BoundingBoxes=get_bounding_boxes(gold_dataset)pd_BoundingBoxes=get_bounding_boxes(pred_dataset)results=get_pascal_voc_metrics(gt_BoundingBoxes,pd_BoundingBoxes,.5)ap, precision, recall, tp, fp, etcforcls,metricinresults.items():label=metric.labelprint('ap',metric.ap)print('precision',metric.precision)print('interpolated_recall',metric.interpolated_recall)print('interpolated_precision',metric.interpolated_precision)print('tp',metric.tp)print('fp',metric.fp)print('num_groundtruth',metric.num_groundtruth)print('num_detection',metric.num_detection)mAPfrompodm.metricsimportMetricPerClassmAP=MetricPerClass.mAP(results)IoUfrompodm.boximportBox,intersection_over_unionbox1=Box.of_box(0.,0.,10.,10.)box2=Box.of_box(1.,1.,11.,11.)intersection_over_union(box1,box2)Official COCO Evalfrompycocotools.cocoimportCOCOfrompycocotools.cocoevalimportCOCOevalcoco_gld=COCO('tests/sample/groundtruths_coco.json')coco_rst=coco_gld.loadRes('tests/sample/detections_coco.json')cocoEval=COCOeval(coco_gld,coco_rst,iouType='bbox')cocoEval.evaluate()cocoEval.accumulate()cocoEval.summarize()Implemented metricsTutorialIntersection Over Union (IOU)TP and FPTrue Positive (TP): IOU ≥IOU threshold(default: 0.5)False Positive (FP): IOU <IOU threshold(default: 0.5)Precision and RecallAverage Precision11-point APall-point APOfficial COCO EvalLicenseCopyright BioNLP Lab at Weill Cornell Medicine, 2022.Distributed under the terms of theMITlicense, this is free and open source software.
Package: object-detection-tf
tf_object_detectionThis is a thin wrapper aroundTensorflow Object Detection APIfor easy installation and use. The originalinstallation procedurecontains multiple manual steps that make dependency management difficult. This repository creates a pip package that automate the installation so that you can install the API with a single pip install.Installationpip install tf-object-detection[tf]Or for tensorflow with GPU support,pip install tf-object-detection[tf-gpu]UsageAll the scripts from tensorflow object detection APIs work out-of-box.
You can find an example usages from the API'smodel_main.py.import object_detectionWhat's in heresetup.py: The python packaging script.PROTOCEnvironment variable should be set so thatsetup.pycan compile as
part of thesetup.pyexecution.# Download and setup all required dependencies required for tensorflow object# detection libarary to work correctly.$pythonsetup.pyinstalltf_object_detection: A git submodule pointing to the version of tensorflow object detection this thin wrapper is for.
Package: object-detector
In this Project I am Using YoloV4 for object detection. To detect object using YoloV4 and OpenCv you have to write many lines of code, but using this framework you can do this using few lines of code.Installationpip install object_detectorExtract Images from a videoImportExtractImagesclass fromobject_detectorLibrary>>>fromobject_detectorimportExtractImagesCreate a objectextofExtractImagesclass>>>ext=ExtractImages(path=0)path=0if you want to extract images from a video, write video path in place of 0.or you can create object specifing Output path>>>ext=ExtractImages(path=0,op=MyOutput)By default Output path isOutputStart Extracting Images.>>>ext.extract("A","B","C")A, B, C are the path where extracting images collected. Relative path of "A" isMyOutput/ANote:We are extracting Images in multiple path such that we can run our object detection task simultaneously.Object DetectionImportObjectDetectorclass fromobject_detectorLibrary>>>fromobject_detectorimportObjectDetectorCreate a objectobjof classObjectDetector>>>obj=ObjectDetector(weights="cars.weights",cfg="yolov4-custom.cfg",classes=['licence'])Object detection is done using YoLo.cars.weightsis the trained file generated by training image dataset by darknet, and we are usingyolov4-custom.cfg.>>>img=obj.detect_object(path)Write path of the image, from which you want to detect object.imgis numpy array of image. To the image from numpy array write>>>importcv2>>>cv2.imshow("Image_Name",img)or You can write>>>importmatplotlib.pyplotasplt>>>plt.imshow(img)If you want image without label write the code as>>>img=obj.detect_object(path,label=False)If you want toimgonly when obj is detected from image write the code as>>>img=detect_object(path,detected_only=True)To read text on the image add following code>>>text=extract_text()Show or Write objects from a video or cameraImport LiveDetect class and make a object of this class.l=LiveDetect(weights="cars.weights",cfg="yolov4-custom.cfg",classes=['licence'])Save images when object detect on video.l.write_from_video(path="Traffic.mp4")Show images when object detect on video.l.show_from_video(path="Traffic.mp4")Save images when object detect on the dir.l.write_from_dir(path="Traffic.mp4")Show images when object detect on the dir.l.show_from_dir(path="Traffic.mp4")
Package: objectdict
使用方法import json
from unittest import TestCase

from objectdict import ObjectDict


class TestObjectDict(TestCase):

    def test_value(self):
        class SimpleObjectDict(ObjectDict):
            int_field: int = 1
            str_field = 'a'
            dict_field = {}
            int2_f: int
            _protect = 'protect'

            @classmethod
            def classmethod(cls):
                pass

            @property
            def proty(cls):
                return 'property'

            def asd(self):
                return 'asd'

        self.assertEqual(ObjectDict(), {})

        self.assertEqual(SimpleObjectDict().int_field, 1)
        self.assertEqual(SimpleObjectDict().str_field, 'a')
        self.assertEqual(SimpleObjectDict().dict_field, {})
        self.assertEqual(SimpleObjectDict(), SimpleObjectDict().from_json(json.dumps(SimpleObjectDict())))
Package: objectfactory
py-object-factoryobjectfactoryis a python package to easily implement the factory design pattern for object creation, serialization, and polymorphismdesigned to support polymorphismintegrates seamlessly withmarshmallowand other serialization frameworksschema inherent in class definitionload any object with a generic interfaceserialize objects to JSONExampleSimpleshapesexample:importobjectfactory@objectfactory.registerclassSquare(objectfactory.Serializable):side=objectfactory.Field()defget_area(self):returnself.side*self.side@objectfactory.registerclassTriangle(objectfactory.Serializable):base=objectfactory.Field()height=objectfactory.Field()defget_area(self):return0.5*self.base*self.heightserialized_data=[{"_type":"Square","side":2.0},{"_type":"Triangle","base":1.75,"height":2.50},{"_type":"Square","side":1.5},]fordatainserialized_data:shape=objectfactory.create(data)print('class type:{}, shape area:{}'.format(type(shape),shape.get_area()))Output:class type: <class '__main__.Square'>, shape area: 4.0
class type: <class '__main__.Triangle'>, shape area: 2.1875
class type: <class '__main__.Square'>, shape area: 2.25More examplesSee more advanced exampleshereInstallUsepipfor installationpip install objectfactoryDocumentationRead the full documentation atobjectfactory.readthedocs.io