Repository navigation
Expand file tree
/
Copy pathmanager.py
More file actions
1661 lines (1443 loc) · 74.1 KB
/
Copy pathmanager.py
File metadata and controls
1661 lines (1443 loc) · 74.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Build management functionality.
This module provides the BuildManager class which orchestrates the entire
build process: finding external dependencies, copying them temporarily,
running the build command, and cleaning up afterward.
"""
from __future__ import annotations
import shutil
import sys
from collections.abc import Callable
from pathlib import Path
try:
import tomllib
except ImportError:
try:
import tomli as tomllib
except ImportError:
tomllib = None
from .analyzer import ImportAnalyzer
from .finder import ExternalDependencyFinder
from .subfolder_build import SubfolderBuildConfig
from .types import ExternalDependency, ImportInfo
class BuildManager:
"""
Manages the build process with external dependency handling.
This is the main class for using the package. It coordinates finding
external dependencies, copying them into the source directory, running
the build, and cleaning up.
Attributes:
project_root: Root directory of the project
src_dir: Source directory containing the package code
copied_files: List of file paths that were copied (for cleanup)
copied_dirs: List of directory paths that were copied (for cleanup)
"""
def __init__(
self,
project_root: Path,
src_dir: Path | None = None,
exclude_patterns: list[str] | None = None,
) -> None:
"""
Initialize the build manager.
Args:
project_root: Root directory of the project
src_dir: Source directory (defaults to project_root/src, or current dir if it has Python files)
exclude_patterns: Additional patterns to exclude from copying (e.g., ['_SS', '__sandbox'])
Raises:
ValueError: If the source directory does not exist or is invalid
"""
from .utils import find_source_directory
self.project_root = project_root.resolve()
# If src_dir not provided, try to find it intelligently
if src_dir is None:
src_dir = find_source_directory(self.project_root)
if src_dir is None:
# Fallback to standard src/ directory
src_dir = self.project_root / "src"
self.src_dir = Path(src_dir).resolve()
# Store original src_dir before any changes (e.g., when temp directory is created)
self.original_src_dir = self.src_dir
# Validate source directory
if not self.src_dir.exists():
raise ValueError(f"Source directory not found: {self.src_dir}")
if not self.src_dir.is_dir():
raise ValueError(f"Source path is not a directory: {self.src_dir}")
self.copied_files: list[Path] = []
self.copied_dirs: list[Path] = []
self.exclude_patterns = exclude_patterns or []
self.finder = ExternalDependencyFinder(
self.project_root, self.src_dir, exclude_patterns=exclude_patterns
)
self.subfolder_config: SubfolderBuildConfig | None = None
# Cache for package name lookups (expensive operation)
self._packages_distributions_cache: dict[str, list[str]] | None = None
# Track files with modified imports and their original content
self._modified_import_files: dict[Path, str] = {}
# Check if it's a valid Python package directory
if not any(self.src_dir.glob("*.py")) and not (self.src_dir / "__init__.py").exists():
# Allow empty directories for now, but warn
pass
def find_src_package_dir(self) -> Path | None:
"""
Find the main package directory within src/.
Looks for directories with __init__.py files. If multiple are found,
tries to match one with the project name from pyproject.toml.
Returns:
Path to the main package directory, or src_dir if not found
"""
if not self.src_dir.exists():
return None
# Look for directories with __init__.py
package_dirs = [
d for d in self.src_dir.iterdir() if d.is_dir() and (d / "__init__.py").exists()
]
if len(package_dirs) == 1:
return package_dirs[0]
# If multiple, try to find the one matching the project name
project_name = self._get_project_name()
if project_name:
for pkg_dir in package_dirs:
if pkg_dir.name.replace("-", "_") == project_name.replace("-", "_"):
return pkg_dir
# Return the first one or src_dir itself
return package_dirs[0] if package_dirs else self.src_dir
def _is_subfolder_build(self) -> bool:
"""
Check if we're building a subfolder (not the main src/ directory).
Returns:
True if this is a subfolder build, False otherwise
"""
# Check if src_dir is not the main src/ directory
main_src = self.project_root / "src"
return (
self.src_dir != main_src
and self.src_dir != self.project_root
and self.src_dir.is_relative_to(self.project_root)
)
def _get_project_name(self) -> str | None:
"""
Get the project name from pyproject.toml.
Uses tomllib (Python 3.11+) or tomli as fallback to parse the file.
Falls back to simple string parsing if TOML parsing is unavailable.
Returns:
Project name from pyproject.toml, or None if not found
"""
pyproject_path = self.project_root / "pyproject.toml"
if not pyproject_path.exists():
return None
try:
if tomllib:
content = pyproject_path.read_bytes()
data = tomllib.loads(content)
return data.get("project", {}).get("name")
else:
# Fallback: simple parsing
content = pyproject_path.read_text(encoding="utf-8")
for line in content.split("\n"):
if line.strip().startswith("name ="):
return line.split("=", 1)[1].strip().strip('"').strip("'")
except Exception:
pass
return None
def prepare_build(
self,
version: str | None = None,
package_name: str | None = None,
dependency_group: str | None = None,
) -> list[ExternalDependency]:
"""
Prepare for build by finding and copying external dependencies.
This method automatically detects if you're building a subfolder (not the main src/
directory) and sets up pyproject.toml appropriately:
- If pyproject.toml exists in the subfolder, it will be used
- Otherwise, creates a temporary pyproject.toml with the correct package configuration
For subfolder builds without their own pyproject.toml, if no version is provided,
it defaults to "0.0.0" with a warning.
Process:
1. Detects if this is a subfolder build and sets up pyproject.toml if needed:
- If pyproject.toml exists in subfolder: uses that file
- If no pyproject.toml in subfolder: creates temporary one from parent
2. Finds all Python files in the source directory
3. Analyzes them for external dependencies
4. Copies external files/directories into the source directory
5. Reports any ambiguous imports
Args:
version: Version for subfolder builds. If building a subfolder and version is None,
defaults to "0.0.0" with a warning. Only used when creating temporary pyproject.toml
(ignored if subfolder has its own pyproject.toml). For regular builds, this parameter
is ignored.
package_name: Package name for subfolder builds. If None, derived from src_dir name
(e.g., "empty_drawing_detection" -> "empty-drawing-detection"). Only used when
creating temporary pyproject.toml (ignored if subfolder has its own pyproject.toml).
Ignored for regular builds.
dependency_group: Name of dependency group to copy from parent pyproject.toml.
Only used for subfolder builds when creating temporary pyproject.toml.
Returns:
List of ExternalDependency objects that were copied
Example:
```python
# Regular build (main src/ directory)
manager = BuildManager(project_root=Path("."), src_dir=Path("src"))
deps = manager.prepare_build() # No version needed
# Subfolder build (automatic detection)
manager = BuildManager(
project_root=Path("."),
src_dir=Path("src/integration/empty_drawing_detection")
)
# Version defaults to "0.0.0" if not provided
deps = manager.prepare_build(version="1.0.0", package_name="my-package")
```
"""
# Check if this is a subfolder build and set up config if needed
if self._is_subfolder_build():
# For subfolder builds, we need a version
# If not provided, use a default version
if not version:
version = "0.0.0"
print(
f"Warning: No version specified for subfolder build. Using default version '{version}'",
file=sys.stderr,
)
if not package_name:
# Derive package name from subfolder: {root_project_name}-{subfolder_name}
root_project_name = self._get_project_name()
subfolder_name = (
self.src_dir.name.replace("_", "-").replace(" ", "-").lower().strip("-")
)
if root_project_name:
# Normalize root project name (replace underscores/hyphens consistently)
root_name_normalized = root_project_name.replace("_", "-").lower()
package_name = f"{root_name_normalized}-{subfolder_name}"
else:
# Fallback to just subfolder name if root project name not found
package_name = subfolder_name
# Check if subfolder_config already exists with the same parameters
# This makes prepare_build() idempotent - safe to call multiple times
if (
self.subfolder_config
and self.subfolder_config.package_name == package_name
and self.subfolder_config.version == version
and self.subfolder_config.dependency_group == dependency_group
and self.subfolder_config._temp_package_dir
and self.subfolder_config._temp_package_dir.exists()
):
print(
f"Subfolder config already exists for '{package_name}' version '{version}', reusing it..."
)
# Still need to find external dependencies, so continue with that
# temp_pyproject should already exist from previous call
temp_pyproject = self.subfolder_config.temp_pyproject
else:
print(
f"Detected subfolder build. Setting up package '{package_name}' version '{version}'..."
)
self.subfolder_config = SubfolderBuildConfig(
project_root=self.project_root,
src_dir=self.src_dir,
package_name=package_name,
version=version,
dependency_group=dependency_group,
)
temp_pyproject = self.subfolder_config.create_temp_pyproject()
# If temp_pyproject is None, it means no parent pyproject.toml exists
# This is acceptable for tests or dependency-only operations
if temp_pyproject is None:
self.subfolder_config = None
# If we have a subfolder_config (either newly created or reused), use temp package dir
if self.subfolder_config:
# If temporary package directory was created, use it for all operations
# This ensures dependencies are copied to the correct location and
# imports are fixed in the files that will actually be packaged
if (
self.subfolder_config._temp_package_dir
and self.subfolder_config._temp_package_dir.exists()
):
# Update src_dir to point to temp package directory
self.src_dir = self.subfolder_config._temp_package_dir
# Recreate finder with updated src_dir so it calculates target paths correctly
# Pass original_src_dir for relative path checks to prevent copying entire src/ directory
self.finder = ExternalDependencyFinder(
self.project_root,
self.src_dir,
exclude_patterns=self.exclude_patterns,
original_src_dir=self.original_src_dir,
)
print(
f"Using temporary package directory for build: {self.src_dir}"
)
analyzer = ImportAnalyzer(self.project_root)
# Find all Python files in src/ (which may now be the temp package directory)
python_files = analyzer.find_all_python_files(self.src_dir)
# Find external dependencies using the configured finder
external_deps = self.finder.find_external_dependencies(python_files)
# Copy external dependencies
for dep in external_deps:
self._copy_dependency(dep)
# For subfolder builds, fix imports
if self._is_subfolder_build() and external_deps:
# Fix relative imports in copied dependency files (convert to absolute)
self._fix_relative_imports_in_copied_files(external_deps)
# Convert absolute imports of copied dependencies and local files to relative imports
self._convert_imports_to_relative(python_files, external_deps)
# For subfolder builds, extract third-party dependencies and add to pyproject.toml
if self._is_subfolder_build() and self.subfolder_config:
# Re-analyze all Python files (including copied dependencies) to find third-party imports
print("Analyzing Python files for third-party dependencies...")
all_python_files = analyzer.find_all_python_files(self.src_dir)
print(f"Found {len(all_python_files)} Python files to analyze")
third_party_deps = self._extract_third_party_dependencies(all_python_files, analyzer)
if third_party_deps:
print(
f"Found {len(third_party_deps)} third-party dependencies: {', '.join(third_party_deps)}"
)
self.subfolder_config.add_third_party_dependencies(third_party_deps)
else:
print("No third-party dependencies found in subfolder code")
# Report ambiguous imports
self._report_ambiguous_imports(python_files)
return external_deps
def _copy_dependency(self, dep: ExternalDependency) -> None:
"""
Copy an external dependency to the target location.
Handles both files and directories. Checks for idempotency to avoid
duplicate copies. Creates parent directories as needed.
Args:
dep: ExternalDependency object with source and target paths
"""
source = dep.source_path
target = dep.target_path
if not source.exists():
print(f"Warning: External dependency not found: {source}", file=sys.stderr)
return
# Create target directory if needed
target.parent.mkdir(parents=True, exist_ok=True)
# Check if already copied (idempotency)
if target.exists():
# Check if it's the same file
if source.is_file() and target.is_file():
try:
if source.samefile(target):
return # Already in place, skip
except OSError:
# Files are different, proceed with copy
pass
elif source.is_dir() and target.is_dir():
# For directories, check if they have the same structure
# Simple check: if target has __init__.py and source does too, assume copied
# Also check if target has any Python files
source_has_init = (source / "__init__.py").exists()
target_has_init = (target / "__init__.py").exists()
if source_has_init == target_has_init:
# Check if target has at least some files from source
source_files = {f.name for f in source.rglob("*.py")}
target_files = {f.name for f in target.rglob("*.py")}
if source_files and target_files and source_files.issubset(target_files):
# Assume already copied if structure matches
return
try:
if source.is_file():
shutil.copy2(source, target)
self.copied_files.append(target)
print(f"Copied external file: {source} -> {target}")
# If copying a Python file, ensure parent directory has __init__.py
# This helps type checkers resolve imports correctly
if source.suffix == ".py" and target.parent != self.src_dir:
init_file = target.parent / "__init__.py"
if not init_file.exists():
init_file.write_text("", encoding="utf-8")
self.copied_files.append(init_file)
elif source.is_dir():
if target.exists():
shutil.rmtree(target)
# Use custom copy function that excludes certain patterns
self._copytree_excluding(source, target)
self.copied_dirs.append(target)
print(f"Copied external directory: {source} -> {target}")
except Exception as e:
print(f"Error copying {source} to {target}: {e}", file=sys.stderr)
def _copytree_excluding(self, src: Path, dst: Path) -> None:
"""
Copy a directory tree, excluding certain patterns.
Excludes directories matching patterns like _SS, __SS, _sandbox, etc.
Ensures __init__.py files exist in directories containing Python files
so that type checkers can resolve imports correctly.
Args:
src: Source directory
dst: Destination directory
"""
default_patterns = [
"_SS",
"__SS",
"_sandbox",
"__sandbox",
"_skip",
"__skip",
"_test",
"__test__",
]
exclude_patterns = default_patterns + self.exclude_patterns
def should_exclude(path: Path) -> bool:
"""Check if a path should be excluded."""
# Check each component of the path
for part in path.parts:
# Check if any part matches an exclusion pattern
for pattern in exclude_patterns:
# Match if part equals pattern or starts with pattern
if part == pattern or part.startswith(pattern):
return True
return False
# Create destination directory
dst.mkdir(parents=True, exist_ok=True)
has_python_files = False
copied_python_files = []
# Copy files and subdirectories, excluding patterns
for item in src.iterdir():
if should_exclude(item):
continue
src_item = src / item.name
dst_item = dst / item.name
if src_item.is_file():
shutil.copy2(src_item, dst_item)
if src_item.suffix == ".py":
has_python_files = True
copied_python_files.append(dst_item)
elif src_item.is_dir():
self._copytree_excluding(src_item, dst_item)
# Check if the subdirectory has Python files
if any(dst_item.rglob("*.py")):
has_python_files = True
# Ensure __init__.py exists in directories containing Python files
# This is needed for type checkers to resolve imports correctly
# Also ensure all parent directories in the path have __init__.py
if has_python_files:
init_file = dst / "__init__.py"
if not init_file.exists():
# Create an empty __init__.py file
init_file.write_text("", encoding="utf-8")
self.copied_files.append(init_file)
# Ensure all parent directories up to src_dir also have __init__.py
# This helps type checkers resolve nested imports like:
# from empty_drawing_detection.models.Information_extraction._shared_ie.ie_enums import ...
current = dst
while current != self.src_dir and current.is_relative_to(self.src_dir):
parent_init = current.parent / "__init__.py"
if (
parent_init.parent != self.src_dir
and not parent_init.exists()
and any(current.parent.rglob("*.py"))
):
parent_init.write_text("", encoding="utf-8")
self.copied_files.append(parent_init)
current = current.parent
def _get_package_name_from_import(self, module_name: str) -> str | None:
"""
Get the actual PyPI package name from an import module name.
This handles cases where the import name differs from the package name
(e.g., 'import fitz' from 'pymupdf' package).
Args:
module_name: The module name from the import statement
Returns:
The actual package name, or None if not found
"""
root_module = module_name.split(".")[0]
try:
# Try Python 3.10+ first (has packages_distributions)
import importlib.metadata as importlib_metadata
# Use packages_distributions() if available (Python 3.10+)
# Cache the result since it's expensive to call
if hasattr(importlib_metadata, "packages_distributions"):
if self._packages_distributions_cache is None:
# Cache the packages_distributions() result
self._packages_distributions_cache = importlib_metadata.packages_distributions()
packages_map = self._packages_distributions_cache
# packages_map is a dict mapping module names to list of distribution names
if root_module in packages_map:
# Return the first distribution name (usually there's only one)
dist_names = packages_map[root_module]
if dist_names:
return dist_names[0]
# Fallback: search all distributions (this can be slow, so limit search)
# Only check top-level package matches to speed up search
dist_count = 0
max_distributions_to_check = 1000 # Limit to prevent excessive searching
for dist in importlib_metadata.distributions():
dist_count += 1
if dist_count > max_distributions_to_check:
# Too many distributions, give up to avoid hanging
break
try:
# Check distribution name first (fast check)
dist_name = dist.metadata.get("Name", "")
# If distribution name matches or contains the module name, check files
if dist_name.lower().replace(
"-", "_"
) == root_module.lower() or root_module.lower() in dist_name.lower().replace(
"-", "_"
):
# Check if this distribution provides the module by looking at its files
files = dist.files or []
# Limit file checking to first 100 files per distribution
file_count = 0
for file in files:
file_count += 1
if file_count > 100:
break
file_str = str(file)
# Check if file is the module itself or in a package directory
if (
file.suffix == ".py"
and (file.stem == root_module or file.stem == "__init__")
) or (
"/" in file_str
and (
file_str.startswith(f"{root_module}/")
or file_str.startswith(f"{root_module.replace('_', '-')}/")
)
):
return dist.metadata["Name"]
except Exception:
continue
except ImportError:
try:
# Fallback for older Python versions
import importlib_metadata
# Search all distributions
for dist in importlib_metadata.distributions():
try:
files = dist.files or []
for file in files:
file_str = str(file)
if (
file.suffix == ".py"
and (file.stem == root_module or file.stem == "__init__")
) or (
"/" in file_str
and (
file_str.startswith(f"{root_module}/")
or file_str.startswith(f"{root_module.replace('_', '-')}/")
)
):
return dist.metadata["Name"]
except Exception:
continue
except ImportError:
pass
except Exception:
pass
return None
def _extract_third_party_dependencies(
self, python_files: list[Path], analyzer: ImportAnalyzer
) -> list[str]:
"""
Extract third-party package dependencies from Python files.
Analyzes all Python files to find imports classified as "third_party"
and returns a list of unique package names. Handles cases where the
import name differs from the package name (e.g., 'fitz' -> 'pymupdf').
Args:
python_files: List of Python file paths to analyze
analyzer: ImportAnalyzer instance to use for classification
Returns:
List of unique third-party package names (e.g., ["pypdf", "requests", "pymupdf"])
"""
# Common third-party packages that are often misclassified as ambiguous
COMMON_THIRD_PARTY_PACKAGES = {
"torch",
"torchvision",
"numpy",
"pandas",
"matplotlib",
"scipy",
"sklearn",
"tensorflow",
"keras",
"pillow",
"PIL",
"cv2",
"opencv",
"requests",
"flask",
"django",
"pytest",
"pydantic",
"fastapi",
"sqlalchemy",
"pymongo",
"redis",
"celery",
"boto3",
"azure",
"google",
"openai",
"langchain",
"fiftyone",
"pycocotools",
"albumentations",
"loguru",
"tqdm",
"rich",
"pypdf",
"pymupdf",
"networkx",
"openpyxl",
"nltk",
"spacy",
"textdistance",
"IPython",
}
third_party_packages: set[str] = set()
# Cache package name lookups to avoid repeated expensive searches
package_name_cache: dict[str, str | None] = {}
total_files = len(python_files)
for idx, file_path in enumerate(python_files):
if idx > 0 and idx % 50 == 0:
print(f" Analyzing file {idx}/{total_files}...", end="\r", flush=True)
imports = analyzer.extract_imports(file_path)
for imp in imports:
analyzer.classify_import(imp, self.src_dir)
# Extract the root package name (first part of module name)
root_module = imp.module_name.split(".")[0]
# Skip if it's a standard library module
stdlib_modules = analyzer.get_stdlib_modules()
if root_module in stdlib_modules:
continue
# Skip if it's local or external (already copied, don't add as dependency)
if imp.classification in ("local", "external"):
continue
# If classified as third_party, try to get actual package name
if imp.classification == "third_party":
# Double-check: if it resolves to a file in src_dir, it's actually local
# (might have been copied and now resolves locally)
if imp.resolved_path and imp.resolved_path.is_relative_to(self.src_dir):
continue # Skip - it's a local file, not a third-party package
# Check cache first
if root_module not in package_name_cache:
package_name_cache[root_module] = self._get_package_name_from_import(
imp.module_name
)
actual_package = package_name_cache[root_module]
if actual_package:
third_party_packages.add(actual_package)
else:
# Fallback to using the import name
third_party_packages.add(root_module)
# If it's ambiguous or unresolved, and not stdlib/local/external,
# check if it's a common third-party package or can be verified
elif imp.classification == "ambiguous" or imp.classification is None:
# Check if it's not a local or external module
if not imp.resolved_path:
# Check if it's a common third-party package
if root_module in COMMON_THIRD_PARTY_PACKAGES:
# Try to get package name, or use module name as fallback
if root_module not in package_name_cache:
package_name_cache[root_module] = self._get_package_name_from_import(
imp.module_name
)
actual_package = package_name_cache[root_module]
if actual_package:
third_party_packages.add(actual_package)
else:
# Fallback: use module name (common packages like torch, numpy)
third_party_packages.add(root_module)
else:
# For other ambiguous imports, only add if verified
if root_module not in package_name_cache:
package_name_cache[root_module] = self._get_package_name_from_import(
imp.module_name
)
actual_package = package_name_cache[root_module]
if actual_package:
third_party_packages.add(actual_package)
# If we can't verify it's a package, don't add it
# (it's likely a local file that wasn't resolved properly)
if total_files > 50:
print() # New line after progress indicator
return sorted(list(third_party_packages))
def _fix_relative_imports_in_copied_files(
self, external_deps: list[ExternalDependency]
) -> None:
"""
Fix relative imports in copied dependency files.
When files are copied into the subfolder, their relative imports (like
`from ._shared.shared_dataclasses import ...`) break because the file
structure has changed. Convert these to absolute imports based on the
target location.
Args:
external_deps: List of external dependencies that were copied
"""
import ast
import re
# Find all Python files in copied dependencies
copied_files: list[Path] = []
for dep in external_deps:
if dep.target_path.is_file() and dep.target_path.suffix == ".py":
copied_files.append(dep.target_path)
elif dep.target_path.is_dir():
copied_files.extend(dep.target_path.rglob("*.py"))
for file_path in copied_files:
try:
content = file_path.read_text(encoding="utf-8")
original_content = content
lines = content.split("\n")
modified = False
try:
tree = ast.parse(content, filename=str(file_path))
except SyntaxError:
continue
lines_to_modify: dict[int, str] = {}
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
if node.module is None:
continue
# Check if this is a relative import (level > 0)
if node.level == 0:
continue
line_num = node.lineno - 1
if line_num < 0 or line_num >= len(lines):
continue
original_line = lines[line_num]
# Convert relative import to absolute based on target location
# When a file is copied to the package root, relative imports need to be absolute
# For example: from ._shared.shared_dataclasses -> from _shared.shared_dataclasses
if node.module:
# Remove the leading dots and convert to absolute
# If it was `from ._shared.shared_dataclasses`, it becomes `from _shared.shared_dataclasses`
absolute_module = node.module
new_line = re.sub(
rf"^(\s*)from\s+\.+{re.escape(node.module)}\s+import",
rf"\1from {absolute_module} import",
original_line,
)
else:
# from . import X -> from . import X (keep as relative, but at package root level)
# Actually, if we're at package root, this should work as-is
# But if the file was in a subdirectory, we need to adjust
# For now, keep it as relative import
continue
if new_line != original_line:
lines_to_modify[line_num] = new_line
modified = True
if modified:
for line_num, new_line in lines_to_modify.items():
lines[line_num] = new_line
new_content = "\n".join(lines)
if file_path not in self._modified_import_files:
self._modified_import_files[file_path] = original_content
file_path.write_text(new_content, encoding="utf-8")
print(f"Fixed relative imports in copied file: {file_path}")
except Exception as e:
print(
f"Warning: Could not fix imports in copied file {file_path}: {e}",
file=sys.stderr,
)
def _calculate_relative_import_depth(
self, file_path: Path, module_path: Path, src_dir: Path
) -> str:
"""
Calculate the relative import prefix (., .., ...) based on directory depth.
Args:
file_path: Path to the file containing the import
module_path: Path to the imported module (file or directory)
src_dir: Source directory (package root)
Returns:
String with appropriate number of dots (e.g., ".", "..", "...")
"""
try:
# Get relative paths from src_dir
file_dir = file_path.parent
# If module_path has a file extension (.py), treat it as a file and use its parent
# Otherwise, treat it as a directory
# This handles cases where the file doesn't exist yet (is_file() would return False)
if module_path.suffix == ".py" or (module_path.is_file() if module_path.exists() else False):
module_dir = module_path.parent
else:
module_dir = module_path
# Normalize both to be relative to src_dir
try:
file_rel = file_dir.relative_to(src_dir)
module_rel = module_dir.relative_to(src_dir)
except ValueError:
# If not relative to src_dir, fall back to single dot
return "."
# Calculate depth difference
# If paths are ".", depth is 0
file_depth = len(file_rel.parts) if file_rel.parts and file_rel.parts != (".",) else 0
module_depth = len(module_rel.parts) if module_rel.parts and module_rel.parts != (".",) else 0
depth_diff = file_depth - module_depth
if depth_diff == 0:
# Same depth - check if they're the same directory or siblings
if file_rel == module_rel:
return "." # Same directory
else:
# Sibling directories at same depth - need to go up one level
# e.g., PytorchCoco/ and _shared/ both at depth 1, need ..
return ".."
elif depth_diff > 0:
# File is deeper than module, need to go up
# e.g., file at depth 2, module at depth 0, need ...
return "." * (depth_diff + 1) # Go up depth_diff levels
else:
# Module is deeper than file, use single dot
return "."
except (ValueError, AttributeError):
# If paths are not relative to src_dir, fall back to single dot
return "."
def _convert_imports_to_relative(
self, python_files: list[Path], external_deps: list[ExternalDependency]
) -> None:
"""
Convert absolute imports to relative imports for subfolder builds.
For subfolder builds, when external dependencies are copied into the subfolder,
imports need to be converted from absolute to relative so they work correctly
when the package is installed. This includes:
1. Imports of copied dependencies (e.g., `from _shared.image_utils` -> `from ._shared.image_utils`)
2. Imports of local files within the subfolder (e.g., `from detect_empty_drawings_utils` -> `from .detect_empty_drawings_utils`)
Only imports classified as "external" or "local" are converted. Imports classified
as "ambiguous", "third_party", or "stdlib" are left unchanged.
Args:
python_files: List of Python files in the source directory
external_deps: List of external dependencies that were copied
"""
import ast
import re
# Create analyzer for classifying imports
analyzer = ImportAnalyzer(self.project_root)
# Build a set of import names that were copied
copied_import_names: set[str] = set()
for dep in external_deps:
root_module = dep.import_name.split(".")[0]
copied_import_names.add(root_module)
copied_import_names.add(dep.import_name)
# Build a set of local file names in the subfolder (excluding copied dependencies)
local_file_names: set[str] = set()
for file_path in python_files:
# Skip files that are part of copied dependencies
is_copied_file = any(file_path.is_relative_to(dep.target_path) for dep in external_deps)
if is_copied_file:
continue
if not file_path.is_relative_to(self.src_dir):
continue
# Get the module name (filename without .py extension)
if file_path.suffix == ".py":
module_name = file_path.stem
if module_name != "__init__":
local_file_names.add(module_name)
# Only modify files that are in the original subfolder (not the copied dependencies)
for file_path in python_files:
# Skip files that are part of copied dependencies
is_copied_file = any(file_path.is_relative_to(dep.target_path) for dep in external_deps)
if is_copied_file:
continue
# Skip if file is not in src_dir (shouldn't happen, but safety check)
if not file_path.is_relative_to(self.src_dir):
continue
try:
content = file_path.read_text(encoding="utf-8")
original_content = content
lines = content.split("\n")
modified = False
# Parse the file with AST to find imports accurately
try:
tree = ast.parse(content, filename=str(file_path))
except SyntaxError:
# Skip files with syntax errors
continue
# Track which lines need to be modified
lines_to_modify: dict[int, str] = {}
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom):
if node.module is None:
continue
# Extract root module (first part before the first dot)
root_module = node.module.split(".")[0]
# Classify the root module first to check if it's third-party/ambiguous/stdlib
# If root is third-party/ambiguous/stdlib, skip ALL its submodules
root_import_info = ImportInfo(
module_name=root_module,
import_type="from",
line_number=node.lineno,
file_path=file_path,
)
analyzer.classify_import(root_import_info, self.src_dir)
# If root is third-party/ambiguous/stdlib, skip ALL submodules
if root_import_info.classification in ("third_party", "ambiguous", "stdlib"):
continue
# Now classify the full import to determine if it should be converted
import_info = ImportInfo(
module_name=node.module,
import_type="from",