Skip to content

Commit

Permalink
added qupath flag in command, configures QuPath path from user if not…
Browse files Browse the repository at this point in the history
… found by default
  • Loading branch information
swaradgat19 committed Nov 29, 2023
1 parent 7854f95 commit e45bfc7
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 36 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ cython_debug/

#QuPath Project
QuPathProject/
*.backup

# Extras
.DS_Store
12 changes: 10 additions & 2 deletions wsinfer/cli/infer.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,13 @@ def get_stdout(args: list[str]) -> str:
help="JIT-compile the model and apply inference optimizations. This imposes a"
" startup cost but may improve performance overall.",
)
@click.option(
"--qupath",
is_flag=True,
default=False,
show_default=True,
help="Creates a QuPath project",
)
def run(
ctx: click.Context,
*,
Expand All @@ -264,6 +271,7 @@ def run(
batch_size: int,
num_workers: int = 0,
speedup: bool = False,
qupath: bool = False
) -> None:
"""Run model inference on a directory of whole slide images.
Expand Down Expand Up @@ -378,6 +386,6 @@ def run(
click.secho("Finished.", fg="green")

csvs = list((results_dir / "model-outputs-csv").glob("*.csv"))
print("")
write_geojsons(csvs, results_dir, num_workers)
make_qupath_project(wsi_dir, results_dir)
if qupath:
make_qupath_project(wsi_dir, results_dir)
71 changes: 37 additions & 34 deletions wsinfer/qupath.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,39 @@
from __future__ import annotations

import sys
import json
from pathlib import Path
import subprocess
import toml
import os
import toml
import paquo
from natsort import natsorted #add in dependencies?

# try:
# subprocess.run(f"python -m paquo config -l -o {Path.cwd()}", shell=True, check=True)
# print("Command executed successfully.")
# data = toml.load(".paquo.toml")
# data["qupath_dir"] = "/home/sggat/QuPath"
def configure_qupath():

# f = open(".paquo.toml",'w')
# toml.dump(data, f)
# f.close()
# except subprocess.CalledProcessError as e:
# print(f"Error running the command: {e}")
try:
from paquo.projects import QuPathProject
except Exception as e:
print(f"Couldn't find Qupath project with error: {e}")

def configure_qupath():
choice = input("""QuPath can be configured by setting the 'qupath_dir' field in '.paquo.toml'.
You can also manually enter the path to your local QuPath installation.
Do you want to enter manually? (Y[yes] or n[no]):
""")

choice = input("""QuPath can be configured by setting the 'qupath_dir'
field in '.paquo.toml'. You can also manually enter the path
to your local QuPath installation. Do you want to enter manually?
Y[yes] or n[no]:
""")

if choice is None or choice == 'n':
pass
elif choice == 'Y':
### Converting the string to Path doesnt work. Gives TypeError: str expected, not PosixPath
qupath_directory = input("Please enter the exact path where QuPath is installed: ")
if choice is None or choice != 'Y':
pass
elif choice == 'Y':
### Converting the string to Path doesnt work. Gives TypeError: str expected, not PosixPath
qupath_directory = input("Please enter the exact path where QuPath is installed: ")

try:
if Path(qupath_directory).exists():
os.environ["PAQUO_QUPATH_DIR"] = qupath_directory
os.environ["PAQUO_QUPATH_DIR"] = str(qupath_directory) # setting the env var
paquo.settings.reload() # Reloading
else:
raise FileNotFoundError
except FileNotFoundError:
print(f"QuPath Directory not found. Try again!")
print(f"QuPath Directory not found. Try again!")
sys.exit(1)

def add_image_and_geojson(
qupath_proj: QuPathProject, *, image_path: Path | str, geojson_path: Path | str
Expand All @@ -59,18 +54,26 @@ def add_image_and_geojson(

def make_qupath_project(wsi_dir, results_dir):

configure_qupath()
from paquo.projects import QuPathProject
configure_qupath() # Sets the environment variable "PAQUO_QUPATH_DIR"
try:
from paquo.projects import QuPathProject
except:
print("Unable to find Qupath! Run the program again")
sys.exit(1)

print("Found QuPath successfully!")
QUPATH_PROJECT_DIRECTORY = "QuPathProject"

csv_list = natsorted([str(file) for file in wsi_dir.iterdir() if file.is_file()])
json_list = natsorted([str(file) for file in Path(f"{results_dir}/model-outputs-geojson").iterdir() if file.is_file()])

slides_and_geojsons = [
("/home/sggat/wsinfer/wsinfer/SlideImages/CMU-1.svs", "/home/sggat/wsinfer/wsinfer/Results/model-outputs-geojson/CMU-1.json"),
("/home/sggat/wsinfer/wsinfer/SlideImages/CMU-2.svs", "/home/sggat/wsinfer/wsinfer/Results/model-outputs-geojson/CMU-2.json"),
("/home/sggat/wsinfer/wsinfer/SlideImages/CMU-3.svs", "/home/sggat/wsinfer/wsinfer/Results/model-outputs-geojson/CMU-3.json"),
]
(csv, json) for csv, json in zip(csv_list, json_list)
]
with QuPathProject(QUPATH_PROJECT_DIRECTORY, mode="w") as qp:
for image_path, geojson_path in slides_and_geojsons:
try:
add_image_and_geojson(qp, image_path=image_path, geojson_path=geojson_path)
except Exception as e:
print(f"Failed to add image/geojson with error:: {e}")
print(f"Failed to add image/geojson with error:: {e}")
print("Successfully created QuPath Project!")

0 comments on commit e45bfc7

Please sign in to comment.