Skip to content

Commit e19dc42

Browse files
authored
Merge pull request #1 from philipturner/file-name-too-long
Add patch for Swift pathway too
2 parents 9057bee + 2851a0d commit e19dc42

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

swift/StableDiffusionCLI/main.swift

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,22 @@ struct StableDiffusionSample: ParsableCommand {
127127
}
128128

129129
let name = imageName(i, step: step)
130-
let fileURL = url.appending(path:name)
130+
var fileURL = url.appending(path: name)
131+
132+
// Don't throw an error when the file path exceeds 255 characters.
133+
// This is important for excessively long prompts, where you might
134+
// run the model only to realize that it failed to save.
135+
if fileURL.absoluteString.count > 255 {
136+
log("WARNING: Image file path was shortened to 255 characters. This may unintentionally overwrite similarly named files. Original path: '\(fileURL.absoluteString)'\n")
137+
let numExcessiveCharacters = fileURL.absoluteString.count - 255
138+
139+
let fileExtensionLength = String(".png").count
140+
guard name.count >= numExcessiveCharacters + fileExtensionLength else {
141+
throw RunError.saving("Directory path length was too large, possibly exceeding 255 characters.")
142+
}
143+
let shortenedName = imageName(i, step: step, truncatedLength: numExcessiveCharacters)
144+
fileURL = url.appending(path: shortenedName)
145+
}
131146

132147
guard let dest = CGImageDestinationCreateWithURL(fileURL as CFURL, UTType.png.identifier as CFString, 1, nil) else {
133148
throw RunError.saving("Failed to create destination for \(fileURL)")
@@ -144,19 +159,19 @@ struct StableDiffusionSample: ParsableCommand {
144159
return saved
145160
}
146161

147-
func imageName(_ sample: Int, step: Int? = nil) -> String {
162+
func imageName(_ sample: Int, step: Int? = nil, truncatedLength: Int = 0) -> String {
148163
var name = prompt.replacingOccurrences(of: " ", with: "_")
149164
if imageCount != 1 {
150165
name += ".\(sample)"
151166
}
152-
153167
name += ".\(seed)"
154168

155169
if let step = step {
156170
name += ".\(step)"
157171
} else {
158172
name += ".final"
159173
}
174+
name.removeLast(truncatedLength)
160175
name += ".png"
161176
return name
162177
}

0 commit comments

Comments
 (0)