Skip to content

Commit e7654dd

Browse files
Only stretch image to resize if format is Stretch (#352)
* Only stretch image to resize if format is Stretch * fix(pre_commit): 🎨 auto format pre-commit hooks * Format * Remove unused resize var * reformat w latest version of ruff * Initialize should_resize var outside of if --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 594bff7 commit e7654dd

File tree

9 files changed

+26
-25
lines changed

9 files changed

+26
-25
lines changed

roboflow/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def check_key(api_key, model, notebook, num_retries=0):
4343
num_retries += 1
4444
return check_key(api_key, model, notebook, num_retries)
4545
else:
46-
raise RuntimeError("There was an error validating the api key with Roboflow" " server.")
46+
raise RuntimeError("There was an error validating the api key with Roboflow server.")
4747
else:
4848
r = response.json()
4949
return r
@@ -71,7 +71,7 @@ def login(workspace=None, force=False):
7171
# default configuration location
7272
conf_location = os.getenv("ROBOFLOW_CONFIG_DIR", default=default_path)
7373
if os.path.isfile(conf_location) and not force:
74-
write_line("You are already logged into Roboflow. To make a different login," "run roboflow.login(force=True).")
74+
write_line("You are already logged into Roboflow. To make a different login,run roboflow.login(force=True).")
7575
return None
7676
# we could eventually return the workspace object here
7777
# return Roboflow().workspace()

roboflow/adapters/rfapi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def save_annotation(
179179

180180

181181
def _save_annotation_url(api_key, project_url, name, image_id, job_name, is_prediction, overwrite=False):
182-
url = f"{API_URL}/dataset/{project_url}/annotate/{image_id}?api_key={api_key}" f"&name={name}"
182+
url = f"{API_URL}/dataset/{project_url}/annotate/{image_id}?api_key={api_key}&name={name}"
183183
if job_name:
184184
url += f"&jobName={job_name}"
185185
if is_prediction:

roboflow/core/project.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def generate_version(self, settings):
230230
)
231231

232232
r = requests.post(
233-
f"{API_URL}/{self.__workspace}/{self.__project_name}/" f"generate?api_key={self.__api_key}",
233+
f"{API_URL}/{self.__workspace}/{self.__project_name}/generate?api_key={self.__api_key}",
234234
json=settings,
235235
)
236236

@@ -426,7 +426,7 @@ def upload(
426426

427427
if not is_image:
428428
raise RuntimeError(
429-
"The image you provided {} is not a supported file format. We" " currently support: {}.".format(
429+
"The image you provided {} is not a supported file format. We currently support: {}.".format(
430430
image_path, ", ".join(ACCEPTED_IMAGE_FORMATS)
431431
)
432432
)

roboflow/core/version.py

+7-9
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ def deploy(self, model_type: str, model_path: str, filename: str = "weights/best
495495
]
496496

497497
if not any(supported_model in model_type for supported_model in supported_models):
498-
raise (ValueError(f"Model type {model_type} not supported. Supported models are" f" {supported_models}"))
498+
raise (ValueError(f"Model type {model_type} not supported. Supported models are {supported_models}"))
499499

500500
if model_type.startswith(("paligemma", "paligemma2", "florence-2")):
501501
if any(model in model_type for model in ["paligemma", "paligemma2", "florence-2"]):
@@ -648,7 +648,7 @@ def deploy(self, model_type: str, model_path: str, filename: str = "weights/best
648648
)
649649
else:
650650
if file in ["model_artifacts.json", "state_dict.pt"]:
651-
raise (ValueError(f"File {file} not found. Please make sure to provide a" " valid model path."))
651+
raise (ValueError(f"File {file} not found. Please make sure to provide a valid model path."))
652652

653653
self.upload_zip(model_type, model_path)
654654

@@ -761,7 +761,7 @@ def deploy_yolonas(self, model_type: str, model_path: str, filename: str = "weig
761761
)
762762
else:
763763
if file in ["model_artifacts.json", filename]:
764-
raise (ValueError(f"File {file} not found. Please make sure to provide a" " valid model path."))
764+
raise (ValueError(f"File {file} not found. Please make sure to provide a valid model path."))
765765

766766
self.upload_zip(model_type, model_path)
767767

@@ -791,8 +791,7 @@ def upload_zip(self, model_type: str, model_path: str, model_file_name: str = "r
791791

792792
if self.public:
793793
print(
794-
"View the status of your deployment at:"
795-
f" {APP_URL}/{self.workspace}/{self.project}/{self.version}"
794+
f"View the status of your deployment at: {APP_URL}/{self.workspace}/{self.project}/{self.version}"
796795
)
797796
print(
798797
"Share your model with the world at:"
@@ -801,8 +800,7 @@ def upload_zip(self, model_type: str, model_path: str, model_file_name: str = "r
801800
)
802801
else:
803802
print(
804-
"View the status of your deployment at:"
805-
f" {APP_URL}/{self.workspace}/{self.project}/{self.version}"
803+
f"View the status of your deployment at: {APP_URL}/{self.workspace}/{self.project}/{self.version}"
806804
)
807805

808806
except Exception as e:
@@ -824,7 +822,7 @@ def bar_progress(current, total, width=80):
824822
progress_message = (
825823
"Downloading Dataset Version Zip in "
826824
f"{location} to {format}: "
827-
f"{current/total*100:.0f}% [{current} / {total}] bytes"
825+
f"{current / total * 100:.0f}% [{current} / {total}] bytes"
828826
)
829827
sys.stdout.write("\r" + progress_message)
830828
sys.stdout.flush()
@@ -923,7 +921,7 @@ def __get_format_identifier(self, format):
923921

924922
if not format:
925923
raise RuntimeError(
926-
"You must pass a format argument to version.download() or define a" " model in your Roboflow object"
924+
"You must pass a format argument to version.download() or define a model in your Roboflow object"
927925
)
928926

929927
friendly_formats = {"yolov5": "yolov5pytorch", "yolov7": "yolov7pytorch"}

roboflow/core/workspace.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def two_stage_ocr(
269269
# capture OCR results from cropped image
270270
results.append(ocr_infer(croppedImg)["results"])
271271
else:
272-
print("please use an object detection model--can only perform two stage with" " bounding box results")
272+
print("please use an object detection model--can only perform two stage with bounding box results")
273273

274274
return results
275275

roboflow/deployment.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def get_deployment(args):
197197
print(json.dumps(msg, indent=2))
198198
break
199199

200-
print(f'{datetime.now().strftime("%H:%M:%S")} Waiting for deployment {args.deployment_name} to be ready...\n')
200+
print(f"{datetime.now().strftime('%H:%M:%S')} Waiting for deployment {args.deployment_name} to be ready...\n")
201201
time.sleep(30)
202202

203203

@@ -278,7 +278,7 @@ def get_deployment_log(args):
278278
continue
279279
log_ids.add(log["insert_id"])
280280
last_log_timestamp = log_timestamp
281-
print(f'[{log_timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")}] {log["payload"]}')
281+
print(f"[{log_timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')}] {log['payload']}")
282282

283283
if not args.follow:
284284
break

roboflow/models/object_detection.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -172,21 +172,25 @@ def predict( # type: ignore[override]
172172
else:
173173
self.__exception_check(image_path_check=image_path)
174174

175-
resize = False
176175
original_dimensions = None
176+
should_resize = False
177177
# If image is local image
178178
if not hosted:
179179
import cv2
180180
import numpy as np
181181

182+
should_resize = (
183+
"resize" in self.preprocessing.keys() and "Stretch" in self.preprocessing["resize"]["format"]
184+
)
185+
182186
if isinstance(image_path, str):
183187
image = Image.open(image_path).convert("RGB")
184188
dimensions = image.size
185189
original_dimensions = copy.deepcopy(dimensions)
186190

187191
# Here we resize the image to the preprocessing settings
188192
# before sending it over the wire
189-
if "resize" in self.preprocessing.keys():
193+
if should_resize:
190194
if dimensions[0] > int(self.preprocessing["resize"]["width"]) or dimensions[1] > int(
191195
self.preprocessing["resize"]["height"]
192196
):
@@ -197,7 +201,6 @@ def predict( # type: ignore[override]
197201
)
198202
)
199203
dimensions = image.size
200-
resize = True
201204

202205
# Create buffer
203206
buffered = io.BytesIO()
@@ -245,7 +248,7 @@ def predict( # type: ignore[override]
245248
if self.format == "json":
246249
resp_json = resp.json()
247250

248-
if resize and original_dimensions is not None:
251+
if should_resize and original_dimensions is not None:
249252
new_preds = []
250253
for p in resp_json["predictions"]:
251254
p["x"] = int(p["x"] * (int(original_dimensions[0]) / int(self.preprocessing["resize"]["width"])))

roboflow/roboflowpy.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ def _add_upload_parser(subparsers):
249249
upload_parser.add_argument(
250250
"-w",
251251
dest="workspace",
252-
help="specify a workspace url or id " "(will use default workspace if not specified)",
252+
help="specify a workspace url or id (will use default workspace if not specified)",
253253
)
254254
upload_parser.add_argument(
255255
"-p",
@@ -307,7 +307,7 @@ def _add_import_parser(subparsers):
307307
import_parser.add_argument(
308308
"-w",
309309
dest="workspace",
310-
help="specify a workspace url or id " "(will use default workspace if not specified)",
310+
help="specify a workspace url or id (will use default workspace if not specified)",
311311
)
312312
import_parser.add_argument(
313313
"-p",

roboflow/util/versions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def get_wrong_dependencies_versions(
3434
module = import_module(dependency)
3535
module_version = module.__version__
3636
if order not in order_funcs:
37-
raise ValueError(f"order={order} not supported, please use" f" `{', '.join(order_funcs.keys())}`")
37+
raise ValueError(f"order={order} not supported, please use `{', '.join(order_funcs.keys())}`")
3838

3939
is_okay = order_funcs[order](Version(module_version), Version(version))
4040
if not is_okay:
@@ -53,7 +53,7 @@ def print_warn_for_wrong_dependencies_versions(
5353
f" {dependency}{order}{version}`"
5454
)
5555
if ask_to_continue:
56-
answer = input(f"Would you like to continue with the wrong version of {dependency}?" " y/n: ")
56+
answer = input(f"Would you like to continue with the wrong version of {dependency}? y/n: ")
5757
if answer.lower() != "y":
5858
sys.exit(1)
5959

0 commit comments

Comments
 (0)