Beispiel #1
0
 def export_pat(self, sender, args):
     if self._export_only:
         self.Close()
         export_dir = forms.pick_folder()
         if export_dir:
             self.export_pattern(export_dir)
     elif self.verify_name():
         self.Hide()
         domain = self.pick_domain()
         export_dir = forms.pick_folder()
         if domain and export_dir:
             self.create_pattern(domain,
                                 export_only=True,
                                 export_path=export_dir)
         self.Close()
Beispiel #2
0
	def selecionar_click(self,sender,e):
		self.folder = forms.pick_folder(title=None, owner=None)
		#print(self.folder)
		try:
			self.pathname.Text = "A árvore de pastas será criada no seguinte caminho:  \n" + self.folder
		except:
			pass
Beispiel #3
0
    def pick_usagelog_folder(self, sender, args):
        """Callback method for picking destination folder for usage log files
        """
        new_path = forms.pick_folder()

        if new_path:
            self.usagelogfile_tb.Text = os.path.normpath(new_path)
Beispiel #4
0
    def addfolder(self, sender, args):
        """Callback method for adding extension folder to configs and list"""
        new_path = forms.pick_folder()
        if new_path:
            new_path = os.path.normpath(new_path)

        if self.extfolders_lb.ItemsSource:
            uniq_items = set(self.extfolders_lb.ItemsSource)
            uniq_items.add(new_path)
            self.extfolders_lb.ItemsSource = list(uniq_items)
        else:
            self.extfolders_lb.ItemsSource = [new_path]
def filepath(filename_str):
    path = os.path.split(sys.argv[0])[0]
    try:
        if __shiftclick__ == True: raise Exception()
        with open(path + "\\" + filename_str, "r+") as f:
            folderpath = f.read()
            return folderpath
    except:
        folderpath = forms.pick_folder()
        if not folderpath: sys.exit()
        with open(path + "\\filepath.txt", "w") as f:
            f.write(folderpath)
        return folderpath
Beispiel #6
0
def Delete():
    global files
    global lengths

    directory = forms.pick_folder(
        "Select parent folder of backup families or files to be purged")

    if directory:
        DeleteRecursive(directory)

    b = convert_unit(lengths, SIZE_UNIT.MB)

    message = 'You are about to delete ' +\
              str(files) + ' files with a total of ' + str(b) + ' MB. Are you sure?'

    if forms.alert(message, ok=False, yes=True, no=True, exitscript=True):
        for file in files_to_delete:
            file.Delete()
        print(str(files) + ' files with a total of ' + str(b) + ' MB deleted.')
Beispiel #7
0

logger = script.get_logger()
output = script.get_output()


ASSMS = [
    'RevitAPI',
    'RevitAPIUI',
    # 'UIFramework',
    # 'Adwindows',
    'pyRevitLabs.Common',
    'pyRevitLabs.TargetApps.Revit',
    'pyRevitLabs.PyRevit',
]

dest_path = forms.pick_folder()

if dest_path:
    for assm_name in ASSMS:
        assm = assmutils.find_loaded_asm(assm_name)
        if assm:
            try:
                stubs_path = labs.PythonStubsBuilder.BuildAssemblyStubs(
                    assm[0].Location,
                    destPath=dest_path
                )
                print('Generated stubs for %s -> %s' % (assm_name, stubs_path))
            except Exception as sgEx:
                logger.error('Failed generating stubs for %s', assm_name)
Beispiel #8
0
__title__ = "Update\nFam/Prj\ninFolder"

__author__ = "Tillmann Baumeister"

from Autodesk.Revit import DB
import sys, os
import traceback
import pyrevit
from pyrevit import (forms, revit)
from pyrevit.forms import BaseCheckBoxItem

app = __revit__.Application

#path to file stored on disk
folderpath = forms.pick_folder()
if not folderpath:
    sys.exit()


# Get List of Files in Dir and SubDir.
def getListOfFiles(dirName):
    # create a list of file and sub directories
    # names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = []
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory
Beispiel #9
0
 def pick_telemetry_folder(self, sender, args):
     """Callback method for picking destination folder for telemetry files"""
     new_path = forms.pick_folder()
     if new_path:
         self.telemetryfile_tb.Text = os.path.normpath(new_path)
Beispiel #10
0
Campus = ET.SubElement(gbXML, "Campus", id="cmps-1")
Building = ET.SubElement(Campus, "Building", id="bldg-1")

#counter
spaces_created = 0
for space in spaces:
    area = space.Area
    #skip space if area is undefined
    if area > 0:
        try:
            area_string = str(round(area, 0))
            #split string at "." to truncate the period and the zeros following the period
            area_print = area_string.split(".")[0]
            #add space to element tree
            Space = ET.SubElement(Building, "Space")
            ET.SubElement(
                Space, "Name").text = space.LookupParameter("Name").AsString()
            ET.SubElement(Space, "Area").text = area_print
            spaces_created += 1
        except:
            pass
#create xml tree
tree = ET.ElementTree(gbXML)
save_path = os.path.join(
    forms.pick_folder(title="Choose folder to Save gbXML file"),
    "revit_export.xml")
#write to file
tree.write(save_path, encoding="utf-8", xml_declaration=True)

print(str(spaces_created) + " spaces created")
Beispiel #11
0
 OpenOptions,WorksetConfiguration, WorksetConfigurationOption, DetachFromCentralOption,\
    ModelPathUtils, SaveAsOptions, WorksharingSaveAsOptions, RevitLinkType, ViewFamilyType, \
    ViewFamily, View3D, IndependentTag
from System.Collections.Generic import List
from Autodesk.Revit.UI.Events import DialogBoxShowingEventArgs
from Autodesk.Revit.UI import UIApplication
from Autodesk.Revit.ApplicationServices import Application
clr.AddReferenceByPartialName('PresentationCore')
clr.AddReferenceByPartialName('PresentationFramework')
clr.AddReferenceByPartialName('System.Windows.Forms')
clr.AddReference('RevitAPIUI')
# Collect Save location and Rvt Files
collectorFiles = forms.pick_file(file_ext='rvt',
                                 multi_file=True,
                                 unc_paths=False)
destinationFolder = forms.pick_folder()


def RVTFileCollector(dir):
    files = []
    for file in os.listdir(dir):
        if file.endswith(".rvt"):
            #print(str(file))
            files.append(str(file))
    return files


def OpenFiles(oFile, app, audit):
    openOpt = OpenOptions()
    if audit == True:
        openOpt.Audit = True
Beispiel #12
0
"""
#pylint: disable=import-error,invalid-name,broad-except,superfluous-parens
import os
from pyrevit import forms
from pyrevit import script

# Custom modules in lib/
from file_utils import FileFinder
from family_utils import FamilyLoader

logger = script.get_logger()
output = script.get_output()


# Get directory with families
directory = forms.pick_folder("Select parent folder of families")
logger.debug('Selected parent folder: {}'.format(directory))
if directory is None:
    logger.debug('No directory selected. Calling script.exit')
    script.exit()

# Find family files in directory
finder = FileFinder(directory)
finder.search('*.rfa')

# Excluding backup files
backup_pattern = r'^.*\.\d{4}\.rfa$'
finder.exclude_by_pattern(backup_pattern)
paths = finder.paths

# Dictionary to look up absolute paths by relative paths
Beispiel #13
0
family_dict = {}
for family in revit.query.get_families(revit.doc, only_editable=True):
    if family.FamilyCategory:
        family_dict["%s: %s" %
                    (family.FamilyCategory.Name, family.Name)] = family

if family_dict:
    selected_families = \
        forms.SelectFromList.show(
            sorted(family_dict.keys()),
            title="Select Families to Save",
            multiselect=True)

    if selected_families:
        dest_folder = forms.pick_folder()
        if dest_folder:
            total_work = len(selected_families)
            for idx, family in enumerate(
                [family_dict[x] for x in selected_families]):
                family_filepath = op.join(dest_folder, family.Name + ".rfa")
                logger.info("Saving %s ..." % family_filepath)
                try:
                    family_doc = revit.doc.EditFamily(family)
                    family_doc.SaveAs(family_filepath)
                    family_doc.Close(False)
                except Exception as ex:
                    logger.error('Error saving family %s | %s',
                                 family_filepath, ex)
                output.update_progress(idx + 1, total_work)
else:
Beispiel #14
0
"""Exports selected schedules to TXT files on user desktop.

Shift-Click:
Rename files on Desktop
"""

import os
import os.path as op

from pyrevit import forms
from pyrevit import revit, DB

# if user shift-clicks, default to user desktop,
# otherwise ask for a folder containing the PDF files
if __shiftclick__:
    basefolder = op.expandvars('%userprofile%\\desktop')
else:
    basefolder = forms.pick_folder()

vseop = DB.ViewScheduleExportOptions()
# vseop.ColumnHeaders = DB.ExportColumnHeaders.None
# vseop.TextQualifier = DB.ExportTextQualifier.None
# vseop.FieldDelimiter = ','
# vseop.Title = False

for el in revit.get_selection():
    fname = "".join(x for x in el.ViewName if x not in ['*']) + '.txt'
    el.Export(basefolder, fname, vseop)
    print('EXPORTED: {0}\n      TO: {1}\n'.format(el.ViewName, fname))
Beispiel #15
0
 def pick(self, sender, args):
     path = pick_folder()
     if path:
         self.temp_dir.Text = path
Beispiel #16
0
    cleanup_str = cleanup_str.replace(r'ö', 'oe')
    cleanup_str = cleanup_str.replace(r'Ö', 'Oe')
    cleanup_str = cleanup_str.replace(r'ä', 'ae')
    cleanup_str = cleanup_str.replace(r'Ä', 'Ae')
    cleanup_str = cleanup_str.replace(r'ß', 'ss')
    cleanup_str = re.sub(r'[^a-zA-Z0-9_\-]', '_', cleanup_str)
    cleanup_str = re.sub(r'_+', '_', cleanup_str)
    cleanup_str = re.sub(r'(-_|_-)', '-', cleanup_str)
    return cleanup_str


stopwatch = Diagnostics.Stopwatch()
stopwatch.Start()

# dest_dir = op.expandvars('%userprofile%\\desktop')
dest_dir = forms.pick_folder()
img_types = DB.FilteredElementCollector(revit.doc)\
              .OfClass(DB.ImageType)\
              .ToElements()

with revit.Transaction("rename_img_types"):
    for img in img_types:
        # export images
        image = img.GetImage()
        image_name = op.basename(img.Path)
        image_path = op.join(dest_dir, image_name)
        image.Save(op.join(dest_dir, image_name))

        # add info to raster image type name
        img_size = convert_size(op.getsize(image_path))
        prefix = cleanup(image_name.rsplit(".", 1)[0])
Beispiel #17
0
    nameSpace = DB.Visual
    schema = getattr(nameSpace, patt)
    prop = getattr(schema, prop_name)
    return prop


logger = script.get_logger()
forms.check_modeldoc(revit.doc, exitscript=True)

# make sure user is using 2019 or later
app = revit.doc.Application
if int(app.VersionNumber) < 2018:
    forms.alert("You must use Revit 2018 or newer to use this script.", exitscript=True)

selected_folder = forms.pick_folder()
if selected_folder:
    # layeredBottomF0 = Base Highlights Color, SurfaceNormal = Top Bump Map, LayeredNormal = Bottom Bump Map
    mat_schemas = {
        "PrismLayeredSchema": [
            "LayeredDiffuse",
            "LayeredBottomF0",
            "SurfaceNormal",
            "LayeredNormal",
        ],
        "PrismOpaqueSchema": ["OpaqueAlbedo", "SurfaceNormal"],
        "PrismMetalSchema": ["SurfaceAlbedo", "SurfaceNormal"],
        "GenericSchema": ["GenericDiffuse", "GenericBumpMap", "CommonTintColor"],
    }

    # col = sorted(DB.FilteredElementCollector(revit.doc).OfClass(DB.Material), key=lambda x: x.Name)
Beispiel #18
0
from System.Collections.Generic import List
from Autodesk.Revit.UI.Events import DialogBoxShowingEventArgs
from Autodesk.Revit.UI import UIApplication
from Autodesk.Revit.ApplicationServices import Application

clr.AddReferenceByPartialName('PresentationCore')
clr.AddReferenceByPartialName('PresentationFramework')
clr.AddReferenceByPartialName('System.Windows.Forms')

# File Collector
# models = r"C:\\Users\\loum\\Desktop\\File Dump\\"

collectorFiles = forms.pick_file(file_ext='rvt',
                                 multi_file=True,
                                 unc_paths=False)
desiinationFolder = forms.pick_folder(title='SaveTo.....')


def RVTFileCollector(dir):
    files = []
    for file in os.listdir(dir):
        if file.endswith(".rvt"):
            #print(str(file))
            files.append(str(file))
    print files
    return files


def OpenFiles(files, app, audit):
    counter = 0
    for oFile in files:
Beispiel #19
0
# Import
from pyrevit import revit, DB
from pyrevit import script
from pyrevit import forms

# Store current document into variable
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

# Import Python modules
import os
import re

# Record for user action and store selected path
directory = forms.pick_folder()


# Retrieve all pathfiles and names from directory and subdirectories
def retrieveFamilies(directory):
    familiesNames = list()
    for folderName, subFolders, files in os.walk(directory):
        # Check if there are Revit families
        families = re.compile(r"[^{ddd+}]\.rfa$")
        for file in files:
            # Assign matched files to a variable
            matched = families.search(file)
            if matched:
                # Get path of families
                filePath = os.path.join(folderName, file)
                familiesNames.append(filePath)
Beispiel #20
0
logger = script.get_logger()
output = script.get_output()

threeD_view = revit.doc.ActiveView

# forms.check_viewtype(threeD_view, ViewType.ThreeD, exitscript=True)

groups = (FilteredElementCollector(
    revit.doc).OfClass(Group).WhereElementIsNotElementType().ToElements())

total_work = len(groups)
# print(total_work)

if total_work > 0:
    target_folder = forms.pick_folder(title="Select Image Save Location")
    if target_folder:
        viewTypeId = threeD_view.GetTypeId()
        for idx, group in enumerate(groups):

            viewSet = []
            # Get group Bounding Box and Create New
            groupBB = group.get_BoundingBox(threeD_view)
            gMax = groupBB.Max
            gMin = groupBB.Min
            height = XYZ(0, 0, gMax.Z).DistanceTo(XYZ(0, 0, gMin.Z))
            # print(height)
            width = XYZ(gMax.X, 0, 0).DistanceTo(XYZ(gMin.X, 0, 0))
            # print(width)
            # if height > width:
            #     newWidth = height/2*1.5177
Beispiel #21
0
if not scriptpath:
    scriptpath = "C:\\Users\\Till\\Desktop"
#Overwrite/Delete path.txt, w+ mode
if __shiftclick__:
    with open(scriptpath + "\\path.txt", "w+") as f:
        pass
    forms.alert("filepath deleted!")

mode = "a+"  # read, create file, write file, pointer at end.
with open(scriptpath + "\\path.txt", mode) as f:
    f.seek(0)
    filepath = f.readline()
    print("---Filepath----------------------------------")
    print(filepath)
    if not filepath:
        filepath = forms.pick_folder()
        f.seek(0)  # set pointer back to Beginning of file
        f.write(filepath)


# ---FILENAME ------------------------------
#func lookuppara; paraname as string: ex: "Sheet Number"
def lookupparaval(element, paraname):
    try:
        newp = element.LookupParameter(paraname)
    except:
        newp = None
        pass
    value = ""
    if newp:
        if newp.StorageType == StorageType.String: value = newp.AsString()