167 lines
7.7 KiB
Python
167 lines
7.7 KiB
Python
import pythoncom
|
||
from win32com.client import Dispatch, gencache
|
||
import os
|
||
|
||
def project_support():
|
||
"""
|
||
Функция для поддержки проектов: создание чертежей и спецификаций.
|
||
Возвращает строку с краткой информацией о выполнении.
|
||
"""
|
||
result = []
|
||
stats = {
|
||
'total_docs': 0,
|
||
'processed_docs': 0,
|
||
'drawings_created': 0,
|
||
'specs_created': 0,
|
||
'errors': 0,
|
||
'created_files': []
|
||
}
|
||
|
||
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
|
||
)
|
||
)
|
||
|
||
k_constants = gencache.EnsureModule(
|
||
"{75C9F5D0-B5B8-4526-8681-9903C567D2ED}", 0, 1, 0
|
||
).constants
|
||
|
||
application = module.IApplication(api)
|
||
saving_path = '../cdw/'
|
||
application.Visible = True
|
||
|
||
stats['total_docs'] = application.Documents.Count
|
||
result.append(f"Найдено документов: {stats['total_docs']}")
|
||
|
||
for i in range(application.Documents.Count):
|
||
try:
|
||
doc = application.Documents.Item(i) # Получаем документ по индексу
|
||
doc_type = doc.DocumentType
|
||
|
||
# Активируем документ через application.ActiveDocument
|
||
application.ActiveDocument = doc
|
||
doc_path = doc.Path
|
||
doc_name = '-'.join(doc.Name.split('.')[:-1])
|
||
stats['processed_docs'] += 1
|
||
|
||
# Логируем тип документа
|
||
result.append(f"Обработка документа #{i + 1}: {doc_name}")
|
||
if doc_type == k_constants.ksDocumentAssembly:
|
||
result.append(f"Документ является сборкой: {doc_name}")
|
||
elif doc_type == k_constants.ksDocumentPart:
|
||
result.append(f"Документ является деталью: {doc_name}")
|
||
else:
|
||
result.append(f"[ПРЕДУПРЕЖДЕНИЕ] Неизвестный тип документа: {doc_type}")
|
||
continue
|
||
|
||
# Получаем 3D-документ
|
||
doc_3d = module.IKompasDocument3D(doc)
|
||
doc_components = []
|
||
|
||
def extract_parts(part):
|
||
"""Рекурсивно извлекает все детали из сборки."""
|
||
parts = module.IParts7(part.Parts)
|
||
for j in range(parts.Count):
|
||
element = parts.Part(j)
|
||
if element.Parts.Count == 0 and not element.Standard:
|
||
if not any(el.Name == element.Name for el in doc_components):
|
||
doc_components.append(element)
|
||
else:
|
||
extract_parts(element)
|
||
|
||
if doc_type == k_constants.ksDocumentAssembly:
|
||
extract_parts(doc_3d.TopPart)
|
||
elif doc_type == k_constants.ksDocumentPart:
|
||
doc_components.append(doc_3d.TopPart)
|
||
|
||
# Обработка каждой детали
|
||
for component in doc_components:
|
||
component_ipart = module.IPart7(component)
|
||
if component_ipart.Standard:
|
||
continue
|
||
|
||
c_doc = application.Documents.Add(k_constants.ksDocumentDrawing)
|
||
c_layout = c_doc.LayoutSheets
|
||
c_sheet = c_layout.Item(0)
|
||
c_sheet.Format.Format = k_constants.ksFormatA3
|
||
c_sheet.Format.VerticalOrientation = False
|
||
c_sheet.Update()
|
||
|
||
c_size = [1, 1, 1]
|
||
if hasattr(component_ipart.Owner, 'ResultBodies') and component_ipart.Owner.ResultBodies is not None:
|
||
gabarit = [0, 0, 0, 0, 0, 0]
|
||
gabarit = component_ipart.Owner.ResultBodies.GetGabarit(*gabarit)
|
||
g1 = gabarit[1:4]
|
||
g2 = gabarit[4:]
|
||
c_size = [abs(g1[i] - g2[i]) for i in range(len(g1))]
|
||
|
||
c_filename = component_ipart.FileName
|
||
c_name = component_ipart.Name
|
||
c_doc_2d = module.IKompasDocument2D(c_doc)
|
||
c_views = c_doc_2d.ViewsAndLayersManager.Views
|
||
c_scale = c_sheet.Format.FormatHeight / sum(c_size)
|
||
|
||
try:
|
||
c_views.AddStandartViews(
|
||
c_filename,
|
||
c_name,
|
||
[1, 3, 5, 7],
|
||
float(c_size[1] * c_scale),
|
||
float(c_sheet.Format.FormatHeight - 25),
|
||
float(c_scale),
|
||
20, 20
|
||
)
|
||
except Exception as e:
|
||
stats['errors'] += 1
|
||
result.append(f"[ОШИБКА] Не удалось добавить виды для компонента {component.Name}: {str(e)}")
|
||
continue
|
||
|
||
if not os.path.exists(f"{doc_path}{saving_path}"):
|
||
os.makedirs(f"{doc_path}{saving_path}")
|
||
filename = '_'.join(filter(None, [component_ipart.Marking, c_name[:20]])).replace(' ', '-')
|
||
save_path = f"{doc_path}{saving_path}{filename}_{i}.cdw"
|
||
c_doc.SaveAs(save_path)
|
||
stats['drawings_created'] += 1
|
||
stats['created_files'].append(save_path)
|
||
|
||
if doc_type == k_constants.ksDocumentAssembly:
|
||
spec = application.Documents.Add(k_constants.ksDocumentSpecification)
|
||
spec_doc = module.ISpecificationDocument(spec)
|
||
spec_doc.AttachedDocuments.Add(doc.PathName, True)
|
||
spec_filename = f"Список_деталей_{i}"
|
||
spec_save_path = f"{doc_path}{saving_path}{spec_filename}.spw"
|
||
spec.SaveAs(spec_save_path)
|
||
stats['specs_created'] += 1
|
||
stats['created_files'].append(spec_save_path)
|
||
|
||
except Exception as e:
|
||
stats['errors'] += 1
|
||
result.append(f"[ОШИБКА] Документ #{i + 1}: {str(e)}")
|
||
|
||
# Формируем итоговый отчёт
|
||
result.append("\n=== РЕЗУЛЬТАТЫ ===")
|
||
result.append(f"Обработано документов: {stats['processed_docs']}/{stats['total_docs']}")
|
||
result.append(f"Создано чертежей: {stats['drawings_created']}")
|
||
result.append(f"Создано спецификаций: {stats['specs_created']}")
|
||
result.append(f"Ошибок: {stats['errors']}")
|
||
|
||
if stats['created_files']:
|
||
result.append("\nСозданные файлы:")
|
||
for file in stats['created_files']:
|
||
result.append(f" • {file}")
|
||
|
||
except Exception as e:
|
||
result.append(f"\n[КРИТИЧЕСКАЯ ОШИБКА]: {str(e)}")
|
||
|
||
return "\n".join(result) |