def create_gdb_featureclass(gdb, name): fc = arcpy.CreateFeatureclass_management(gdb, name, geometry_type="POINT") arcpy.EnableAttachments_management(fc) arcpy.AddGlobalIDs_management(fc) arcpy.EnableEditorTracking_management( fc, creator_field="created_user", creation_date_field="created_date", last_editor_field="last_edit_user", last_edit_date_field="last_edit_date", add_fields=True, record_dates_in="UTC") print("Feature Class {} created".format(name)) #Add comments table fc_comments_name = "{}_Comments".format(name) fc_comments = create_gdb_table(gdb, fc_comments_name) arcpy.EnableAttachments_management(fc_comments) arcpy.AddGlobalIDs_management(fc_comments) arcpy.EnableEditorTracking_management( fc_comments, creator_field="created_user", creation_date_field="created_date", last_editor_field="last_edit_user", last_edit_date_field="last_edit_date", add_fields=True, record_dates_in="UTC") return fc, fc_comments, fc_comments_name
def test_get_attachment_info(self): no_attach = self.workspace.get_attachment_info(self.FEATURE_CLASS_NAME) self.assertEqual(no_attach, None) arcpy.EnableAttachments_management(self.fc_path) attach = self.workspace.get_attachment_info(self.FEATURE_CLASS_NAME) self.assertEqual(attach.origin, self.FEATURE_CLASS_NAME)
def enable_copy_attachments(input_fc, output_fc): # Check if the input feature class has attachments table inputRow = input_fc + '__ATTACH' if not arcpy.Exists(inputRow): desc = arcpy.Describe(input_fc) inputRow = desc.Path.split('.')[0] + '.gdb\\' + desc.Name + '__ATTACH' if not arcpy.Exists(inputRow): arcpy.AddError( "Unable to locate the attachment table for the input feature class." ) return # Enable Attachments arcpy.AddMessage("Enabling Attachments") arcpy.EnableAttachments_management(output_fc) arcpy.AddMessage("Enabled Attachments") # Copy Attachments from Input feature class to Temp feature class. arcpy.AddMessage("Copying Attachments..") outputTable = output_fc + '__ATTACH' try: arcpy.Append_management(inputRow, outputTable) arcpy.AddMessage("Copied Attachments..") except Exception as e: arcpy.AddError(e)
def process_attachements(rows, fields, join_fc, gdb, table_name="attachments", working_folder=arcpy.env.scratchFolder): """ creates and handles the attachments Inputs: rows - list - attachments rows to insert to table fields - list - fields for insert cursor join_fc - string - path of file geodatabase feature class that will have attachments enabled. gdb - string - path to geodatabase table_name - string - name of attachments table working_folder - string - path to where attachments are stored. Output: boolean. True successful/False failed. """ tbl = arcpy.CreateTable_management(out_path=gdb, out_name=table_name)[0] arcpy.AddField_management(tbl, "ParentID", "TEXT", field_length=1320) arcpy.AddField_management(tbl, "PATH", "TEXT", field_length=1320) icur = arcpy.da.InsertCursor(tbl, ['ParentID', "PATH"]) for row in rows: icur.insertRow(__unicode_convert(row)) del row del rows del icur arcpy.EnableAttachments_management(in_dataset=join_fc) arcpy.AddAttachments_management(in_dataset=join_fc, in_join_field="GlobalID", in_match_table=tbl, in_match_join_field="ParentID", in_match_path_field="PATH", in_working_folder=working_folder) return True
def create_gdb_featureclass(gdb, name): fc = arcpy.CreateFeatureclass_management(gdb, name, geometry_type="POINT") arcpy.AddGlobalIDs_management(fc) arcpy.EnableAttachments_management(fc) arcpy.EnableEditorTracking_management(fc, "created_user", "created_date", "last_edit_user", "last_edit_date", "ADD_FIELDS", "UTC") print("Feature Class {} created".format(name)) #Add comments table fc_comments_name = "{}_Comments".format(name) fc_comments = create_gdb_table(gdb, fc_comments_name) arcpy.AddGlobalIDs_management(fc_comments) arcpy.EnableAttachments_management(fc_comments) arcpy.EnableEditorTracking_management(fc_comments, "created_user", "created_date", "last_edit_user", "last_edit_date", "ADD_FIELDS", "UTC") return fc_comments_name
def enable_copy_attachments(input_fc, output_fc): # Check if the input feature class has attachments table input_attachment_table = input_fc + '__ATTACH' if not arcpy.Exists(input_attachment_table): desc = arcpy.Describe(input_fc) input_attachment_table = desc.Path.split('.')[0] + '.gdb\\' + desc.Name + '__ATTACH' if not arcpy.Exists(input_attachment_table): arcpy.AddError("Unable to locate the attachment table for the input feature class.") return # Enable Attachments arcpy.AddMessage("Enabling Attachments") arcpy.EnableAttachments_management(output_fc) arcpy.AddMessage("Enabled Attachments") # Copy Attachments from Input feature class to Temp feature class. arcpy.AddMessage("Copying Attachments..") outputTable = output_fc + '__ATTACH' try: # Check if the input feature class was related to the attachment tables via the ObjectID field. input_table_desc = arcpy.Describe(input_attachment_table) field_rel_objectID = [field for field in input_table_desc.fields if field.name.lower() == 'rel_objectid'] # If the input attachment table has REL_OBJECTID field then remap GUID fields between input and output attachment table. if field_rel_objectID: field_rel_globalID = [field for field in input_table_desc.fields if field.type.lower() == 'guid'] if field_rel_globalID: output_field = field_rel_globalID[0] else: arcpy.AddError("Can't copy attachments...") output_table_field_mappings = arcpy.FieldMappings() output_table_field_mappings.addTable(outputTable) input_table_field_mappings = arcpy.FieldMappings() input_table_field_mappings.addTable(input_attachment_table) output_table_globalID = [field for field in output_table_field_mappings.fields if field.type.lower() == 'guid'][0] field_index = output_table_field_mappings.findFieldMapIndex(output_table_globalID.name) fmap = output_table_field_mappings.fieldMappings[field_index] output_table_field_mappings.removeFieldMap(field_index) fmap.addInputField(input_attachment_table,output_field.name) output_table_field_mappings.addFieldMap(fmap) for input_field_map in input_table_field_mappings.fieldMappings: output_table_field_mappings.addFieldMap(input_field_map) arcpy.Append_management(input_attachment_table, outputTable, 'NO_TEST', output_table_field_mappings) else: arcpy.Append_management(input_attachment_table, outputTable) arcpy.AddMessage("Copied Attachments..") except Exception as e: arcpy.AddError(e)
def export(self, url, tempBddName, addPhoto, tempPicsBddName, cheminOutputCC47, prjInput, prjOutput, tempDir, tempPictureDir, proxyURL, entryXPath, elementPropertiesXPath, pictureLabel, objectIDLabel, titleLabel, xLabel, yLabel, projectionMethod, customEntries = None): start = time.time() log('Fichier log infos:\n\tURL: ' + str(url) + '\n\tOutput: ' + str(cheminOutputCC47) + '\n') # Creation des dossiers temporarires tempDirectory = createDirectory(tempDir) tempPictureDirectory = createDirectory(os.path.join(tempDirectory, tempPictureDir)) # Ajout du proxy si celui-ci est renseigne if proxyURL is not None and proxyURL != '': proxy_support = urllib2.ProxyHandler({"http": proxyURL}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) # Creation de la table temporaire self.createNewTabDelIfExists(tempDirectory, tempBddName) coucheOutputTmp = arcpy.CreateFeatureclass_management(os.path.join(tempDirectory, tempBddName), 'point', 'POINT') arcpy.EnableAttachments_management(coucheOutputTmp) # Activation des pieces jointes coucheOutputTmp2 = arcpy.CreateFeatureclass_management(os.path.join(tempDirectory, tempBddName), 'point2', 'POINT') arcpy.EnableAttachments_management(coucheOutputTmp2) # Creation de la table pour les pieces jointes coucheOutputPics = '' if addPhoto: coucheOutputPics = self.createNewPhotoTable(tempDirectory, tempPicsBddName) log('\n--- DEBUT ---') entries = self.getEntries(tempDirectory, url, entryXPath, elementPropertiesXPath) # Recuperation des entrees self.addEntriesFieldsDatabase(coucheOutputTmp, entries, customEntries) # Creation du schema de la table self.addEntriesDatabase(coucheOutputTmp, entries, addPhoto, coucheOutputPics, pictureLabel, objectIDLabel, titleLabel, tempPictureDirectory, xLabel, yLabel) # Ajout des entrees a la table self.copyCouche(coucheOutputTmp, coucheOutputTmp2, cheminOutputCC47, prjInput, prjOutput, addPhoto, coucheOutputPics, objectIDLabel, projectionMethod) # Copie la table temporaire dans la table finale # Suppression des donnees temporarires self.delTable(tempDirectory, tempBddName) if addPhoto: self.delTable(tempDirectory, tempPicsBddName) try: shutil.rmtree(tempDirectory) except: log('Le dossier ' + tempDirectory + ' n\'a pas pu etre supprime') log('\n--- FIN (' + str(round(time.time() - start, 3)) + 's) ---')
def copyData(self, base, to, addPhoto, basePhoto, objectIDLabel): log('\tCopie de ' + str(base) + ' vers ' + str(to)) if not arcpy.Exists(to): try: arcpy.Copy_management(base, to) except BaseException as e: log(e) else: arcpy.Append_management(base, to, "TEST", "", "") if addPhoto and basePhoto and basePhoto != '': arcpy.EnableAttachments_management(to) arcpy.AddAttachments_management(to, objectIDLabel, basePhoto, 'objid', "img", "#")
def enable_copy_attachments(input_fc, output_fc): # Enable Attachments arcpy.AddMessage("Enabling Attachments") arcpy.EnableAttachments_management(output_fc) arcpy.AddMessage("Enabled Attachments") # Copy Attachments from Input feature class to Temp feature class. arcpy.AddMessage("Copying Attachments..") inputRow = input_fc + '__ATTACH' outputTable = output_fc + '__ATTACH' try: arcpy.Append_management(inputRow, outputTable) arcpy.AddMessage("Copied Attachments..") except Exception as e: arcpy.Error(e)
pylab.xlabel("Distance to target") pylab.grid(True) # save the graph to a PNG file in the scratch folder graphPath = os.path.join(scratchFolder, r"profile" + str(llosID) + r".png") if debug == True: arcpy.AddMessage("graphPath: " + str(graphPath)) pylab.savefig(graphPath, dpi=900) pylab.cla() # clear the graph??? graphLocationDict[llosID] = graphPath deleteme.append(graphPath) # TODO: start an update cursor arcpy.AddMessage("Enabling attachments ...") arcpy.EnableAttachments_management(inputFeatures) matchTable = os.path.join(scratchGDB, "matchTable") deleteme.append(matchTable) arcpy.AddMessage("Building match table ...") arcpy.GenerateAttachmentMatchTable_management(inputFeatures, scratchFolder, matchTable, "pngname", "*.png", "ABSOLUTE") arcpy.AddMessage("Attaching graphs to lines ...") arcpy.AddAttachments_management(inputFeatures, "OID", matchTable, "MatchID", "Filename") # cleanup arcpy.AddMessage("Removing scratch data ...") for ds in deleteme:
def createTables(surveyGDB, outWorkspace, prefix): '''Creates the doamins, tables and relationships of the survey in the target workspace''' arcpy.AddMessage('\t-Creating Tables') arcpy.env.workspace = surveyGDB allTables = getSurveyTables(surveyGDB) dscW = arcpy.Describe(arcpy.env.workspace) #migrate the domains arcpy.AddMessage('\t\t-Creating Domains') for domainName in dscW.domains: if domainName[0:3] == 'cvd': arcpy.AddMessage('\t\t\t-'.format(domainName)) tempTable = 'in_memory\{0}'.format(domainName) domainTable = arcpy.DomainToTable_management(surveyGDB, domainName, tempTable,'CODE', 'DESC') newDomain = arcpy.TableToDomain_management(tempTable, 'CODE', 'DESC', outWorkspace, domainName, update_option='REPLACE') arcpy.Delete_management(tempTable) arcpy.AddMessage("\t\t-Creating Feature Classes & Tables") for table in allTables: dsc = arcpy.Describe(table) newTableName = "{0}_{1}".format(prefix, table) templateTable = template=os.path.join(surveyGDB, table) if dsc.datatype == u'FeatureClass': newTable = arcpy.CreateFeatureclass_management(outWorkspace, newTableName, "POINT", template=templateTable, spatial_reference=dsc.spatialReference) else: newTable = arcpy.CreateTable_management(outWorkspace, newTableName, template=templateTable) arcpy.AddMessage("\t\t\t-Created {0}".format(newTableName)) #Attach domains to fields tableFields = arcpy.ListFields(table) for field in tableFields: if field.domain != '': arcpy.AssignDomainToField_management(newTable, field.name, field.domain) if dscW.workspaceType == "RemoteDatabase": arcpy.RegisterAsVersioned_management(newTable) arcpy.AddMessage('\t\t-Creating Relationships') #Reconnect Relationship classes, checking for attachments CARDINALITIES = { 'OneToOne': "ONE_TO_ONE", 'OneToMany': "ONE_TO_MANY", 'ManyToMany': "MANY_TO_MANY" } for child in [(c.name, c.datatype) for c in dscW.children if c.datatype == u'RelationshipClass']: dscRC = arcpy.Describe(child[0]) RCOriginTable = dscRC.originClassNames[0] RCDestTable = dscRC.destinationClassNames[0] newOriginTable = "{0}_{1}".format(prefix, RCOriginTable) newOriginPath = os.path.join(outWorkspace, newOriginTable) if dscRC.isAttachmentRelationship: #Simple case - attachments have a dedicated tool arcpy.EnableAttachments_management(newOriginPath) else: newDestTable = "{0}_{1}".format(prefix, RCDestTable) newDestPath = os.path.join(outWorkspace, newDestTable) newRC = os.path.join(outWorkspace, "{0}_{1}".format(prefix, child[0])) relationshipType = "COMPOSITE" if dscRC.isComposite else "SIMPLE" fwd_label = dscRC.forwardPathLabel if dscRC.forwardPathLabel != '' else 'Repeat' bck_label = dscRC.backwardPathLabel if dscRC.backwardPathLabel != '' else 'MainForm' msg_dir = dscRC.notification.upper() cardinality = CARDINALITIES[dscRC.cardinality] attributed = "ATTRIBUTED" if dscRC.isAttributed else "NONE" originclassKeys = dscRC.originClassKeys originclassKeys_dict = {} for key in originclassKeys: originclassKeys_dict[key[1]] = key[0] originPrimaryKey = originclassKeys_dict[u'OriginPrimary'] originForiegnKey = originclassKeys_dict[u'OriginForeign'] arcpy.CreateRelationshipClass_management(newOriginPath, newDestPath, newRC, relationshipType, fwd_label, bck_label, msg_dir, cardinality, attributed, originPrimaryKey, originForiegnKey)
def create_gdb_featureclass(gdb,name): fc = arcpy.CreateFeatureclass_management(gdb,name, geometry_type="POINT") arcpy.AddGlobalIDs_management(fc) arcpy.EnableAttachments_management(fc) arcpy.EnableEditorTracking_management(fc, "created_user","created_date","last_edit_user","last_edit_date","ADD_FIELDS","UTC")
else: oid = "OID@" with arcpy.da.UpdateCursor(table, [oid, fields[table]]) as cur: for row in cur: row[1] = row[0] cur.updateRow(row) edit.stopOperation() edit.stopEditing(True) print("Merging {0} and {1}, creating {2}".format(feature_class_1, feature_class_2, output_feature_class)) FILE.write("Merging {0} and {1}, creating {2}\n".format(feature_class_1, feature_class_2, output_feature_class)) arcpy.Merge_management([feature_class_1, feature_class_2], output_feature_class) print("Enabling attachments on {0}, creating {1}".format(output_feature_class, attachment_table_merge)) FILE.write("Enabling attachments on {0}, creating {1}\n".format(output_feature_class, attachment_table_merge)) arcpy.EnableAttachments_management(output_feature_class) arcpy.MakeFeatureLayer_management(output_feature_class, jointable) for table in [[attachment_table_1, feature_class_1, firsttable],[attachment_table_2, feature_class_2, secondtable]]: tableview = "testmergedattachments" arcpy.MakeTableView_management(table[0], tableview) arcpy.AddJoin_management(tableview, fields[table[0]], jointable, fields[table[1]], "KEEP_COMMON") print("Creating table {0}".format(table[2])) FILE.write("Creating table {0}\n".format(table[2])) arcpy.TableToTable_conversion(tableview, arcpy.env.workspace, table[2]) edit = arcpy.da.Editor(arcpy.env.workspace) edit.startEditing(False, is_versioned) edit.startOperation()
def MatchPhotos2Rows(folder, fc, timefield, outtable, badphotostable="", attachphotos="", timetol=0, offset=0): try: # Convert text from boolean parameters to Python True | False attachphotos = True if attachphotos.lower() in [ "true", "add_attachments", "" ] else False oidfield = arcpy.Describe(fc).OIDFieldName dict = {} # Create dictionary of timestamps in Input Table for row in da.SearchCursor(fc, [oidfield, timefield]): dict[row[0]] = row[1] # Get all photo files from Input Folder photolist = ExifUtils.ListPhotos(folder) # Create outputs CreateOutputs(outtable, badphotostable, photolist) foundone = 0 icur = incurbad = None # Set progress bar arcpy.SetProgressor("step", "", 0, len(photolist), 1) try: with arcpy.da.Editor(os.path.dirname(outtable)) as edit_session: # Open an InsertCursor to write matches to the Output Table icur = da.InsertCursor( outtable, ["IN_FID", "Photo_Path", "Photo_Name", "Match_Diff"]) # Open an InsertCursor to write a list of non-matching photos incurbad = da.InsertCursor( badphotostable, ["Photo"]) if badphotostable else None # Get DateTime information from each photo for file in photolist: photo = ExifUtils.GetExifMetadata(file) # If the photo has a valid Exif header with DateTime information if photo.m: # Turn timestamp string into a Python datetime class photo.m = datetime.datetime.fromtimestamp( time.mktime( time.strptime(photo.m, '%Y:%m:%d %H:%M:%S'))) # If a time offset was specified, change the photo timestamp if offset: photo.m += datetime.timedelta(seconds=offset) # Find a match for this DateTime closestID = ClosestTime(photo.m, dict.items()) # Determine if the time difference between this photo and row is within the tolerance closestDif = abs(dict[closestID] - photo.m).total_seconds() # If the difference is within the tolerance, make a match by writing an output row if closestDif <= timetol or timetol == 0: icur.insertRow([ closestID, photo.file, os.path.basename(photo.file), closestDif ]) foundone = 1 else: # Write the photo path to the Unmatched Photos Table if badphotostable: incurbad.insertRow([photo.file]) else: # Write the photo path to the Unmatched Photos Table if badphotostable: incurbad.insertRow([photo.file]) arcpy.SetProgressorPosition() except: raise finally: if icur: del icur if incurbad: del incurbad # Attach photos if option specified if attachphotos: arcpy.EnableAttachments_management(fc) arcpy.AddAttachments_management(fc, oidfield, outtable, "IN_FID", "Photo_Path", "") # If none of the photos were matched give the standard empty output warning if not foundone: arcpy.AddIDMessage("WARNING", 117) except: if arcpy.Exists(outtable): arcpy.Delete_management(outtable) if arcpy.Exists(badphotostable): arcpy.Delete_management(badphotostable) arcpy.AddIDMessage("ERROR", 999999) sys.exit()
dictList = list(dict.keys()) dictList.sort() x = 1 y = 0 while x <= count: with arcpy.da.UpdateCursor(fc, ["OID@", "GlobalID_Str"], "OBJECTID = " + str(x)) as cursor: for row in cursor: row[1] = dict[dictList[y]] cursor.updateRow(row) x += 1 y += 1 try: arcpy.EnableAttachments_management(fc) except: PrintException("Error Adding Attachments") try: arcpy.AddField_management(fc + "__ATTACH", "GlobalID_Str", "TEXT") arcpy.AddField_management(fc + "__ATTACH", "PhotoPath", "TEXT") except: PrintException("Error Adding Field") # Add Attachments # Create Match Table try: for x in data['layers'][0]['attachments']: gaUrl = x['url'] gaFolder = cwd + os.sep + x['parentGlobalId'] if not os.path.exists(gaFolder):
arcpy.FeatureClassToFeatureClass_conversion(TemplateFC,Geodatabase,"PhotoPoints") else: pass if CameraInput == "Associate Photo with Parcel": arcpy.AddMessage("Step 8: Adding survey question fields") else: arcpy.AddMessage("Step 2: Adding Survey question fields") if CameraInput == 'Associate Photo with Parcel': arcpy.Append_management(ParcelPointClassHelper, ParcelPointHelper, "NO_TEST") arcpy.AddField_management(ParcelPointHelper, "REVERSE", "TEXT", "", "", "5", "", "NULLABLE", "NON_REQUIRED", "") arcpy.JoinField_management(ParcelPointHelper, ParcelPIN, PhotoFeatureClass3, ParcelPIN) arcpy.CalculateField_management(ParcelPointHelper, "REVERSE", "!REVERSE_1!", "PYTHON", "") arcpy.EnableAttachments_management(ParcelPointHelper) arcpy.AddAttachments_management(ParcelPointHelper, ParcelPIN, PhotoFeatureClass3, ParcelPIN, "Path2", "") arcpy.AddMessage("Step 9: Creating photo attachments") else: pass if CameraInput == 'Associate Geotagged Photo with Point (photo has location)': arcpy.AddMessage("Step 3: Adding application required fields") arcpy.AddField_management(ParcelPointHelper, "BSTPHOTOID", "TEXT", "", "", "25", "Best Photo Identifier", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ParcelPointHelper, "SRVNAME", "TEXT", "", "", "25", "Surveyor Name", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ParcelPointHelper, "Path", "TEXT","", "", "254", "Path", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ParcelPointHelper, "Name", "TEXT","", "", "150", "Name", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ParcelPointHelper, "DateTime", "TEXT","", "", "100", "DateTime", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ParcelPointHelper, "Direction", "Double","", "", "", "Direction", "NULLABLE", "NON_REQUIRED", "")
field_length="", field_alias=editor_tracking_fields[3][1], field_is_nullable="NULLABLE", field_is_required="NON_REQUIRED", field_domain="") #Enable Editor Tracking arcpy.EnableEditorTracking_management( in_dataset=feature_class_created, creator_field=editor_tracking_fields[0][0], creation_date_field=editor_tracking_fields[1][0], last_editor_field=editor_tracking_fields[2][0], last_edit_date_field=editor_tracking_fields[3][0], add_fields="", record_dates_in="UTC") # Enable attachments arcpy.EnableAttachments_management(in_dataset=feature_class_created) # # Optionally: Add Global IDs # arcpy.AddGlobalIDs_management(feature_class_created) print( datetime.datetime.today().strftime('%c') + ": Feature classes have been added, with global ids, editor tracking and attachments enabled" ) print('===================') print("Ready: " + datetime.datetime.today().strftime('%c')) print('===================') # In case you want to publish an empty File Geodatabase, you can zip it here and now print('Do you want to zip the File Geodatabase {} immediately?'.format(fgdb)) answer = input('y/yes or n/no >> ').lower() if answer in ['yes', 'y']:
def create_fcs(): for _fc in fcDict: if fcDict[_fc] == "TABLE": _dataset = os.path.join(get_workspace(), _fc) if arcpy.Exists(_dataset) is True: arcpy.Delete_management(_dataset) print("Table: " + _fc + " deleted") arcpy.CreateTable_management(get_workspace(), _fc) arcpy.AddGlobalIDs_management(_dataset) if _fc == "FIDA_ANHANGLFP" or _fc == "FIDA_ANHANGHFP": arcpy.EnableAttachments_management(_dataset) if sde_fida is True: arcpy.ChangePrivileges_management( _dataset, "ARCSDE_EDITOR", "GRANT", "GRANT" ) arcpy.ChangePrivileges_management(_dataset, "ARCSDE_READER", "GRANT") # if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_dataset, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled") # Anhang: EnableEditorTracking (wichtig für BranchVersioning) if _fc == "FIDA_ANHANGLFP" or _fc == "FIDA_ANHANGHFP": _datasetattach = os.path.join(get_workspace(), _fc + "__ATTACH") if sde_fida is True: arcpy.ChangePrivileges_management( _datasetattach, "ARCSDE_EDITOR", "GRANT", "GRANT" ) arcpy.ChangePrivileges_management( _datasetattach, "ARCSDE_READER", "GRANT" ) arcpy.EnableEditorTracking_management( in_dataset=_datasetattach, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled __ATTACH") print("Table: " + _fc + " created") else: _dataset = os.path.join(get_workspace(), featuredataset, _fc) _out_path = os.path.join(get_workspace(), featuredataset) _has_z = "ENABLED" arcpy.CreateFeatureclass_management( out_path=_out_path, out_name=_fc, geometry_type=fcDict[_fc], has_z=_has_z, out_alias=_fc, ) arcpy.AddGlobalIDs_management(_dataset) # if sde_fida is True: arcpy.EnableEditorTracking_management( in_dataset=_dataset, creator_field="CREATOR_FIELD", creation_date_field="CREATOR_DATE_FIELD", last_editor_field="LAST_EDITOR_FIELD", last_edit_date_field="LAST_EDITOR_DATE_FIELD", add_fields="ADD_FIELDS", record_dates_in="UTC", ) print("Tracking enabled") print("Featureclass: " + _fc + " created")
import arcpy target_attachment = target + "__ATTACH" jointable = "jointable" newfield = "oldglobalid" tableview = "test1234" temptable = "deleteme" newglobalid = "newglobalid" arcpy.env.workspace = GDB_location arcpy.env.overwriteOutput = True arcpy.env.qualifiedFieldNames = True fieldsyntax = target + "_" + "GLOBALID" print("Enabling attachments") arcpy.EnableAttachments_management(target) for table in [target, source, source_attachment]: print("Adding field {0} to {1}".format(newfield, table)) arcpy.AddField_management(table, newfield, "TEXT") edit = arcpy.da.Editor(arcpy.env.workspace) edit.startEditing(False, False) edit.startOperation() oid = "GLOBALID" if table == source_attachment: oid = "REL_GLOBALID" print("Persisting old global id in {0}".format(table)) with arcpy.da.UpdateCursor(table, [oid, newfield]) as cur: for row in cur:
def do_analysis(inFC, outDir, uniqueNameField, googleMapsAPIKey, headingField=None, attachmentBool=True): """This is the main function call for the StreetViewGISRetrieval Tool. It interacts with the Google Maps API and the ArcGIS Arcpy library to fill a directory with street view images that correspond to an input feature's inside centroids.""" try: arcpy.env.overwriteOutput = True workspace = os.path.dirname(inFC) FileName = os.path.basename(inFC) # tempOutName = arcpy.ValidateTableName("TempBlockFC_1", workspace) # tempOutFeature = os.path.join(workspace, tempOutName) # Add New Fields arcPrint( "Adding new field for Image paths, will change if images location change.", True) featurePathField = arcpy.ValidateFieldName("UniqueFeatPaths", workspace) AddNewField(inFC, featurePathField, "TEXT") arcPrint("Gathering feature information.", True) # Get feature description and spatial reference information for tool use desc = arcpy.Describe(inFC) spatialRef = desc.spatialReference shpType = desc.shapeType srName = spatialRef.name arcPrint( "The shape type is {0}, and the current spatial reference is: {1}." .format(str(shpType), str(srName)), True) WGS_1984_MajAux = arcpy.SpatialReference( 104199 ) # http://support.esri.com/cn/knowledgebase/techarticles/detail/34749 fNames = ["SHAPE@", uniqueNameField, featurePathField] if headingField and FieldExist(inFC, headingField): fNames.append(str(headingField)) if not os.path.exists(outDir): os.makedirs(outDir) arcPrint( "Specified directory did not exist, so a new one was created.", True) counter = 1 arcPrint( "Establishing an update cursor for simultaneous image collection and feature class correspondence.", True) if shpType == "Polyline": with arcpy.da.UpdateCursor( inFC, fNames, spatial_reference=WGS_1984_MajAux) as cursor: arcPrint( "Feature class is a polyline, using midpoint along line to determine location and heading to pass to API.", True) for row in cursor: try: arcPrint("!") midPoint = row[getFIndex(fNames, "SHAPE@")].positionAlongLine( .5, True) beyondMidPoint = row[getFIndex( fNames, "SHAPE@")].positionAlongLine(.500001, True) arcPrint("!") headingParam = getAngleBetweenPoints( midPoint, beyondMidPoint, True) arcPrint("!") midpointProjected = midPoint.projectAs(WGS_1984_MajAux) fileName = "{0}.{1}".format( str(row[getFIndex(fNames, uniqueNameField)]), "jpeg") fileOutPath = os.path.join(outDir, fileName) # Lat is y, Long is x- Passed to street vew image fetch_streetview_image_and_save( (midpointProjected.centroid.Y, midpointProjected.centroid.X), headingParam, fileOutPath) counter += 1 row[getFIndex(fNames, featurePathField)] = fileName cursor.updateRow(row) print("Completed save of image and updated row.") except Exception as e: arcPrint( "Iteration {0} had a handling error and was skipped." .format((str(counter)))) print(e.args[0]) else: with arcpy.da.UpdateCursor( inFC, fNames, spatial_reference=WGS_1984_MajAux) as cursor: arcPrint( "Feature class is either point or polygon, using label point to get location only.", True) for row in cursor: try: midLabelPoint = row[getFIndex(fNames, "SHAPE@")].labelPoint midLabelPointProjected = midLabelPoint.projectAs( WGS_1984_MajAux) headingParam = row[getFIndex( fNames, headingField)] if getFIndex( fNames, headingField) else None fileName = "{0}.{1}".format( str(row[getFIndex(fNames, uniqueNameField)]), "jpeg") fileOutPath = os.path.join(outDir, fileName) if headingParam: fetch_streetview_image_and_save( (midLabelPointProjected.centroid.Y, midLabelPointProjected.centroid.X), headingParam, fileOutPath) else: fetch_streetview_image_and_save( (midLabelPointProjected.centroid.Y, midLabelPointProjected.centroid.X), path=fileOutPath) counter += 1 row[getFIndex(fNames, featurePathField)] = fileName cursor.updateRow(row) print("Completed save of image and updated row.") except Exception as e: arcPrint( "Iteration {0} had a handling error and was skipped." .format((str(counter)))) print(e.args[0]) arcPrint("Image collection cycle completed. QAQC resulting Images.", True) if attachmentBool: arcPrint( "Attempting to attach images to feature class with Add Attachment's tool.", True) arcpy.EnableAttachments_management(inFC) arcpy.AddAttachments_management( inFC, in_match_path_field=featurePathField, in_working_folder=outDir) arcPrint("Images in directory were attached to the feature class.") arcPrint("Cleaning up intermediates.", True) del spatialRef, desc, cursor, WGS_1984_MajAux except arcpy.ExecuteError: print(arcpy.GetMessages(2)) except Exception as e: print(e.args[0])
def GeoPhotoToPoint(folder, fc, badphotostable="", addnongps="", attachphotos=""): try: # Convert text from boolean parameters to Python True | False addnongps = True if addnongps.lower() in ["true", "all_photos", "" ] else False attachphotos = True if attachphotos.lower() in [ "true", "add_attachments", "" ] else False # Get all photo files from Input Folder photolist = ExifUtils.ListPhotos(folder) # Create outputs CreateOutputs(fc, badphotostable, photolist) foundone = 0 incur = incurbad = None # Set progress bar arcpy.SetProgressor("step", "", 0, len(photolist), 1) try: with arcpy.da.Editor(os.path.dirname(fc)) as edit_session: # Open an InsertCursor to write point locations to a new feature class incur = da.InsertCursor(fc, [ "Path", "Name", "DateTime", "SHAPE@X", "SHAPE@Y", "SHAPE@Z", "Direction" ]) # Open an InsertCursor to write a list of photos with no GPS coordinates incurbad = da.InsertCursor( badphotostable, ["Photo"]) if badphotostable else None # Get GPS information from each photo for file in photolist: photo = ExifUtils.GetExifMetadata(file) # If the photo has a valid Exif header with coordinate information if (photo.x and photo.y) or addnongps: # Create the point with geometry and attributes incur.insertRow([ photo.file, os.path.basename(photo.file), photo.m, photo.x, photo.y, photo.z, photo.d ]) foundone = 1 if (not photo.x or not photo.y) and badphotostable: # Write the photo path to the Invalid Photos Table output incurbad.insertRow([photo.file]) arcpy.SetProgressorPosition() except: raise finally: if incur: del incur if incurbad: del incurbad # If none of the photos were geotagged, give the standard empty output warning if not foundone: arcpy.AddIDMessage("WARNING", 117) # Attach photos if option specified if attachphotos: if foundone or addnongps: oidfield = arcpy.Describe(fc).OIDFieldName arcpy.EnableAttachments_management(fc) arcpy.AddAttachments_management(fc, oidfield, fc, oidfield, "Path", "") except: # Delete outputs if failure occurs if arcpy.Exists(fc): arcpy.Delete_management(fc) if arcpy.Exists(badphotostable): arcpy.Delete_management(badphotostable) arcpy.AddIDMessage("ERROR", 999999) sys.exit()
import arcpy import csv import os from arcpy import env from os import listdir #Inputs: folder with attachments, the layer to attach to, the name of the attribute field the match is based on attachments_folder = arcpy.GetParameterAsText(0) attachments_layer = arcpy.GetParameterAsText(1) #Define match field on which to base join match_field = arcpy.GetParameterAsText(2) f_id_name = arcpy.GetParameterAsText(3) #Enable Attachments arcpy.EnableAttachments_management(attachments_layer) attachments_table = attachments_folder + "\\" + "attachments_Table.csv" #Parse file names to extract unique identifier (must be separated from file name structure by an '_'), then write csv table with open(attachments_table, 'wb') as output: writer = csv.writer(output, delimiter=",") writer.writerow([str(f_id_name), 'Attachment']) for f in os.listdir(attachments_folder): file_name, file_ext = os.path.splitext(f) f_file, f_id = file_name.split('_') if str(f).find('.pdf') > -1: writer.writerow([f_id, f]) #Add attachments