")
elif stash.startsWithInList(DupFileToKeep, DupFile['files'][0]['path']) and not stash.startsWithInList(whitelist, DupFile['files'][0]['path']):
fileHtmlReport.write(f"
Reason: not whitelist vs whitelist
")
elif isTaggedExcluded(DupFileToKeep) and not isTaggedExcluded(DupFile):
fileHtmlReport.write(f"
")
fileHtmlReport.write(f"{stash.Setting('htmlReportTable')}\n")
htmlReportTableHeader = stash.Setting('htmlReportTableHeader')
SceneTableHeader = htmlReportTableHeader
if htmlIncludeVideoPreview or htmlIncludeImagePreview:
fileHtmlReport.write(f"{htmlReportTableRow}{SceneTableHeader}Scene{htmlReportTableHeader}Duplicate to Delete{SceneTableHeader}Scene-ToKeep{htmlReportTableHeader}Duplicate to Keep\n")
else:
fileHtmlReport.write(f"{htmlReportTableRow}{htmlReportTableHeader}Duplicate to Delete{htmlReportTableHeader}Duplicate to Keep\n")
fileDuplicateCandidateForDeletionList = open(DuplicateCandidateForDeletionList, "w")
for DupFileSet in DupFileSets:
# stash.Trace(f"DupFileSet={DupFileSet}", toAscii=True)
QtyDupSet+=1
stash.progressBar(QtyDupSet, qtyResults)
SepLine = "---------------------------"
DupFileToKeep = None
DupToCopyFrom = ""
DupFileDetailList = []
for DupFile in DupFileSet:
QtyDup+=1
Scene = DupFile
if skipIfTagged and createHtmlReport == False and duplicateMarkForDeletion in Scene['tags']:
stash.Trace(f"Skipping scene '{Scene['files'][0]['path']}' because already tagged with {duplicateMarkForDeletion}")
continue
stash.TraceOnce(f"Scene = {Scene}", toAscii=True)
DupFileDetailList = DupFileDetailList + [Scene]
if os.path.isfile(Scene['files'][0]['path']):
if DupFileToKeep != None:
if int(DupFileToKeep['files'][0]['duration']) == int(Scene['files'][0]['duration']): # Do not count fractions of a second as a difference
QtyExactDup+=1
else:
QtyAlmostDup+=1
SepLine = "***************************"
if significantTimeDiffCheck(DupFileToKeep, Scene):
QtyRealTimeDiff += 1
if int(DupFileToKeep['files'][0]['width']) * int(DupFileToKeep['files'][0]['height']) < int(Scene['files'][0]['width']) * int(Scene['files'][0]['height']):
logReason(DupFileToKeep, Scene, f"resolution: {DupFileToKeep['files'][0]['width']}x{DupFileToKeep['files'][0]['height']} < {Scene['files'][0]['width']}x{Scene['files'][0]['height']}")
DupFileToKeep = Scene
elif significantMoreTimeCompareToBetterVideo(DupFileToKeep, Scene):
if significantTimeDiffCheck(DupFileToKeep, Scene):
theReason = f"significant-duration: {DupFileToKeep['files'][0]['duration']} < {Scene['files'][0]['duration']}"
else:
theReason = f"duration: {DupFileToKeep['files'][0]['duration']} < {Scene['files'][0]['duration']}"
reasonKeyword = "significant-duration" if significantTimeDiffCheck(DupFileToKeep, Scene) else "duration"
logReason(DupFileToKeep, Scene, theReason)
DupFileToKeep = Scene
elif isBetterVideo(DupFileToKeep, Scene):
logReason(DupFileToKeep, Scene, f"codec,bit_rate, or frame_rate: {DupFileToKeep['files'][0]['video_codec']}, {DupFileToKeep['files'][0]['bit_rate']}, {DupFileToKeep['files'][0]['frame_rate']} : {Scene['files'][0]['video_codec']}, {Scene['files'][0]['bit_rate']}, {Scene['files'][0]['frame_rate']}")
DupFileToKeep = Scene
elif stash.startsWithInList(whitelist, Scene['files'][0]['path']) and not stash.startsWithInList(whitelist, DupFileToKeep['files'][0]['path']):
logReason(DupFileToKeep, Scene, f"not whitelist vs whitelist")
DupFileToKeep = Scene
elif isTaggedExcluded(Scene) and not isTaggedExcluded(DupFileToKeep):
logReason(DupFileToKeep, Scene, f"not ExcludeTag vs ExcludeTag")
DupFileToKeep = Scene
elif allThingsEqual(DupFileToKeep, Scene):
# Only do below checks if all imporant things are equal.
if stash.startsWithInList(blacklist, DupFileToKeep['files'][0]['path']) and not stash.startsWithInList(blacklist, Scene['files'][0]['path']):
logReason(DupFileToKeep, Scene, f"blacklist vs not blacklist")
DupFileToKeep = Scene
elif stash.startsWithInList(blacklist, DupFileToKeep['files'][0]['path']) and stash.startsWithInList(blacklist, Scene['files'][0]['path']) and stash.indexStartsWithInList(blacklist, DupFileToKeep['files'][0]['path']) > stash.indexStartsWithInList(blacklist, Scene['files'][0]['path']):
logReason(DupFileToKeep, Scene, f"blacklist-index {stash.indexStartsWithInList(blacklist, DupFileToKeep['files'][0]['path'])} > {stash.indexStartsWithInList(blacklist, Scene['files'][0]['path'])}")
DupFileToKeep = Scene
elif stash.startsWithInList(graylist, Scene['files'][0]['path']) and not stash.startsWithInList(graylist, DupFileToKeep['files'][0]['path']):
logReason(DupFileToKeep, Scene, f"not graylist vs graylist")
DupFileToKeep = Scene
elif stash.startsWithInList(graylist, Scene['files'][0]['path']) and stash.startsWithInList(graylist, DupFileToKeep['files'][0]['path']) and stash.indexStartsWithInList(graylist, DupFileToKeep['files'][0]['path']) > stash.indexStartsWithInList(graylist, Scene['files'][0]['path']):
logReason(DupFileToKeep, Scene, f"graylist-index {stash.indexStartsWithInList(graylist, DupFileToKeep['files'][0]['path'])} > {stash.indexStartsWithInList(graylist, Scene['files'][0]['path'])}")
DupFileToKeep = Scene
elif favorLongerFileName and len(DupFileToKeep['files'][0]['path']) < len(Scene['files'][0]['path']) and not isWorseKeepCandidate(DupFileToKeep, Scene):
logReason(DupFileToKeep, Scene, f"path-len {len(DupFileToKeep['files'][0]['path'])} < {len(Scene['files'][0]['path'])}")
DupFileToKeep = Scene
elif favorLargerFileSize and int(DupFileToKeep['files'][0]['size']) < int(Scene['files'][0]['size']) and not isWorseKeepCandidate(DupFileToKeep, Scene):
logReason(DupFileToKeep, Scene, f"size {DupFileToKeep['files'][0]['size']} < {Scene['files'][0]['size']}")
DupFileToKeep = Scene
elif not favorLongerFileName and len(DupFileToKeep['files'][0]['path']) > len(Scene['files'][0]['path']) and not isWorseKeepCandidate(DupFileToKeep, Scene):
logReason(DupFileToKeep, Scene, f"path-len {len(DupFileToKeep['files'][0]['path'])} > {len(Scene['files'][0]['path'])}")
DupFileToKeep = Scene
elif not favorLargerFileSize and int(DupFileToKeep['files'][0]['size']) > int(Scene['files'][0]['size']) and not isWorseKeepCandidate(DupFileToKeep, Scene):
logReason(DupFileToKeep, Scene, f"size {DupFileToKeep['files'][0]['size']} > {Scene['files'][0]['size']}")
DupFileToKeep = Scene
else:
DupFileToKeep = Scene
# stash.Trace(f"DupFileToKeep = {DupFileToKeep}")
stash.Debug(f"KeepID={DupFileToKeep['id']}, ID={DupFile['id']} duration=({Scene['files'][0]['duration']}), Size=({Scene['files'][0]['size']}), Res=({Scene['files'][0]['width']} x {Scene['files'][0]['height']}) Name={Scene['files'][0]['path']}, KeepPath={DupFileToKeep['files'][0]['path']}", toAscii=True)
else:
stash.Error(f"Scene does NOT exist; path={Scene['files'][0]['path']}; ID={Scene['id']}")
for DupFile in DupFileDetailList:
if DupFileToKeep != None and DupFile['id'] != DupFileToKeep['id']:
if merge:
result = stash.mergeMetadata(DupFile, DupFileToKeep)
if result != "Nothing To Merge":
QtyMerge += 1
didAddTag = False
if stash.startsWithInList(whitelist, DupFile['files'][0]['path']) and (not whitelistDelDupInSameFolder or not hasSameDir(DupFile['files'][0]['path'], DupFileToKeep['files'][0]['path'])):
QtySkipForDel+=1
if isSwapCandidate(DupFileToKeep, DupFile):
if merge:
stash.mergeMetadata(DupFileToKeep, DupFile)
if toRecycleBeforeSwap:
sendToTrash(DupFile['files'][0]['path'])
stash.Log(f"Moving better file '{DupFileToKeep['files'][0]['path']}' to '{DupFile['files'][0]['path']}'; SrcID={DupFileToKeep['id']};DescID={DupFile['id']};QtyDup={QtyDup};Set={QtyDupSet} of {qtyResults};QtySwap={QtySwap};QtySkipForDel={QtySkipForDel}", toAscii=True, printTo=LOG_STASH_N_PLUGIN)
try:
shutil.move(DupFileToKeep['files'][0]['path'], DupFile['files'][0]['path'])
QtySwap+=1
except Exception as e:
tb = traceback.format_exc()
stash.Error(f"Exception while moving file '{DupFileToKeep['files'][0]['path']}' to '{DupFile['files'][0]['path']}; SrcID={DupFileToKeep['id']};DescID={DupFile['id']}'; Error: {e}\nTraceBack={tb}")
DupFileToKeep = DupFile
else:
if dupWhitelistTagId and tagDuplicates:
didAddTag = setTagId_withRetry(duplicateWhitelistTag, DupFile, DupFileToKeep, ignoreAutoTag=True)
stash.Log(f"NOT processing duplicate, because it's in whitelist. '{DupFile['files'][0]['path']}';AddTagW={didAddTag};QtyDup={QtyDup};Set={QtyDupSet} of {qtyResults};QtySkipForDel={QtySkipForDel}", toAscii=True)
else:
if isTaggedExcluded(DupFile):
QtyExcludeForDel+=1
stash.Log(f"Excluding file {DupFile['files'][0]['path']} because tagged for exclusion via tag {excludeDupFileDeleteTag};QtyDup={QtyDup};Set={QtyDupSet} of {qtyResults}")
else:
# ToDo: Add merge logic here
if deleteDup:
DupFileName = DupFile['files'][0]['path']
if not deleteBlacklistOnly or stash.startsWithInList(blacklist, DupFile['files'][0]['path']):
if not deleteLowerResAndDuration or (isBetterVideo(DupFile, DupFileToKeep) and not significantMoreTimeCompareToBetterVideo(DupFileToKeep, DupFile)) or (significantMoreTimeCompareToBetterVideo(DupFile, DupFileToKeep) and not isBetterVideo(DupFileToKeep, DupFile)):
QtyDeleted += 1
DupFileNameOnly = pathlib.Path(DupFileName).stem
stash.Warn(f"Deleting duplicate '{DupFileName}';QtyDup={QtyDup};Set={QtyDupSet} of {qtyResults};QtyDeleted={QtyDeleted}", toAscii=True, printTo=LOG_STASH_N_PLUGIN)
if alternateTrashCanPath != "":
destPath = f"{alternateTrashCanPath }{os.sep}{DupFileNameOnly}"
if os.path.isfile(destPath):
destPath = f"{alternateTrashCanPath }{os.sep}_{time.time()}_{DupFileNameOnly}"
shutil.move(DupFileName, destPath)
elif moveToTrashCan:
sendToTrash(DupFileName)
if dry_run:
result = f"dry_run enabled, but scene {DupFile['files'][0]['path']} would have been removed from stash with delete_file=True."
stash.Log(result)
else:
stash.destroyScene(DupFile['id'], delete_file=True)
updateDuplicateCandidateForDeletionList(DupFile['id'], removeScene = True)
elif tagDuplicates or fileHtmlReport != None:
if excludeFromReportIfSignificantTimeDiff and significantTimeDiffCheck(DupFile, DupFileToKeep, True):
stash.Log(f"Skipping duplicate {DupFile['files'][0]['path']} (ID={DupFile['id']}), because of time difference greater than {significantTimeDiff} for file {DupFileToKeep['files'][0]['path']}.")
continue
QtyTagForDel+=1
QtyTagForDelPaginate+=1
didAddTag = False
if tagDuplicates:
didAddTag = setTagId_withRetry(duplicateMarkForDeletion, DupFile, DupFileToKeep, ignoreAutoTag=True)
if fileHtmlReport != None:
# ToDo: Add icons using github path
# add copy button with copy icon
# add move button with r-sqr icon
# repace delete button with trashcan icon
# add rename file code and button
# add delete only from stash db code and button using DB delete icon
stash.Debug(f"Adding scene {DupFile['id']} to HTML report.")
writeRowToHtmlReport(fileHtmlReport, DupFile, DupFileToKeep, QtyTagForDel, tagDuplicates)
DupFile['DupFileToKeep'] = DupFileToKeep['id']
fileDuplicateCandidateForDeletionList.write(json.dumps(DupFile) + "\n")
if QtyTagForDelPaginate >= htmlReportPaginate:
QtyTagForDelPaginate = 0
fileHtmlReport.write("\n")
homeHtmReportLink = f"Home"
prevHtmReportLink = ""
prevRemoteLink = f"Prev"
homeRemoteLink = f"Home"
if PaginateId > 0:
if PaginateId > 1:
prevHtmReport = htmlReportNameHomePage.replace(".html", f"_{PaginateId-1}.html")
else:
prevHtmReport = htmlReportNameHomePage
prevHtmReportLink = f"Prev"
nextHtmReport = htmlReportNameHomePage.replace(".html", f"_{PaginateId+1}.html")
nextHtmReportLink = f"Next"
nextRemoteLink = f"Next"
if PaginateId > 0:
fileHtmlReport.write(f"
")
fileHtmlReport.write(f"{stash.Setting('htmlReportTable')}\n")
if htmlIncludeVideoPreview or htmlIncludeImagePreview:
fileHtmlReport.write(f"{htmlReportTableRow}{SceneTableHeader}Scene{htmlReportTableHeader}Duplicate to Delete{SceneTableHeader}Scene-ToKeep{htmlReportTableHeader}Duplicate to Keep\n")
else:
fileHtmlReport.write(f"{htmlReportTableRow}{htmlReportTableHeader}Duplicate to Delete{htmlReportTableHeader}Duplicate to Keep\n")
if tagDuplicates and graylistTagging and stash.startsWithInList(graylist, DupFile['files'][0]['path']):
stash.addTag(DupFile, graylistMarkForDeletion, ignoreAutoTag=True)
if didAddTag:
QtyNewlyTag+=1
if QtyTagForDel == 1:
stash.Log(f"Tagging duplicate {DupFile['files'][0]['path']} for deletion with tag {duplicateMarkForDeletion}", toAscii=True, printTo=LOG_STASH_N_PLUGIN)
else:
didAddTag = 1 if didAddTag else 0
stash.Log(f"Tagging duplicate {DupFile['files'][0]['path']} for deletion;AddTag={didAddTag};Qty={QtyDup};Set={QtyDupSet} of {qtyResults};NewlyTag={QtyNewlyTag};isTag={QtyTagForDel}", toAscii=True, printTo=LOG_STASH_N_PLUGIN)
stash.Trace(SepLine)
if maxDupToProcess > 0 and ((QtyTagForDel > maxDupToProcess) or (QtyTagForDel == 0 and QtyDup > maxDupToProcess)):
break
fileDuplicateCandidateForDeletionList.close()
if fileHtmlReport != None:
fileHtmlReport.write("\n")
if PaginateId > 0:
homeHtmReportLink = f"Home"
homeRemoteLink = f"Home"
prevRemoteLink = f"Home"
if PaginateId > 1:
prevHtmReport = htmlReportNameHomePage.replace(".html", f"_{PaginateId-1}.html")
else:
prevHtmReport = htmlReportNameHomePage
prevHtmReportLink = f"Prev"
fileHtmlReport.write(f"
{homeHtmReportLink}
{prevHtmReportLink}
")
fileHtmlReport.write(f"
{homeRemoteLink}
{prevRemoteLink}
")
fileHtmlReport.write(f"
Total Tagged for Deletion {QtyTagForDel}
\n")
fileHtmlReport.write(f"{stash.Setting('htmlReportPostfix')}")
fileHtmlReport.close()
if PaginateId == 0:
modifyPropertyToSceneClassToAllFiles("NextPage_Top", "{display:none;}")
stash.Log(f"************************************************************", printTo = stash.LogTo.STASH)
stash.Log(f"************************************************************", printTo = stash.LogTo.STASH)
stash.Log(f"View Stash duplicate report using Stash->Settings->Tools->[Duplicate File Report]", printTo = stash.LogTo.STASH)
stash.Log(f"************************************************************", printTo = stash.LogTo.STASH)
stash.Log(f"************************************************************", printTo = stash.LogTo.STASH)
stash.Debug("#####################################################")
stash.Log(f"QtyDupSet={QtyDupSet}, QtyDup={QtyDup}, QtyDeleted={QtyDeleted}, QtySwap={QtySwap}, QtyTagForDel={QtyTagForDel}, QtySkipForDel={QtySkipForDel}, QtyExcludeForDel={QtyExcludeForDel}, QtyExactDup={QtyExactDup}, QtyAlmostDup={QtyAlmostDup}, QtyMerge={QtyMerge}, QtyRealTimeDiff={QtyRealTimeDiff}", printTo=LOG_STASH_N_PLUGIN)
killScanningJobs()
if cleanAfterDel and deleteDup:
stash.Log("Adding clean jobs to the Task Queue", printTo=LOG_STASH_N_PLUGIN)
stash.metadata_clean()
stash.metadata_clean_generated()
stash.optimise_database()
if doGeneratePhash:
stash.metadata_generate({"phashes": True})
sys.stdout.write("Report complete")
def findCurrentTagId(tagNames):
# tagNames = [i for n, i in enumerate(tagNames) if i not in tagNames[:n]]
for tagName in tagNames:
if tag := stash.find_tag(tagName):
return tag['id'], tagName
return "-1", None
def toJson(data):
# data = data.replace("'", '"')
data = data.replace("\\", "\\\\")
data = data.replace("\\\\\\\\", "\\\\")
return json.loads(data)
def getAnAdvanceMenuOptionSelected(taskName, target, getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater):
stash.Log(f"Processing taskName = {taskName}, target = {target}")
if "Blacklist" in taskName:
tagOrFlag = "Blacklist"
if "Graylist" in taskName:
tagOrFlag = "Graylist"
if "Pinklist" in taskName:
tagOrFlag = "Pinklist"
if "YellowFlag" in taskName:
tagOrFlag = "YellowFlag"
if "GreenFlag" in taskName:
tagOrFlag = "GreenFlag"
if "OrangeFlag" in taskName:
tagOrFlag = "OrangeFlag"
if "CyanFlag" in taskName:
tagOrFlag = "CyanFlag"
if "PinkFlag" in taskName:
tagOrFlag = "PinkFlag"
if "RedFlag" in taskName:
tagOrFlag = "RedFlag"
if "Less" in taskName:
compareToLess = True
if "Greater" in taskName:
compareToGreater = True
if ":TagOnlyScenes" in target:
getTagScenesFromStash = True
target = target.replace(":TagOnlyScenes","")
if "pathToDelete" in taskName:
pathToDelete = target.lower()
elif "sizeToDelete" in taskName:
sizeToDelete = int(target)
elif "durationToDelete" in taskName:
durationToDelete = int(target)
elif "commonResToDelete" in taskName:
resolutionToDelete = int(target)
elif "resolutionToDelete" in taskName:
resolutionToDelete = int(target)
elif "ratingToDelete" in taskName:
ratingToDelete = int(target) * 20
elif "tagToDelete" in taskName:
tagToDelete = target.lower()
elif "titleToDelete" in taskName:
titleToDelete = target.lower()
elif "pathStrToDelete" in taskName:
pathStrToDelete = target.lower()
elif "fileNotExistToDelete" in taskName:
fileNotExistToDelete = True
if target == "Tagged":
getTagScenesFromStash = True
else:
getTagScenesFromStash = False
elif "TagOnlyScenes" in taskName:
getTagScenesFromStash = True
return getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater
def getAdvanceMenuOptionSelected(advanceMenuOptionSelected):
getTagScenesFromStash = False
tagOrFlag = None
pathToDelete = ""
sizeToDelete = -1
durationToDelete = -1
resolutionToDelete = -1
ratingToDelete = -1
tagToDelete = ""
titleToDelete = ""
pathStrToDelete = ""
fileNotExistToDelete = False
compareToLess = False
compareToGreater = False
if advanceMenuOptionSelected:
stash.enableProgressBar(False)
if 'Target' in stash.JSON_INPUT['args']:
if "applyCombo" in stash.PLUGIN_TASK_NAME:
jsonObject = toJson(stash.JSON_INPUT['args']['Target'])
for taskName in jsonObject:
getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater = getAnAdvanceMenuOptionSelected(taskName, jsonObject[taskName], getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater)
else:
return getAnAdvanceMenuOptionSelected(stash.PLUGIN_TASK_NAME, stash.JSON_INPUT['args']['Target'], getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, compareToLess, compareToGreater)
return getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater
def getScenesFromReport():
stash.Log(f"Getting candidates for deletion from file {DuplicateCandidateForDeletionList}.")
scenes = []
lines = None
with open(DuplicateCandidateForDeletionList, 'r') as file:
lines = file.readlines()
for line in lines:
scenes += [json.loads(line)]
return scenes
deleteSceneFlagBgColor = "#646464"
def getFlaggedScenesFromReport(fileName, flagType):
stash.Debug(f"Searching for flag type {flagType} in file {fileName}")
flaggedScenes = []
lines = None
with open(fileName, 'r') as file:
lines = file.readlines()
stash.Trace(f"line count = {len(lines)}")
for line in lines:
if line.startswith(f".ID_") and flagType in line and deleteSceneFlagBgColor not in line:
id = int(line[4:line.index("{")])
stash.Debug(f"Found scene id = {id} with flag {flagType}")
flaggedScenes +=[id]
stash.Trace(f"flaggedScenes count = {len(flaggedScenes)}")
elif line.startswith(""):
if len(flaggedScenes) > 0:
return flaggedScenes
break
stash.Trace(f"Did not find flag {flagType}")
return None
def getFlaggedScenes(flagType=None, ReportName = htmlReportName):
flaggedScenes = []
if flagType == None:
flagType = stash.JSON_INPUT['args']['Target']
if flagType == "green":
flagType = "#00FF00"
else:
if flagType == "YellowFlag":
flagType = "yellow"
if flagType == "GreenFlag":
flagType = "#00FF00"
if flagType == "OrangeFlag":
flagType = "orange"
if flagType == "CyanFlag":
flagType = "cyan"
if flagType == "PinkFlag":
flagType = "pink"
if flagType == "RedFlag":
flagType = "red"
stash.Debug(f"Searching for scenes with flag type {flagType}")
if os.path.isfile(ReportName):
results = getFlaggedScenesFromReport(ReportName,flagType)
if results != None:
flaggedScenes += results
stash.Trace(f"flaggedScenes count = {len(flaggedScenes)}")
for x in range(2, 9999):
fileName = ReportName.replace(".html", f"_{x-1}.html")
stash.Debug(f"Checking if file '{fileName}' exist.")
if not os.path.isfile(fileName):
break
results = getFlaggedScenesFromReport(fileName,flagType)
if results != None:
flaggedScenes += results
stash.Trace(f"flaggedScenes count = {len(flaggedScenes)}")
else:
stash.Log(f"Report file does not exist: {ReportName}")
return flaggedScenes, flagType
# //////////////////////////////////////////////////////////////////////////////
# //////////////////////////////////////////////////////////////////////////////
def manageDuplicatesTaggedOrInReport(deleteScenes=False, clearTag=False, setGrayListTag=False, tagId=-1, advanceMenuOptionSelected=False, checkFlagOption=False, flagColor=None, flagAction=None):
global cleanAfterDel
tagName = None
if tagId == -1:
tagId, tagName = findCurrentTagId([duplicateMarkForDeletion, base1_duplicateMarkForDeletion, base2_duplicateMarkForDeletion, 'DuplicateMarkForDeletion', '_DuplicateMarkForDeletion'])
if int(tagId) < 0:
stash.Warn(f"Could not find tag ID for tag '{duplicateMarkForDeletion}'.")
return
excludedTags = [duplicateMarkForDeletion]
if clearAllDupfileManagerTags:
excludedTags = [duplicateMarkForDeletion, duplicateWhitelistTag, excludeDupFileDeleteTag, graylistMarkForDeletion, longerDurationLowerResolution]
getTagScenesFromStash, tagOrFlag, pathToDelete, sizeToDelete, durationToDelete, resolutionToDelete, ratingToDelete, tagToDelete, titleToDelete, pathStrToDelete, fileNotExistToDelete, compareToLess, compareToGreater = getAdvanceMenuOptionSelected(advanceMenuOptionSelected)
if advanceMenuOptionSelected and deleteScenes and pathToDelete == "" and tagToDelete == "" and titleToDelete == "" and pathStrToDelete == "" and sizeToDelete == -1 and durationToDelete == -1 and resolutionToDelete == -1 and ratingToDelete == -1 and fileNotExistToDelete == False:
stash.Error("Running advance menu option with no options enabled.")
return
flaggedScenes = None
flagType = None
button_property = None
flagActionToLog = flagAction
if flagColor != None:
cleanAfterDel = False
if flagAction == None and deleteScenes == True:
flagActionToLog = "deleteScenes"
stash.Log(f"Processing [Duplicate-to-Delete] scenes with flag color {flagColor} and performing action {flagActionToLog}")
flaggedScenes, flagType = getFlaggedScenes(flagColor)
if stash.isEmpty(flaggedScenes):
stash.Error(f"Early exit, because found no scenes with flag {flagColor}.")
return
elif checkFlagOption or (tagOrFlag != None and "Flag" in tagOrFlag):
if checkFlagOption:
flaggedScenes, flagType = getFlaggedScenes()
else:
checkFlagOption = True
flaggedScenes, flagType = getFlaggedScenes(tagOrFlag)
if stash.isEmpty(flaggedScenes):
stash.Error(f"Early exit, because found no scenes with flag {flagType}.")
return
button_property ="{background-color:" + flagType + ";}"
stash.Debug(f"Fournd {len(flaggedScenes)} scenes with flag {flagType}; button_property={button_property}")
QtyDup = 0
QtyDeleted = 0
QtyClearedTags = 0
QtySetGraylistTag = 0
QtyFailedQuery = 0
stash.Debug("#########################################################################")
stash.startSpinningProcessBar()
if advanceMenuOptionSelected == False and checkFlagOption == False and flagColor == None:
getTagScenesFromStash = True
if getTagScenesFromStash:
stash.Log(f"Getting candidates for deletion by using tag-ID {tagId} and tag-name {tagName}; getTagScenesFromStash={getTagScenesFromStash};advanceMenuOptionSelected={advanceMenuOptionSelected}")
scenes = stash.find_scenes(f={"tags": {"value":tagId, "modifier":"INCLUDES"}}, fragment=fragmentForSceneDetails) # Old setting 'id tags {id name} files {path width height duration size video_codec bit_rate frame_rate} details title rating100')
else:
scenes = getScenesFromReport()
stash.stopSpinningProcessBar()
qtyResults = len(scenes)
if getTagScenesFromStash:
stash.Log(f"Found {qtyResults} scenes with tag ({duplicateMarkForDeletion})")
else:
stash.Log(f"Found {qtyResults} scenes in report")
stash.setProgressBarIter(qtyResults)
for scene in scenes:
QtyDup += 1
stash.progressBar(QtyDup, qtyResults)
# scene = stash.find_scene(sceneID['id'])
# if scene == None or len(scene) == 0:
# stash.Warn(f"Could not get scene data for scene ID {scene['id']}.")
# QtyFailedQuery += 1
# continue
# stash.Trace(f"scene={scene}")
if clearTag:
QtyClearedTags += 1
# ToDo: Add logic to exclude graylistMarkForDeletion
tags = [int(item['id']) for item in scene["tags"] if item['name'] not in excludedTags]
# if clearAllDupfileManagerTags:
# tags = []
# for tag in scene["tags"]:
# if tag['name'] in excludedTags:
# continue
# tags += [int(tag['id'])]
stash.TraceOnce(f"tagId={tagId}, len={len(tags)}, tags = {tags}")
dataDict = {'id' : scene['id']}
if addPrimaryDupPathToDetails:
sceneDetails = scene['details']
if sceneDetails.find(detailPrefix) == 0 and sceneDetails.find(detailPostfix) > 1:
Pos1 = sceneDetails.find(detailPrefix)
Pos2 = sceneDetails.find(detailPostfix)
sceneDetails = sceneDetails[0:Pos1] + sceneDetails[Pos2 + len(detailPostfix):]
dataDict.update({'details' : sceneDetails})
dataDict.update({'tag_ids' : tags})
stash.Log(f"Updating scene with {dataDict};QtyClearedTags={QtyClearedTags};Count={QtyDup} of {qtyResults}")
stash.updateScene(dataDict)
# stash.removeTag(scene, duplicateMarkForDeletion)
elif setGrayListTag:
if stash.startsWithInList(graylist, scene['files'][0]['path']):
QtySetGraylistTag+=1
if stash.addTag(scene, graylistMarkForDeletion, ignoreAutoTag=True):
stash.Log(f"Added tag {graylistMarkForDeletion} to scene {scene['files'][0]['path']};QtySetGraylistTag={QtySetGraylistTag};Count={QtyDup} of {qtyResults}")
else:
stash.Trace(f"Scene already had tag {graylistMarkForDeletion}; {scene['files'][0]['path']}")
elif flagAction != None:
if int(scene['id']) in flaggedScenes:
stash.Log(f"Found {flagType} flagged candidate for {flagAction}; Scene ID = {scene['id']}")
else:
continue
if flagAction == "addExcludeTag":
stash.addTag(scene['id'], excludeDupFileDeleteTag)
stash.Log(f"Done adding exclude tag to scene {scene['id']}.")
elif flagAction == "copyScene" or flagAction == "moveScene":
copyScene(flagAction == "moveScene", scene)
elif flagAction == "mergeScene":
mergeTags(scene)
else:
stash.Error(f"flagAction not recognized. flagAction={flagAction}")
elif deleteScenes:
DupFileName = scene['files'][0]['path']
DupFileNameOnly = pathlib.Path(DupFileName).stem
if flagColor != None or (checkFlagOption and (tagOrFlag == None or "Flag" not in tagOrFlag)):
if int(scene['id']) in flaggedScenes:
stash.Log(f"Found {flagType} flagged candidate for deletion; Scene ID = {scene['id']}")
else:
continue
elif advanceMenuOptionSelected:
if checkFlagOption:
if int(scene['id']) in flaggedScenes:
stash.Trace(f"Found {flagType} flag for Scene ID = {scene['id']}")
else:
continue
if tagOrFlag == "Blacklist":
if not stash.startsWithInList(blacklist, scene['files'][0]['path']):
continue
if tagOrFlag == "Graylist":
if not stash.startsWithInList(graylist, scene['files'][0]['path']):
continue
if tagOrFlag == "Pinklist":
if not stash.startsWithInList(pinklist, scene['files'][0]['path']):
continue
if pathToDelete != "":
if not DupFileName.lower().startswith(pathToDelete):
stash.Debug(f"Skipping file {DupFileName} because it does not start with {pathToDelete}.")
continue
if pathStrToDelete != "":
if not pathStrToDelete in DupFileName.lower():
stash.Debug(f"Skipping file {DupFileName} because it does not contain value {pathStrToDelete}.")
continue
if sizeToDelete != -1:
compareTo = int(scene['files'][0]['size'])
if compareToLess:
if not (compareTo < sizeToDelete):
continue
elif compareToGreater:
if not (compareTo > sizeToDelete):
continue
else:
if not compareTo == sizeToDelete:
continue
if durationToDelete != -1:
compareTo = int(scene['files'][0]['duration'])
if compareToLess:
if not (compareTo < durationToDelete):
continue
elif compareToGreater:
if not (compareTo > durationToDelete):
continue
else:
if not compareTo == durationToDelete:
continue
if resolutionToDelete != -1:
compareTo = int(scene['files'][0]['width']) * int(scene['files'][0]['height'])
if compareToLess:
if not (compareTo < resolutionToDelete):
continue
elif compareToGreater:
if not (compareTo > resolutionToDelete):
continue
else:
if not compareTo == resolutionToDelete:
continue
if ratingToDelete != -1:
if scene['rating100'] == "None":
compareTo = 0
else:
compareTo = int(scene['rating100'])
if compareToLess:
if not (compareTo < resolutionToDelete):
continue
elif compareToGreater:
if not (compareTo > resolutionToDelete):
continue
else:
if not compareTo == resolutionToDelete:
continue
if titleToDelete != "":
if not titleToDelete in scene['title'].lower():
stash.Debug(f"Skipping file {DupFileName} because it does not contain value {titleToDelete} in title ({scene['title']}).")
continue
if tagToDelete != "":
doProcessThis = False
for tag in scene['tags']:
if tag['name'].lower() == tagToDelete:
doProcessThis = True
break
if doProcessThis == False:
continue
if fileNotExistToDelete:
if os.path.isfile(scene['files'][0]['path']):
continue
stash.Log(f"Deleting duplicate '{DupFileName}'", toAscii=True, printTo=LOG_STASH_N_PLUGIN)
if alternateTrashCanPath != "":
destPath = f"{alternateTrashCanPath }{os.sep}{DupFileNameOnly}"
if os.path.isfile(destPath):
destPath = f"{alternateTrashCanPath }{os.sep}_{time.time()}_{DupFileNameOnly}"
shutil.move(DupFileName, destPath)
elif moveToTrashCan:
sendToTrash(DupFileName)
result = deleteScene(scene=scene['id'], deleteFile=True, writeToStdOut=False, button_property=button_property)
QtyDeleted += 1
stash.Debug(f"destroyScene result={result} for file {DupFileName};QtyDeleted={QtyDeleted};Count={QtyDup} of {qtyResults}", toAscii=True)
else:
stash.Error("manageDuplicatesTaggedOrInReport called with invlaid input arguments. Doing early exit.")
return
stash.Debug("#####################################################")
stash.Log(f"QtyDup={QtyDup}, QtyClearedTags={QtyClearedTags}, QtySetGraylistTag={QtySetGraylistTag}, QtyDeleted={QtyDeleted}, QtyFailedQuery={QtyFailedQuery}", printTo=LOG_STASH_N_PLUGIN)
killScanningJobs()
if deleteScenes and not advanceMenuOptionSelected:
if cleanAfterDel:
stash.Log("Adding clean jobs to the Task Queue", printTo=LOG_STASH_N_PLUGIN)
stash.metadata_clean()
stash.metadata_clean_generated()
stash.optimise_database()
def removeDupTag():
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return
scene = stash.JSON_INPUT['args']['Target']
stash.Log(f"Processing scene ID# {scene}")
stash.removeTag(scene, duplicateMarkForDeletion)
stash.Log(f"Done removing tag from scene {scene}.")
jsonReturn = "{'removeDupTag' : 'complete', 'id': '" + f"{scene}" + "'}"
stash.Log(f"Sending json value {jsonReturn}")
sys.stdout.write(jsonReturn)
def addExcludeTag():
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return
scene = stash.JSON_INPUT['args']['Target']
stash.Log(f"Processing scene ID# {scene}")
stash.addTag(scene, excludeDupFileDeleteTag)
stash.Log(f"Done adding exclude tag to scene {scene}.")
sys.stdout.write("{" + f"addExcludeTag : 'complete', id: '{scene}'" + "}")
def removeExcludeTag():
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return
scene = stash.JSON_INPUT['args']['Target']
stash.Log(f"Processing scene ID# {scene}")
stash.removeTag(scene, excludeDupFileDeleteTag)
stash.Log(f"Done removing exclude tag from scene {scene}.")
sys.stdout.write("{" + f"removeExcludeTag : 'complete', id: '{scene}'" + "}")
def getParseData(getSceneDetails1=True, getSceneDetails2=True, checkIfNotSplitValue=False):
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return None, None
targetsSrc = stash.JSON_INPUT['args']['Target']
if checkIfNotSplitValue and ":" not in targetsSrc:
return targetsSrc, None
targets = targetsSrc.split(":")
if len(targets) < 2:
stash.Error(f"Could not get both targets from string {targetsSrc}")
return None, None
stash.Log(f"Parsed targets {targets[0]} and {targets[1]}")
target1 = targets[0]
target2 = targets[1]
if getSceneDetails1:
target1 = stash.find_scene(int(target1))
if getSceneDetails2:
target2 = stash.find_scene(int(target2))
elif len(targets) > 2:
target2 = target2 + targets[2]
return target1, target2
def mergeMetadataInThisFile(fileName):
stash.Debug(f"Checking report file '{fileName}' for yellow icons indicating missing metadata in DuplicateToKeep.")
lines = None
with open(fileName, 'r') as file:
lines = file.readlines()
for line in lines:
if "https://www.axter.com/images/stash/Yellow" in line: # FYI: This catches YellowGroup.png as well, even though group is not currently supported for merging
idx = line.index(ToDeleteSceneIDSrchStr) + len(ToDeleteSceneIDSrchStr)
scene_id1 = line[idx:]
scene_id1 = scene_id1[:scene_id1.index('::')]
idx = line.index(ToKeepSceneIDSrchStr, idx) + len(ToKeepSceneIDSrchStr)
scene_id2 = line[idx:]
scene_id2 = scene_id2[:scene_id2.index('::')]
stash.Log(f"From file {fileName}, merging metadata from scene {scene_id1} to scene {scene_id2}")
stash.mergeMetadata(int(scene_id1), int(scene_id2))
updateScenesInReports(scene_id2)
def mergeMetadataForAll(ReportName = htmlReportName):
if os.path.isfile(ReportName):
mergeMetadataInThisFile(ReportName)
for x in range(2, 9999):
fileName = ReportName.replace(".html", f"_{x-1}.html")
stash.Debug(f"Checking if file '{fileName}' exist.")
if not os.path.isfile(fileName):
break
mergeMetadataInThisFile(fileName)
stash.Log(f"Done merging metadata for all scenes")
sys.stdout.write("{mergeTags : 'complete'}")
# ToDo: Rename mergeTags to mergeMetadata
def mergeTags(inputScene1=None):
if inputScene1 == None:
scene1, scene2 = getParseData(checkIfNotSplitValue=True)
if scene1 == None or scene2 == None:
if scene1 == "mergeMetadataForAll":
mergeMetadataForAll()
else:
sys.stdout.write("{" + f"mergeTags : 'failed', id1: '{scene1}', id2: '{scene2}'" + "}")
return
else:
scene1 = inputScene1
scene2 = stash.find_scene(int(inputScene1['DupFileToKeep']))
stash.mergeMetadata(scene1, scene2)
updateScenesInReports(scene2['id'])
stash.Log(f"Done merging scenes for scene {scene1['id']} and scene {scene2['id']}")
if inputScene1 == None:
sys.stdout.write("{" + f"mergeTags : 'complete', id1: '{scene1['id']}', id2: '{scene2['id']}'" + "}")
def getLocalDupReportPath():
htmlReportExist = "true" if os.path.isfile(htmlReportName) else "false"
localPath = htmlReportName.replace("\\", "\\\\")
LocalDir = htmlReportNameFolder.replace("\\", "\\\\")
ReportUrl = f"file://{htmlReportName.replace(os.sep, '/')}"
AdvMenuUrl = f"file://{stash.PLUGINS_PATH.replace(os.sep, '/')}/DupFileManager/advance_options.html"
ReportUrlDir = f"file://{htmlReportNameFolder.replace(os.sep, '/')}"
apikey_json = ", 'apiKey':''"
if 'apiKey' in stash.STASH_CONFIGURATION:
apikey_json = f", 'apiKey':'{stash.STASH_CONFIGURATION['apiKey']}'"
jsonReturn = "{" + f"'LocalDupReportExist' : {htmlReportExist}, 'Path': '{localPath}', 'LocalDir': '{LocalDir}', 'ReportUrlDir': '{ReportUrlDir}', 'ReportUrl': '{ReportUrl}', 'AdvMenuUrl': '{AdvMenuUrl}', 'IS_DOCKER': '{stash.IS_DOCKER}', 'remoteReportDirURL': '{stash.Setting('remoteReportDirURL')}' {apikey_json}" + "}"
stash.Log(f"Sending json value {jsonReturn}")
sys.stdout.write(jsonReturn)
def deleteLocalDupReportHtmlFiles(doJsonOutput = True):
htmlReportExist = "true" if os.path.isfile(htmlReportName) else "false"
if os.path.isfile(htmlReportName):
stash.Log(f"Deleting file {htmlReportName}")
os.remove(htmlReportName)
for x in range(2, 9999):
fileName = htmlReportName.replace(".html", f"_{x-1}.html")
stash.Debug(f"Checking if file '{fileName}' exist.")
if not os.path.isfile(fileName):
break
stash.Log(f"Deleting file {fileName}")
os.remove(fileName)
else:
stash.Log(f"Report file does not exist: {htmlReportName}")
if doJsonOutput:
jsonReturn = "{'LocalDupReportExist' : " + f"{htmlReportExist}" + ", 'Path': '" + f"{htmlReportName}" + "', 'qty': '" + f"{x}" + "'}"
stash.Log(f"Sending json value {jsonReturn}")
sys.stdout.write(jsonReturn)
def removeTagFromAllScenes(tagName, deleteTags):
if tag := stash.find_tag(tagName):
if deleteTags:
stash.Debug(f"Deleting tag name {tagName} with Tag ID {tag['id']} from stash.")
stash.destroy_tag(int(tag['id']))
else:
stash.Debug(f"Removing tag name {tagName} with Tag ID {tag['id']} from all scenes.")
if stash.isCorrectDbVersion() and stash.removeTagFromAllScenes(tagID=int(tag['id'])):
stash.Log(f"Removed tag name {tagName} using SQL.")
else:
manageDuplicatesTaggedOrInReport(clearTag=True, tagId=int(tag['id']))
return True
stash.Warn(f"Could not find tag name {tagName}")
return False
def removeAllDupTagsFromAllScenes(deleteTags=False):
tagsToClear = [duplicateMarkForDeletion, base1_duplicateMarkForDeletion, base2_duplicateMarkForDeletion, graylistMarkForDeletion, longerDurationLowerResolution, duplicateWhitelistTag]
for x in range(0, 3):
tagsToClear += [base1_duplicateMarkForDeletion + f"_{x}"]
for x in range(0, 3):
tagsToClear += [base2_duplicateMarkForDeletion + f"_{x}"]
tagsToClear = list(set(tagsToClear)) # Remove duplicates
validTags = []
for tagToClear in tagsToClear:
if removeTagFromAllScenes(tagToClear, deleteTags):
validTags +=[tagToClear]
if doJsonReturn:
jsonReturn = "{'removeAllDupTagFromAllScenes' : " + f"{duplicateMarkForDeletion}" + ", 'OtherTags': '" + f"{validTags}" + "'}"
stash.Log(f"Sending json value {jsonReturn}")
sys.stdout.write(jsonReturn)
else:
stash.Log(f"Clear tags {tagsToClear}")
def updateDuplicateCandidateForDeletionList(scene, removeScene = False):
lines = None
scene_id = None
if not os.path.isfile(DuplicateCandidateForDeletionList):
return
with open(DuplicateCandidateForDeletionList, 'r') as file:
lines = file.readlines()
if removeScene:
scene_id = scene
else:
scene_id = scene['id']
stash.Trace(f"Trying to update scene ID {scene_id} in file {DuplicateCandidateForDeletionList}.")
foundScene = False
with open(DuplicateCandidateForDeletionList, 'w') as file:
for line in lines:
if foundScene:
file.write(line)
else:
sceneDetails = json.loads(line)
if sceneDetails['id'] == scene_id:
if not removeScene:
file.write(json.dumps(scene) + "\n")
foundScene = True
else:
file.write(line)
if foundScene:
stash.Debug(f"Found and updated scene ID {scene_id} in file {DuplicateCandidateForDeletionList}.")
else:
stash.Debug(f"Did not find scene ID {scene_id} in file {DuplicateCandidateForDeletionList}.")
def getItemIndex(line):
idx = line.find(itemIndexSrchStr) + len(itemIndexSrchStr)
if idx > len(itemIndexSrchStr):
itemIndex = line[idx:]
itemIndex = itemIndex[:itemIndex.index('::')]
return itemIndex
return "??"
def updateScenesInReport(fileName, scene):
stash.Log(f"Updating table rows with scene {scene} in file {fileName}")
results = False
scene1 = -1
scene2 = -1
strToFind = "class=\"ID_"
lines = None
sceneDetails_ToUpdate = []
Duplicates_ToDelete = []
with open(fileName, 'r') as file:
lines = file.readlines()
stash.Log(f"line count = {len(lines)}")
stash.Log(f"Searching for class=\"ID_{scene}\"")
with open(fileName, 'w') as file:
for line in lines:
# stash.Debug(f"line = {line}")
if f"class=\"ID_{scene}\"" in line:
stash.Debug(f"Found class ID_{scene} in line: {line}")
idx = 0
while line.find(strToFind, idx) > -1:
idx = line.find(strToFind, idx) + len(strToFind)
id = line[idx:]
stash.Debug(f"id = {id}, idx = {idx}")
id = stash.getNum(id[:id.find('"')])
stash.Debug(f"id = {id}")
if scene1 == -1:
scene1 = int(id)
elif scene1 != int(id) and scene2 == -1:
scene2 = int(id)
elif scene1 != -1 and scene2 != -1:
break
if scene1 != -1 and scene2 != -1:
sceneDetails1 = stash.find_scene(scene1, fragment=fragmentForSceneDetails)
sceneDetails2 = stash.find_scene(scene2, fragment=fragmentForSceneDetails)
if sceneDetails1 == None or sceneDetails2 == None:
stash.Error(f"Could not get scene details for both scene1 ({scene1}) and scene2 ({scene2}); sceneDetails1={sceneDetails1}; sceneDetails2={sceneDetails2};")
else:
if sceneDetails1['id'] in Duplicates_ToDelete:
stash.Warn(f"Found Duplicates_ToDelete ID {sceneDetails1['id']} more than once for line {line}")
else:
Duplicates_ToDelete += [sceneDetails1['id']]
stash.Log(f"Updating in report {fileName} scene {scene1} and scene {scene2}")
writeRowToHtmlReport(file, sceneDetails1, sceneDetails2, getItemIndex(line), doTraceDetails=True)
if scene == sceneDetails1['id']:
results = True
sceneDetails_ToUpdate += [sceneDetails1]
else:
stash.Error(f"Could not get both scene ID associated with scene {scene}; scene1 = {scene1}; scene2 = {scene2}")
file.write(line)
else:
file.write(line)
if scene1 == -1 or scene2 == -1:
stash.Log(f"Did not find both scene ID's associated with scene {scene}; scene1 = {scene1}; scene2 = {scene2}")
else:
for sceneDetails in sceneDetails_ToUpdate:
updateDuplicateCandidateForDeletionList(sceneDetails)
return results
def updateScenesInReports(scene, ReportName = htmlReportName):
if os.path.isfile(ReportName):
if updateScenesInReport(ReportName, scene):
return
for x in range(2, 9999):
fileName = ReportName.replace(".html", f"_{x-1}.html")
stash.Debug(f"Checking if file '{fileName}' exist.")
if not os.path.isfile(fileName):
break
if updateScenesInReport(fileName, scene):
break
stash.Debug("updateScenesInReports complete")
else:
stash.Log(f"Report file does not exist: {ReportName}")
def modifyPropertyToSceneClass(fileName, scene, property, button_property):
stash.Debug(f"Inserting property {property} for scene {scene} in file {fileName}")
doStyleEndTagCheck = True
lines = None
with open(fileName, 'r') as file:
lines = file.readlines()
stash.Debug(f"line count = {len(lines)}")
with open(fileName, 'w') as file:
for line in lines:
# stash.Debug(f"line = {line}")
if doStyleEndTagCheck:
if scene == None:
if line.startswith(f".ID_") and deleteSceneFlagBgColor not in line:
if property == None:
continue
if property in line:
continue
elif line.startswith(""):
doStyleEndTagCheck = False
else:
if property == "remove highlight" and line.startswith(f".ID_{scene}" + "{") and deleteSceneFlagBgColor not in line and "background-color" in line:
continue
if property == "" and line.startswith(f".ID_{scene}" + "{"):
continue
if line.startswith(""):
if property != "" and property != "remove highlight":
styleSetting = f".ID_{scene}{property}\n"
stash.Debug(f"styleSetting = {styleSetting}")
file.write(styleSetting)
if button_property != None:
styleSetting = f".Btn-ID-{scene}{button_property}\n"
stash.Trace(f"Button styleSetting = {styleSetting}")
file.write(styleSetting)
elif deleteSceneFlagBgColor in property:
styleSetting = f".Btn-ID-{scene}{property}\n"
stash.Trace(f"Button styleSetting = {styleSetting}")
file.write(styleSetting)
doStyleEndTagCheck = False
file.write(line)
def modifyPropertyToSceneClassToAllFiles(scene, property, button_property = None, ReportName = htmlReportName):
if os.path.isfile(ReportName):
modifyPropertyToSceneClass(ReportName, scene, property, button_property)
for x in range(2, 9999):
fileName = ReportName.replace(".html", f"_{x-1}.html")
stash.Debug(f"Checking if file '{fileName}' exist.")
if not os.path.isfile(fileName):
break
modifyPropertyToSceneClass(fileName, scene, property, button_property)
else:
stash.Log(f"Report file does not exist: {ReportName}")
def deleteScene(disableInReport=True, deleteFile=True, scene=None, writeToStdOut=True, button_property = None): # Scene ID
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return
if scene == None:
scene = stash.JSON_INPUT['args']['Target']
stash.Log(f"Processing scene ID# {scene}")
if dry_run:
result = f"dry_run enabled, but scene {scene} would have been removed from stash with delete_file={deleteFile}."
stash.Log(result)
else:
result = stash.destroyScene(scene, delete_file=deleteFile)
if disableInReport:
modifyPropertyToSceneClassToAllFiles(scene, "remove highlight")
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:" + deleteSceneFlagBgColor + ";pointer-events:none;}", button_property)
updateDuplicateCandidateForDeletionList(scene, removeScene = True)
modifyPropertyToSceneClassToAllFiles(f"{scene}_preview", "{display:none;}")
if writeToStdOut:
stash.Log(f"{stash.PLUGIN_TASK_NAME} complete for scene {scene} with results = {result}")
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'complete', id: '{scene}', result: '{result}'" + "}")
return result
def clearAllSceneFlags(flagColor=None):
modifyPropertyToSceneClassToAllFiles(None, flagColor)
stash.Log(f"{stash.PLUGIN_TASK_NAME} complete for all scenes")
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'complete'" + "}")
def copyScene(moveScene=False, inputScene1=None):
if inputScene1 == None:
scene1, scene2 = getParseData()
if scene1 == None or scene2 == None:
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'failed', id1: '{scene1}', id2: '{scene2}'" + "}")
return
else:
scene1 = inputScene1
scene2 = stash.find_scene(int(inputScene1['DupFileToKeep']))
actionStr = "copyScene"
if moveScene:
stash.mergeMetadata(scene1, scene2)
actionStr = "moveScene"
stash.Debug(f"Coping file {scene1['files'][0]['path']} to {scene2['files'][0]['path']}")
result = shutil.copy(scene1['files'][0]['path'], scene2['files'][0]['path'])
result += stash.updateFileScene(scene2['files'][0]['path'])
if moveScene:
if dry_run:
result = f"dry_run enabled, but scene {scene1['files'][0]['path']} would have been removed from stash with delete_file=True."
stash.Log(result)
else:
result = stash.destroyScene(scene1['id'], delete_file=True)
updateDuplicateCandidateForDeletionList(scene1['id'], removeScene = True)
stash.Log(f"destroyScene for scene {scene1['id']} results = {result}")
# Need a few seconds delay to make sure stash has updated database after calling updateFileScene
time.sleep(2)
updateScenesInReports(scene2['id'])
stash.Log(f"{actionStr} complete for scene {scene1['id']} and {scene2['id']}")
if inputScene1 == None:
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'complete', id1: '{scene1['id']}', id2: '{scene2['id']}', result: '{result}'" + "}")
def renameFile():
scene, newName = getParseData(getSceneDetails2=False)
if scene == None or newName == None:
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'failed', scene: '{scene}', newName: '{newName}'" + "}")
return
newName = newName.strip("'")
ext = pathlib.Path(scene['files'][0]['path']).suffix
newNameFull = f"{pathlib.Path(scene['files'][0]['path']).resolve().parent}{os.sep}{newName}{ext}"
newNameFull = newNameFull.strip("'")
newNameFull = newNameFull.replace("\\\\", "\\")
oldNameFull = scene['files'][0]['path']
oldNameFull = oldNameFull.strip("'")
oldNameFull = oldNameFull.replace("\\\\", "\\")
stash.Log(f"renaming file '{stash.asc2(oldNameFull)}' to '{stash.asc2(newNameFull)}'")
result = os.rename(oldNameFull, newNameFull)
stash.renameFileNameInDB(scene['files'][0]['id'], pathlib.Path(oldNameFull).stem, f"{newName}{ext}", UpdateUsingIdOnly = True)
updateScenesInReports(scene['id'])
stash.Log(f"{stash.PLUGIN_TASK_NAME} complete for scene {scene['id']} ;renamed to {newName}; result={result}")
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'complete', scene: '{scene['id']}', newName: '{newName}', result: '{result}'" + "}")
def flagScene():
scene, flagType = getParseData(False, False)
if scene == None or flagType == None:
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'failed', scene: '{scene}', flagType: '{flagType}'" + "}")
return
if " highlight" in flagType:
modifyPropertyToSceneClassToAllFiles(scene, "remove highlight")
if flagType == "disable-scene":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:gray;pointer-events:none;}")
elif flagType == "strike-through":
modifyPropertyToSceneClassToAllFiles(scene, "{text-decoration: line-through;}")
elif flagType == "yellow highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:yellow;}")
elif flagType == "green highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:#00FF00;}")
elif flagType == "orange highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:orange;}")
elif flagType == "cyan highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:cyan;}")
elif flagType == "pink highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:pink;}")
elif flagType == "red highlight":
modifyPropertyToSceneClassToAllFiles(scene, "{background-color:red;}")
elif flagType == "remove all flags":
modifyPropertyToSceneClassToAllFiles(scene, "")
else:
stash.Log(f"Invalid flagType ({flagType})")
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'failed', scene: '{scene}', flagType: '{flagType}'" + "}")
return
sys.stdout.write("{" + f"{stash.PLUGIN_TASK_NAME} : 'complete', scene: '{scene}', flagType: '{flagType}'" + "}")
def getReport():
if 'Target' not in stash.JSON_INPUT['args']:
stash.Error(f"Could not find Target in JSON_INPUT ({stash.JSON_INPUT['args']})")
return
PageNo = int(stash.JSON_INPUT['args']['Target'])
fileName = htmlReportName
if PageNo > 0:
fileName = fileName.replace(".html", f"_{PageNo}.html")
lines = None
stash.Log(f"Getting file {fileName}")
with open(fileName, 'r') as file:
lines = file.read()
if PageNo > 0 or lines.find(".ID_NextPage_Top{display:none;}") == -1:
lines = lines.replace("#ID_NextPage_Top_Remote{display:none;}", ".ID_NextPage_Top{display:none;}")
lines = lines.replace("#ID_NextPage_Bottom_Remote{display:none;}", "#ID_NextPage_Bottom{display:none;}")
# strToSrch = ""
# pos = lines.find(strToSrch)
# if pos > -1:
# lines = lines[pos + len(strToSrch):]
sys.stdout.write(lines)
stash.Log(f"Done getting file {fileName}.")
def getAdvanceMenu():
fileName = f"{DupFileManagerFolder}{os.sep}advance_options.html"
lines = None
stash.Log(f"Getting file {fileName}")
with open(fileName, 'r') as file:
lines = file.read()
sys.stdout.write(lines)
stash.Log(f"Done getting file {fileName}.")
# ToDo: Add to UI menu
# Remove all Dup tagged files (Just remove from stash, and leave file)
# Clear GraylistMarkForDel tag
# Delete GraylistMarkForDel tag
# Remove from stash all files no longer part of stash library
# Remove from stash all files in the Exclusion list (Not supporting regexps)
# ToDo: Add to advance menu
# Remove only graylist dup
# Exclude graylist from delete
# Include graylist in delete
taskName_deleteScene = "deleteScene"
taskName_copyScene = "copyScene"
taskName_moveScene = "moveScene"
taskName_mergeScene = "mergeScene"
taskName_addExcludeTag = "addExcludeTag"
taskName_clearFlag = "clearFlag"
try:
if stash.PLUGIN_TASK_NAME == "tag_duplicates_task":
mangeDupFiles(tagDuplicates=True, merge=mergeDupFilename)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "create_duplicate_report_task":
mangeDupFiles(tagDuplicates=False, merge=mergeDupFilename)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "delete_tagged_duplicates_task":
manageDuplicatesTaggedOrInReport(deleteScenes=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "delete_duplicates_task":
mangeDupFiles(deleteDup=True, merge=mergeDupFilename)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "clear_duplicate_tags_task":
removeAllDupTagsFromAllScenes()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "graylist_tag_task":
manageDuplicatesTaggedOrInReport(setGrayListTag=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "generate_phash_task":
stash.metadata_generate({"phashes": True})
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "getReport":
getReport()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "getAdvanceMenu":
getAdvanceMenu()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteScene":
deleteScene()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith("deleteScene"):
manageDuplicatesTaggedOrInReport(deleteScenes=True, checkFlagOption=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "removeScene":
deleteScene(deleteFile=False)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "renameFile":
renameFile()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "flagScene":
flagScene()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "clearAllSceneFlags":
clearAllSceneFlags()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "copyScene":
copyScene()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "moveScene":
copyScene(moveScene=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "removeDupTag":
removeDupTag()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "addExcludeTag":
addExcludeTag()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_deleteScene):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_deleteScene):]
manageDuplicatesTaggedOrInReport(deleteScenes=True, flagColor=flagColor)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_copyScene):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_copyScene):]
manageDuplicatesTaggedOrInReport(flagColor=flagColor, flagAction=taskName_copyScene)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_moveScene):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_moveScene):]
manageDuplicatesTaggedOrInReport(flagColor=flagColor, flagAction=taskName_moveScene)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_mergeScene):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_mergeScene):]
manageDuplicatesTaggedOrInReport(flagColor=flagColor, flagAction=taskName_mergeScene)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_addExcludeTag):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_addExcludeTag):]
manageDuplicatesTaggedOrInReport(flagColor=flagColor, flagAction=taskName_addExcludeTag)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME.startswith(taskName_clearFlag):
flagColor = stash.PLUGIN_TASK_NAME[len(taskName_clearFlag):]
flagColor = flagColor.replace("Flag", "").lower()
if flagColor == "green":
flagColor = "#00FF00"
flagColor = f"background-color:{flagColor};"
stash.Debug(f"{stash.PLUGIN_TASK_NAME} task called with flag color {flagColor}")
clearAllSceneFlags(flagColor)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "removeExcludeTag":
removeExcludeTag()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "mergeTags":
mergeTags()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "getLocalDupReportPath":
getLocalDupReportPath()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteLocalDupReportHtmlFiles":
deleteLocalDupReportHtmlFiles()
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "createDuplicateReportWithoutTagging":
mangeDupFiles(tagDuplicates=False, merge=mergeDupFilename)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteAllDupFileManagerTags":
removeAllDupTagsFromAllScenes(deleteTags=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteBlackListTaggedDuplicatesTask":
mangeDupFiles(deleteDup=True, merge=mergeDupFilename, deleteBlacklistOnly=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteTaggedDuplicatesLwrResOrLwrDuration":
mangeDupFiles(deleteDup=True, merge=mergeDupFilename, deleteLowerResAndDuration=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif stash.PLUGIN_TASK_NAME == "deleteBlackListTaggedDuplicatesLwrResOrLwrDuration":
mangeDupFiles(deleteDup=True, merge=mergeDupFilename, deleteBlacklistOnly=True, deleteLowerResAndDuration=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
elif parse_args.dup_tag:
stash.PLUGIN_TASK_NAME = "dup_tag"
mangeDupFiles(tagDuplicates=True, merge=mergeDupFilename)
stash.Debug(f"Tag duplicate EXIT")
elif parse_args.del_tag:
stash.PLUGIN_TASK_NAME = "del_tag"
manageDuplicatesTaggedOrInReport(deleteScenes=True)
stash.Debug(f"Delete Tagged duplicates EXIT")
elif parse_args.clear_tag:
stash.PLUGIN_TASK_NAME = "clear_tag"
removeAllDupTagsFromAllScenes()
stash.Debug(f"Clear duplicate tags EXIT")
elif parse_args.remove:
stash.PLUGIN_TASK_NAME = "remove"
mangeDupFiles(deleteDup=True, merge=mergeDupFilename)
stash.Debug(f"Delete duplicate EXIT")
elif len(sys.argv) < 2 and stash.PLUGIN_TASK_NAME in advanceMenuOptions:
manageDuplicatesTaggedOrInReport(deleteScenes=True, advanceMenuOptionSelected=True)
stash.Debug(f"{stash.PLUGIN_TASK_NAME} EXIT")
else:
stash.Error(f"Invalid task name {stash.PLUGIN_TASK_NAME};")
stash.Log(f"Error: Nothing to do!!! (PLUGIN_ARGS_MODE={stash.PLUGIN_TASK_NAME})")
except Exception as e:
tb = traceback.format_exc()
stash.Error(f"Exception while running DupFileManager Task({stash.PLUGIN_TASK_NAME}); Error: {e}\nTraceBack={tb}")
killScanningJobs()
stash.convertToAscii = False
stash.Error(f"Error: {e}\nTraceBack={tb}")
if doJsonReturn:
sys.stdout.write("{" + f"Exception : '{e}; See log file for TraceBack' " + "}")
stash.Log("\n*********************************\nEXITING ***********************\n*********************************")