Best Python code snippet using tempest_python
utils.py
Source:utils.py  
...51    global cleanup_counter52    if cleanup_counter < 50:53        cleanup_counter += 154    else:55        _cleanup_images(os.path.dirname(item.path))56        cleanup_counter = 057    rimg_dir = os.path.join(os.path.dirname(item.path), img_dir)58    rimg_path = os.path.join(rimg_dir, item.name)59    rimg_url = os.path.join(os.path.dirname(item.url), img_dir, item.name)60    item.resized_img_url = rimg_url61    item.resized_img_path = rimg_path62    if os.path.exists(rimg_path):63        return64    ext = os.path.splitext(item.name)[1]65    if ext.lower()[1:] not in ['jpg', 'jpeg',  'gif', 'png']:66        item.resized_img_url = item.url67        item.resized_img_path = item.path68        return69    if not os.path.exists(rimg_dir):70        try:71            os.mkdir(rimg_dir)72        except:73            item.resized_img_url = item.url74            item.resized_img_path = item.path75    try:76        with Image.open(item.path) as im:77            im.thumbnail([rwidth, rheight], Image.ANTIALIAS)78            im.save(rimg_path)79    except:80        item.resized_img_url = item.url81        item.resized_img_path = item.path82def _list_dir(path):83    items = []84    if not os.path.exists(path):85        return items86    for item in os.listdir(path):87        item_path = os.path.join(path, item)88        if os.path.isfile(item_path):89            items.append(item)90    return items91def _cleanup_images(path):92    images = _list_dir(path)93    thumbs = _list_dir(os.path.join(path, img_thumbs))94    display = _list_dir(os.path.join(path, img_display))95    for image in images:96        if image in thumbs:97            del thumbs[thumbs.index(image)]98        if image in display:99            del display[display.index(image)]100    for t in thumbs:101        tpath = os.path.join(path, img_thumbs, t)102        if os.path.exists(tpath):103            os.remove(tpath)104    for d in display:105        dpath = os.path.join(path, img_display, d)...image_serve.py
Source:image_serve.py  
...5from PIL import Image6import os7import pandas as pd8import numpy as np9def _cleanup_images():10    files = os.listdir('.')11    for file in files:12        if file.endswith('.png'):13            os.remove(file)14def model_fn(model_dir):15    """loads model from previously saved artifact"""16    model = ImagePredictor.load(model_dir)17    return model18def transform_fn(model, request_body, input_content_type, output_content_type="application/json"):19    if input_content_type == "application/x-npy":20        buf = BytesIO(request_body)21        data = np.load(buf, allow_pickle=True)22        image_paths = []23        for i, image in enumerate(data):24            im = Image.fromarray(image)25            im_name = f'{i}.png'26            im.save(im_name)27            image_paths.append(im_name)28    elif input_content_type == "application/x-image":29        buf = BytesIO(request_body)30        im = Image.open(buf)31        image_paths = []32        im_name = 'test.png'33        im.save(im_name)34        image_paths.append(im_name)35    else:36        raise ValueError(37            f'{input_content_type} input content type not supported.'38        )39    if model._problem_type != REGRESSION:40        pred_proba = model.predict_proba(image_paths, as_pandas=True)41        pred = get_pred_from_proba_df(pred_proba, problem_type=model._problem_type)42        pred_proba.columns = [str(c) + '_proba' for c in pred_proba.columns]43        pred.name = str(pred.name) + '_pred' if pred.name is not None else 'pred'44        prediction = pd.concat([pred, pred_proba], axis=1)45    else:46        prediction = model.predict(image_paths, as_pandas=True)47    if isinstance(prediction, pd.Series):48        prediction = prediction.to_frame()49    if output_content_type == "application/json":50        output = prediction.to_json()51    elif output_content_type == "application/x-parquet":52        prediction.columns = prediction.columns.astype(str)53        output = prediction.to_parquet()54    elif output_content_type == "text/csv":55        output = prediction.to_csv(index=None)56    else:57        raise ValueError(f"{output_content_type} content type not supported")58    _cleanup_images()...cleanup_media_files.py
Source:cleanup_media_files.py  
...5class CleanupMediaFilesService(ICleanupMediaFilesService):6    """Cleanup media files service."""7    def cleanup_media_files(self, instance: models.Model) -> None:8        """Cleanup media files."""9        self._cleanup_images(instance)10    def _cleanup_images(self, instance: models.Model) -> None:11        for image_field in self._get_media_fields(instance, Image):12            media_instance = getattr(instance, image_field.name)13            if media_instance:14                self._delete_image(media_instance)15    def _delete_file(self, file_instance: models.Model) -> None:16        self._delete_media_from_storage(file_instance.storage_file)17        file_instance.delete()18    def _delete_image(self, image_instance: models.Model) -> None:19        self._delete_media_from_storage(image_instance.storage_image)20        image_instance.delete()21    def _delete_media_from_storage(22        self,23        media_field: models.FileField,24    ) -> None:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
