kompas_window/get_all_sheets.py

153 lines
7.2 KiB
Python

# pip install pywin32
import pythoncom
from win32com.client import Dispatch, gencache
import os
def get_all_sheets():
try:
# Получаем API интерфейсов версии 5
api5_module = gencache.EnsureModule("{0422828C-F174-495E-AC5D-D31014DBBE87}", 0, 1, 0)
api5_api = api5_module.KompasObject(
Dispatch("Kompas.Application.5")._oleobj_.QueryInterface(api5_module.KompasObject.CLSID, pythoncom.IID_IDispatch)
)
module = gencache.EnsureModule("{69AC2981-37C0-4379-84FD-5DD2F3C0A520}", 0, 1, 0)
api = module.IKompasAPIObject(
Dispatch("Kompas.Application.7")._oleobj_.QueryInterface(module.IKompasAPIObject.CLSID, pythoncom.IID_IDispatch)
)
application = module.IApplication(api)
application.Visible = True
result = []
for i in range(application.Documents.Count):
try:
doc = application.Documents.Open(i)
doc_type = doc.DocumentType
if doc_type not in [4, 5]: # 4 — чертеж, 5 — сборка
continue
doc.Active = True
doc_path = doc.Path
doc_name = '-'.join(doc.Name.split('.')[:-1])
# Добавляем заголовок документа
result.append(f"{'=' * 80}")
result.append(f"Анализ документа: {doc_name}")
result.append(f"Тип: {'Чертеж' if doc_type == 4 else 'Сборка'}")
result.append(f"Путь: {doc_path}")
result.append(f"{'=' * 80}")
doc_3d = module.IKompasDocument3D(doc)
top_part = doc_3d.TopPart
elements = []
bends = []
welding = []
def look_features(element):
feature = module.IFeature7(element)
sub_features = feature.SubFeatures(1, True, False) or []
for item in sub_features:
if type(item) in (module.ISheetMetalBend, module.ISheetMetalLineBend, module.ISheetMetalBody):
sub_sheets = item.Owner.SubFeatures(1, True, False)
if sub_sheets:
for b in sub_sheets:
bend = module.ISheetMetalBend(b)
bends.append(bend)
def look_drawing(part):
drawing_context = module.IDrawingContainer(part)
macro = module.IMacroObject3D(drawing_context)
sub_features = macro.Owner.SubFeatures(1, True, False) or []
for item in sub_features:
if type(item) in (module.IUserDesignationCompObj,):
welding.append(item)
def find_elements(part):
try:
drawing_context = module.IDrawingContainer(part)
macro = module.IMacroObject3D(drawing_context)
sub_features = macro.Owner.SubFeatures(1, True, False) or []
for item in sub_features:
if type(item) in (module.IUserDesignationCompObj,):
welding.append(item)
except Exception as e:
result.append("Ошибка в DrawingContext")
try:
doc_parts = module.IParts7(part.Parts)
for i in range(doc_parts.Count):
element = doc_parts.Part(i)
if element.Parts.Count == 0:
elements.append(element)
look_features(element)
find_elements(element)
except Exception as e:
result.append("Ошибка в Parts")
if doc_type == 5:
find_elements(top_part)
else:
elements.append(top_part)
look_drawing(top_part)
look_features(top_part)
result.append(f"\nНайдено:\n Элементов: {len(elements)}\n Гибов: {len(bends)}\n")
sorted_data = {
"Элементы": {},
"Материалы": {},
"Площади": {},
"Сварные соединения": {}
}
for e in elements:
# Элементы
name = f"{getattr(e, 'Name', 'Неизвестное имя')}, масса {round(getattr(e, 'Mass', 0), 3)} кг"
sorted_data["Элементы"][name] = sorted_data["Элементы"].get(name, 0) + 1
# Материалы
material = getattr(e, 'Material', "Неизвестный материал")
sorted_data["Материалы"][material] = sorted_data["Материалы"].get(material, 0) + 1
# Площади
try:
mass_inertial_params = module.IMassInertiaParam7(e)
area = round(mass_inertial_params.Area * 0.0001, 6) # Перевод в м²
area_key = f"площадь {material}, м²:"
sorted_data["Площади"][area_key] = sorted_data["Площади"].get(area_key, 0) + area
except Exception as e:
result.append(f"Ошибка при вычислении площади: {e}")
sorted_data["Площади"]["Общая площадь"] = sum(sorted_data["Площади"].values())
# Сварные соединения
if welding:
for w in welding:
w_name = w.Name
w_len = w_name.split("-")[-1].split("@")[0]
sorted_data["Сварные соединения"][w_name] = w_len
total_welding = sum(float(w_len) for w_len in sorted_data["Сварные соединения"].values() if isinstance(w_len, str) and w_len.isdigit())
sorted_data["Сварные соединения"]["Общая длина"] = round(total_welding, 2)
else:
sorted_data.pop("Сварные соединения", None) # Удаляем раздел, если данных нет
# Вывод результатов
for section, data in sorted_data.items():
if not data: # Пропускаем пустые разделы
continue
result.append(f"\n{section}:")
for key, value in data.items():
result.append(f" {key}: {value}")
result.append("") # Пустая строка для разделения
except Exception as e:
result.append(f"Ошибка при обработке документа {i}: {e}")
return "\n".join(result)
except Exception as e:
return f"Произошла ошибка: {e}"