PyRevit CLI problem with Creating New family Instance in Opened IFC file

Hi for professionals!
I’m having issue with processing creating of NewFamilyInstance with pyRevit automation.
I alredy read Jerremy Tammik article about " Activate Your Family Symbol Before Using It"

Pipeline:
0. Im using revit template for IFC openings (all families are preloaded in it previously). I’ve check it and there are loaded models.
I don’t know why but revit removes walls and levels(temp.leveles) from template.

  1. I run code that loads initialization file in Revit via pyrevit terminal RUN command (with 2 files ifc and json)
  2. the Revit opens IFC model on backend (you can’t see changes and geometry in a viewport)
  3. it mapps objects families Symbols to revit according the object names
  4. Activates Families Symbols ( seems no problem is here)
  5. Should create a new family instance from this symbols
  6. saves revit file, exports dwg , and closes Revit.
  7. ALSO there is no way to logging run of pyrevit script - how to debug it???

If I run same code in revit python shell while revit is opened with some initialization model it’s works,
But as long as I try to run same actions by using pyrevit it’s not works - I get in output revit model with loaded families but without instances.
There are many other problems for opening IFC as document and working with it.

I’ll appreciate any help, Thanks!

CODE Main + activation function

import sys
import time
import datetime
import inspect
import logging

sys.path.append('C:\Program Files\IronPython 3.4\Lib\site-packages')

from pyrevit import HOST_APP  # for pyrevit script to open active ifc_document
import wescan_paths

init_revit_file = wescan_paths.INIT_REVIT__FILE  # for now using init_project_revit.rvt

model = init_revit_file
uidoc = HOST_APP.uiapp.OpenAndActivateDocument(model)
doc_pyrevit_init = uidoc.Document
print(doc_pyrevit_init)
print(doc_pyrevit_init.Title)


import wescan_imports
import wescan_file_extensions


import clr  # Imports to works with Revit API .NET implementation via python
from System.Collections.Generic import List
from collections import OrderedDict

from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *
from Autodesk.Revit.DB.IFC import *
from Autodesk.Revit.DB import Transaction, FilteredElementCollector, View3D, DWGExportOptions, ElementId
from Autodesk.Revit.ApplicationServices import *
from Autodesk.Revit.DB import Document, IFCExportOptions, Transaction
from Autodesk.Revit.UI.Events import DialogBoxShowingEventArgs
from Autodesk.Revit.UI.Events import DisplayingOptionsDialogEventArgs

from Autodesk.Revit.UI import TaskDialog, TaskDialogResult, TaskDialogCommandLinkId, TaskDialogCommonButtons
from Autodesk.Revit.DB import FailureProcessingResult, IFailuresPreprocessor
from Autodesk.Revit.DB import Transaction, FailureHandlingOptions

# ######################### FORMAT CONVERSION IMPORTS #########################################
from wescan_revit_helpers.open_ifc import open_ifc_file
from wescan_revit_helpers.export_dwg import export_project_to_dwg
from wescan_revit_helpers.save_to_rvt import save_project_to_rtv
from wescan_revit_helpers.export_ifc import export_to_IFC
from wescan_revit_helpers.family_loader import *

from wescan_utilities.get_project_name import get_project_name
from wescan_utilities.remove_files import remove_files

from wescan_mapp_item import *
from wescan_mapp_walls import *

from wescan_mapp_doors_windows import *
# from wescan_mapp_window import *

from wescan_fml_processor.item_class import *
from wescan_fml_processor.open_fml_file import load_json

from wescan_revit_processor.set_default_level import *
from wescan_revit_processor.new_level import *
from wescan_revit_processor.select_level import *
from wescan_revit_processor.new_view_plan import *

# from wescan_revit_processor.delete_model_host_level import *

from wescan_revit_processor.select_family_symbol import *

from wescan_revit_processor.convert_to_revit_units import *
from wescan_revit_processor.select_wall_type import *

######################### ALL PATHS #########################################
input_path = wescan_paths.INPUT_PATH  # for now using "test_input" folder

output_path = wescan_paths.OUTPUT_PATH  # for now using "test_output" folder

refid_and_model_names = wescan_paths.MODELS_FML_REFID_PATH
revit_models_storage = wescan_paths.MODELS_REVIT_PATH

doors_revit_models_path = wescan_paths.IFC_DOORS_MODELS_REVIT_PATH
windows_revit_models_path = wescan_paths.IFC_WINDOWS_MODELS_REVIT_PATH

input_extensions = wescan_file_extensions.INPUT_EXTENSIONS
output_extensions = wescan_file_extensions.OUTPUT_EXTENSIONS
remove_files_exstension = wescan_file_extensions.REMOVE_EXTENSIONS


def main_fml_to_revit_parser(document):

    project_name = get_project_name(input_path, input_extensions)  # carefully with input extensions
    # print('The project name is: {}'.format(project_name))
    fml_document = load_json(input_path, project_name)
    # print(fml_document)

    fml_centemiters_project_height = 0  # Starting values -> Variable used to sed correct values for floors

    for floor in fml_document['floors']:
        print('################## NEW LEVEL' + '#' * 100)

        level = floor['level']
        print('Level level N: {}'.format(level))
        level_name = floor['name']
        print('Level Name: {}'.format(level_name))
        original_level_high = floor['height']
        level_high = z_height_revit(original_level_high)
        print('Level Height in cm: {}'.format(original_level_high))
        print('Level Converted Height in cm: {}'.format(level_high))

        if level == 0:
            selected_level = select_and_set_default_zero_level(document, level_name)     # selecting and assigning default level in Revit
            print(type(selected_level))
            print('Default revit level been settled successfully!')
            logger.info('Default revit level been settled successfully!')
            host_level = select_level_by_name(document, level_name)
            zero_level_height = 0
            revit_project_height = level_high

            elevation_param = host_level.get_Parameter(BuiltInParameter.LEVEL_ELEV)
            elevation_value = elevation_param.AsDouble()
            print('Elevation of Host level {}: {}'.format(level_name, elevation_value))
            print('Host level Name -> {}'.format(host_level.Name))
            print('Host level Location -> {}'.format(host_level.Location))
            walls_z_base_coordinate = elevation_value
            print('Walls 0 Level Z Base coordinate -> {}'.format(walls_z_base_coordinate))

        elif level == 1:
            print('level is 1st - creating level')
            logger.info('level is 1st - creating level')
            first_level_height = zero_level_height + level_high    # usually 280cm
            print('Height for second floor -> {}'.format(first_level_height))
            level_create(document, level_name, first_level_height)
            host_level = select_level_by_name(document, level_name)
            revit_project_height = level_high

            elevation_param = host_level.get_Parameter(BuiltInParameter.LEVEL_ELEV)
            elevation_value = elevation_param.AsDouble()
            print('Elevation of Host level {}: {}'.format(level_name, elevation_value))
            print('Host level Name -> {}'.format(host_level.Name))
            print('Host level Location -> {}'.format(host_level.Location))
            walls_z_base_coordinate = elevation_value
            print('Walls 1st Level Z Base coordinate -> {}'.format(walls_z_base_coordinate))

        else:   # for level 2 3 4 5 after 1st
            print('level is not 0 - creating other levels')
            logger.info('level is not 0 - creating other levels')
            first_level_height += level_high
            level_create(document, level_name, first_level_height)    # commutative height
            host_level = select_level_by_name(document, level_name)
            revit_project_height = first_level_height

            elevation_param = host_level.get_Parameter(BuiltInParameter.LEVEL_ELEV)
            elevation_value = elevation_param.AsDouble()
            print('Elevation of Host level {}: {}'.format(level_name, elevation_value))
            print('Host level Name -> {}'.format(host_level.Name))
            print('Host level Location -> {}'.format(host_level.Location))
            walls_z_base_coordinate = elevation_value
            print('Walls Other Level Z Base coordinate -> {}'.format(walls_z_base_coordinate))

        designs = floor['designs']
        for design in designs:
            items = design['items']
            for item in items:
                print('Item -> {}'.format(item))

                items_refid = item['refid']

                default_revit_model_name = 'Default_XYZ_box'
                selected_family_symbol = select_symbol(document, items_refid, default_revit_model_name)
                activate_family(document, selected_family_symbol)


                new_model_from_item = mapping_item(document, item, revit_project_height, selected_family_symbol)

############################## SAVING FORMATS AND EXPORTING #####################################
    logging.info('Saving dwg files')
    export_project_to_dwg(document, output_path, project_name)
    logging.info('Saving rvt files')
    save_project_to_rtv(document, output_path, project_name)

    # logging.info('Exporting in IFC')
    # print('Exporting in IFC')
    # export_to_IFC(ifc_document, output_path, project_name)

    # logging.info('Making ZIP archive for project')
    # wescan_imports.make_zip(output_path, project_name, remove_files_exstension)

    # logging.info('Removing files after automation been processed...INPUT/OUTPUT paths')
    # remove_files(input_path, project_name, remove_files_exstension)
    # remove_files(output_path, project_name, remove_files_exstension)  # PROBLEM WITH REMOVING .rvt file


################ RUN ###################################################
document = __revit__.ActiveUIDocument.Document

start_time = time.time()  # Record the current time

# opening IFC
project_name_ifc = get_project_name(input_path, input_extensions)  # carefully with input extensions
ifc_document = open_ifc_file(document, input_path, project_name_ifc)

# executing main script with IFC document in backend
main_fml_to_revit_parser(ifc_document)

end_time = time.time()  # Record the current time again
execution_time = end_time - start_time  # Calculate the difference
print("MAIN FUNCTION Execution time:", execution_time, "seconds")
################ RUN ###################################################

and Separately function that Activates Symbol:

def activate_family(document, selected_loaded_family):
    """
    INPUT   -> previously loaded & selected_level family_symbol
            -> active revit ifc_document (like ifc in backend)
    1) Checking status of family_symbol by calling the method - family_symbol.IsActivated (False/True)
    2) Applying Activation -> Family.Activate() wrapped in Transaction
    3) Checking / printing activation status -> should return True
    RETURN -> Activated FamilySymbol
    """

    function_name = inspect.currentframe().f_code.co_name
    logger.info('Activating pre Selected and pre Loaded FamilySymbol -> {}'.format(function_name))
    print ('Activating pre Selected and pre Loaded FamilySymbol -> {}'.format(function_name))

    t = Transaction(document, "Activation selected_level Family")

    try:
        print('Family Symbol Activating.... -> {}'.format(selected_loaded_family.Name))

        t.Start()
        selected_loaded_family.Activate()

        document.Regenerate()


        t.Commit()
        print('Success -> Family name -> {}'.format(selected_loaded_family.Name))
        print('Success -> Family Is Active Status -> {}'.format(selected_loaded_family.IsActive))

        return selected_loaded_family

    except Exception as e:
        print('ERROR trying to ACTIVATE FamilySymbol -> {}'.format(e))
        if t.HasStarted():
            t.RollBack()
            print('ERROR trying to ACTIVATE FamilySymbol -> {} Transaction Status -> {}'.format(e, t.GetStatus()))