Skip to content

Commit

Permalink
Fix MyPy issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Icosahunter committed May 23, 2024
1 parent a53b515 commit e5a12b9
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 37 deletions.
11 changes: 6 additions & 5 deletions tagstudio/src/core/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,17 +489,18 @@ def open_library(self, path: str | Path) -> int:
"""

return_code: int = 2
path: Path = self._fix_lib_path(path)

_path: Path = self._fix_lib_path(path)

if (path / TS_FOLDER_NAME / "ts_library.json").exists():
if (_path / TS_FOLDER_NAME / "ts_library.json").exists():
try:
with open(
path / TS_FOLDER_NAME / "ts_library.json",
_path / TS_FOLDER_NAME / "ts_library.json",
"r",
encoding="utf-8",
) as file:
json_dump: JsonLibary = ujson.load(file)
self.library_dir = Path(path)
self.library_dir = Path(_path)
self.verify_ts_folders()
major, minor, patch = json_dump["ts-version"].split(".")

Expand Down Expand Up @@ -1155,7 +1156,7 @@ def fix_missing_files(self):
# json.dump({}, outfile, indent=4)
# print(f'Re-saved to disk at {matched_json_filepath}')

def _match_missing_file(self, file: str) -> list[str]:
def _match_missing_file(self, file: str) -> list[Path]:
"""
Tries to find missing entry files within the library directory.
Works if files were just moved to different subfolders and don't have duplicate names.
Expand Down
12 changes: 6 additions & 6 deletions tagstudio/src/core/ts_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ def get_gdl_sidecar(self, filepath: str | Path, source: str = "") -> dict:
"""
json_dump = {}
info = {}
filepath: Path = Path(filepath)
filepath = filepath.parent / (filepath.stem + ".json")
_filepath: Path = Path(filepath)
_filepath = _filepath.parent / (_filepath.stem + ".json")

# NOTE: This fixes an unknown (recent?) bug in Gallery-DL where Instagram sidecar
# files may be downloaded with indices starting at 1 rather than 0, unlike the posts.
# This may only occur with sidecar files that are downloaded separate from posts.
if source == "instagram":
if not filepath.is_file():
newstem = filepath.stem[:-16] + "1" + filepath[-15:]
filepath = filepath.parent / (newstem + ".json")
if not _filepath.is_file():
newstem = _filepath.stem[:-16] + "1" + _filepath[-15:]

Check failure on line 40 in tagstudio/src/core/ts_core.py

View workflow job for this annotation

GitHub Actions / Run MyPy

[mypy] reported by reviewdog 🐶 Value of type "Path" is not indexable [index] Raw Output: /home/runner/work/TagStudio/TagStudio/tagstudio/src/core/ts_core.py:40:56: error: Value of type "Path" is not indexable [index]
_filepath = _filepath.parent / (newstem + ".json")

try:
with open(filepath, "r", encoding="utf8") as f:
with open(_filepath, "r", encoding="utf8") as f:
json_dump = json.load(f)

if json_dump:
Expand Down
18 changes: 10 additions & 8 deletions tagstudio/src/qt/helpers/file_opener.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import shutil
import sys
import traceback
from pathlib import Path

from PySide6.QtWidgets import QLabel
from PySide6.QtCore import Qt
Expand All @@ -19,21 +20,22 @@
logging.basicConfig(format="%(message)s", level=logging.INFO)


def open_file(path: str, file_manager: bool = False):
def open_file(path: str|Path, file_manager: bool = False):
"""Open a file in the default application or file explorer.
Args:
path (str): The path to the file to open.
file_manager (bool, optional): Whether to open the file in the file manager (e.g. Finder on macOS).
Defaults to False.
"""
logging.info(f"Opening file: {path}")
if not os.path.exists(path):
logging.error(f"File not found: {path}")
_path = str(path)
logging.info(f"Opening file: {_path}")
if not os.path.exists(_path):
logging.error(f"File not found: {_path}")
return
try:
if sys.platform == "win32":
normpath = os.path.normpath(path)
normpath = os.path.normpath(_path)
if file_manager:
command_name = "explorer"
command_args = '/select,"' + normpath + '"'
Expand All @@ -59,7 +61,7 @@ def open_file(path: str, file_manager: bool = False):
else:
if sys.platform == "darwin":
command_name = "open"
command_args = [path]
command_args = [_path]
if file_manager:
# will reveal in Finder
command_args.append("-R")
Expand All @@ -73,12 +75,12 @@ def open_file(path: str, file_manager: bool = False):
"--type=method_call",
"/org/freedesktop/FileManager1",
"org.freedesktop.FileManager1.ShowItems",
f"array:string:file://{path}",
f"array:string:file://{_path}",
"string:",
]
else:
command_name = "xdg-open"
command_args = [path]
command_args = [_path]
command = shutil.which(command_name)
if command is not None:
subprocess.Popen([command] + command_args, close_fds=True)
Expand Down
2 changes: 1 addition & 1 deletion tagstudio/src/qt/widgets/collage_icon.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def render(
except DecompressionBombError as e:
logging.info(f"[ERROR] One of the images was too big ({e})")
elif filepath.suffix in VIDEO_TYPES:
video = cv2.VideoCapture(filepath)
video = cv2.VideoCapture(str(filepath))
video.set(
cv2.CAP_PROP_POS_FRAMES,
(video.get(cv2.CAP_PROP_FRAME_COUNT) // 2),
Expand Down
34 changes: 17 additions & 17 deletions tagstudio/src/qt/widgets/thumb_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def render(
image: Image.Image = None
pixmap: QPixmap = None
final: Image.Image = None
filepath: Path = Path(filepath)
_filepath: Path = Path(filepath)
resampling_method = Image.Resampling.BILINEAR
if ThumbRenderer.font_pixel_ratio != pixel_ratio:
ThumbRenderer.font_pixel_ratio = pixel_ratio
Expand All @@ -118,12 +118,12 @@ def render(
pixmap.setDevicePixelRatio(pixel_ratio)
if update_on_ratio_change:
self.updated_ratio.emit(1)
elif filepath:
elif _filepath:
try:
# Images =======================================================
if filepath.suffix in IMAGE_TYPES:
if _filepath.suffix in IMAGE_TYPES:
try:
image = Image.open(filepath)
image = Image.open(_filepath)
if image.mode != "RGB" and image.mode != "RGBA":
image = image.convert(mode="RGBA")
if image.mode == "RGBA":
Expand All @@ -134,12 +134,12 @@ def render(
image = ImageOps.exif_transpose(image)
except DecompressionBombError as e:
logging.info(
f"[ThumbRenderer]{WARNING} Couldn't Render thumbnail for {filepath} (because of {e})"
f"[ThumbRenderer]{WARNING} Couldn't Render thumbnail for {_filepath} (because of {e})"
)

elif filepath.suffix in RAW_IMAGE_TYPES:
elif _filepath.suffix in RAW_IMAGE_TYPES:
try:
with rawpy.imread(filepath) as raw:
with rawpy.imread(_filepath) as raw:
rgb = raw.postprocess()
image = Image.frombytes(
"RGB",
Expand All @@ -149,16 +149,16 @@ def render(
)
except DecompressionBombError as e:
logging.info(
f"[ThumbRenderer]{WARNING} Couldn't Render thumbnail for {filepath} (because of {e})"
f"[ThumbRenderer]{WARNING} Couldn't Render thumbnail for {_filepath} (because of {e})"
)
except rawpy._rawpy.LibRawIOError:
logging.info(
f"[ThumbRenderer]{ERROR} Couldn't Render thumbnail for raw image {filepath}"
f"[ThumbRenderer]{ERROR} Couldn't Render thumbnail for raw image {_filepath}"
)

# Videos =======================================================
elif filepath.suffix in VIDEO_TYPES:
video = cv2.VideoCapture(filepath)
elif _filepath.suffix in VIDEO_TYPES:
video = cv2.VideoCapture(str(_filepath))
video.set(
cv2.CAP_PROP_POS_FRAMES,
(video.get(cv2.CAP_PROP_FRAME_COUNT) // 2),
Expand All @@ -174,8 +174,8 @@ def render(
image = Image.fromarray(frame)

# Plain Text ===================================================
elif filepath.suffix in PLAINTEXT_TYPES:
with open(filepath, "r", encoding="utf-8") as text_file:
elif _filepath.suffix in PLAINTEXT_TYPES:
with open(_filepath, "r", encoding="utf-8") as text_file:
text = text_file.read(256)
bg = Image.new("RGB", (256, 256), color="#1e1e1e")
draw = ImageDraw.Draw(bg)
Expand All @@ -189,7 +189,7 @@ def render(
# axes = figure.add_subplot(projection='3d')

# # Load the STL files and add the vectors to the plot
# your_mesh = mesh.Mesh.from_file(filepath)
# your_mesh = mesh.Mesh.from_file(_filepath)

# poly_collection = mplot3d.art3d.Poly3DCollection(your_mesh.vectors)
# poly_collection.set_color((0,0,1)) # play with color
Expand Down Expand Up @@ -265,7 +265,7 @@ def render(
) as e:
if e is not UnicodeDecodeError:
logging.info(
f"[ThumbRenderer]{ERROR}: Couldn't render thumbnail for {filepath} ({e})"
f"[ThumbRenderer]{ERROR}: Couldn't render thumbnail for {_filepath} ({e})"
)
if update_on_ratio_change:
self.updated_ratio.emit(1)
Expand All @@ -286,8 +286,8 @@ def render(
math.ceil(adj_size / pixel_ratio),
math.ceil(final.size[1] / pixel_ratio),
),
filepath.suffix,
_filepath.suffix,
)

else:
self.updated.emit(timestamp, QPixmap(), QSize(*base_size), filepath.suffix)
self.updated.emit(timestamp, QPixmap(), QSize(*base_size), _filepath.suffix)

0 comments on commit e5a12b9

Please sign in to comment.