Skip to content
This repository was archived by the owner on Apr 23, 2025. It is now read-only.

Commit f4855d6

Browse files
authored
Use stderr for logging messages (#228)
* Use stderr for logging messages * Rename printerr into printError
1 parent 250f0a4 commit f4855d6

File tree

6 files changed

+44
-25
lines changed

6 files changed

+44
-25
lines changed

Benchmarks/main.swift

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
import Commander
16+
import ModelSupport
1617

1718
func runBenchmark(
1819
_ name: String,
@@ -42,8 +43,8 @@ func runBenchmark(
4243
benchmark: bench,
4344
callback: logResults)
4445
} else {
45-
print("No registered inference benchmark with a name: \(name)")
46-
print("Consider running `list` command to see all available benchmarks.")
46+
printError("No registered inference benchmark with a name: \(name)")
47+
printError("Consider running `list` command to see all available benchmarks.")
4748
}
4849
}
4950

@@ -98,11 +99,11 @@ let main =
9899
iterations: iterations,
99100
epochs: epochs)
100101
if !trainingFlag && !inferenceFlag {
101-
print("Must specify either --training xor --inference benchmark variety.")
102+
printError("Must specify either --training xor --inference benchmark variety.")
102103
} else if trainingFlag && inferenceFlag {
103-
print("Can't specify both --training and --inference benchmark variety.")
104+
printError("Can't specify both --training and --inference benchmark variety.")
104105
} else if name == "" {
105-
print("Must provide a --benchmark to run.")
106+
printError("Must provide a --benchmark to run.")
106107
} else {
107108
var variety: BenchmarkVariety
108109
if trainingFlag {

Datasets/CIFAR10/CIFAR10.swift

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
// https://www.cs.toronto.edu/~kriz/cifar.html
1919

2020
import Foundation
21+
import ModelSupport
2122
import TensorFlow
2223

2324
#if canImport(FoundationNetworking)
@@ -41,23 +42,23 @@ func downloadCIFAR10IfNotPresent(to directory: String = ".") {
4142

4243
guard !directoryExists else { return }
4344

44-
print("Downloading CIFAR dataset...")
45+
printError("Downloading CIFAR dataset...")
4546
let archivePath = "\(directory)/cifar-10-binary.tar.gz"
4647
let archiveExists = FileManager.default.fileExists(atPath: archivePath)
4748
if !archiveExists {
48-
print("Archive missing, downloading...")
49+
printError("Archive missing, downloading...")
4950
do {
5051
let downloadedFile = try Data(
5152
contentsOf: URL(
5253
string: "https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz")!)
5354
try downloadedFile.write(to: URL(fileURLWithPath: archivePath))
5455
} catch {
55-
print("Could not download CIFAR dataset, error: \(error)")
56+
printError("Could not download CIFAR dataset, error: \(error)")
5657
exit(-1)
5758
}
5859
}
5960

60-
print("Archive downloaded, processing...")
61+
printError("Archive downloaded, processing...")
6162

6263
#if os(macOS)
6364
let tarLocation = "/usr/bin/tar"
@@ -72,17 +73,17 @@ func downloadCIFAR10IfNotPresent(to directory: String = ".") {
7273
try task.run()
7374
task.waitUntilExit()
7475
} catch {
75-
print("CIFAR extraction failed with error: \(error)")
76+
printError("CIFAR extraction failed with error: \(error)")
7677
}
7778

7879
do {
7980
try FileManager.default.removeItem(atPath: archivePath)
8081
} catch {
81-
print("Could not remove archive, error: \(error)")
82+
printError("Could not remove archive, error: \(error)")
8283
exit(-1)
8384
}
8485

85-
print("Unarchiving completed")
86+
printError("Unarchiving completed")
8687
}
8788

8889
func loadCIFARFile(named name: String, in directory: String = ".") -> LabeledExample {
@@ -91,11 +92,11 @@ func loadCIFARFile(named name: String, in directory: String = ".") -> LabeledExa
9192

9293
let imageCount = 10000
9394
guard let fileContents = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
94-
print("Could not read dataset file: \(name)")
95+
printError("Could not read dataset file: \(name)")
9596
exit(-1)
9697
}
9798
guard fileContents.count == 30_730_000 else {
98-
print(
99+
printError(
99100
"Dataset file \(name) should have 30730000 bytes, instead had \(fileContents.count)")
100101
exit(-1)
101102
}

Datasets/DatasetUtilities.swift

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
import Foundation
16+
import ModelSupport
1617

1718
#if canImport(FoundationNetworking)
1819
import FoundationNetworking
@@ -27,7 +28,7 @@ public struct DatasetUtilities {
2728
remoteRoot: URL,
2829
localStorageDirectory: URL = currentWorkingDirectoryURL
2930
) -> Data {
30-
print("Loading resource: \(filename)")
31+
printError("Loading resource: \(filename)")
3132

3233
let resource = ResourceDefinition(
3334
filename: filename,
@@ -37,16 +38,16 @@ public struct DatasetUtilities {
3738
let localURL = resource.localURL
3839

3940
if !FileManager.default.fileExists(atPath: localURL.path) {
40-
print(
41+
printError(
4142
"File does not exist locally at expected path: \(localURL.path) and must be fetched"
4243
)
4344
fetchFromRemoteAndSave(resource)
4445
}
4546

4647
do {
47-
print("Loading local data at: \(localURL.path)")
48+
printError("Loading local data at: \(localURL.path)")
4849
let data = try Data(contentsOf: localURL)
49-
print("Succesfully loaded resource: \(filename)")
50+
printError("Succesfully loaded resource: \(filename)")
5051
return data
5152
} catch {
5253
fatalError("Failed to contents of resource: \(localURL)")
@@ -76,20 +77,20 @@ public struct DatasetUtilities {
7677
let archiveLocation = resource.archiveURL
7778

7879
do {
79-
print("Fetching URL: \(remoteLocation)...")
80+
printError("Fetching URL: \(remoteLocation)...")
8081
let archiveData = try Data(contentsOf: remoteLocation)
81-
print("Writing fetched archive to: \(archiveLocation.path)")
82+
printError("Writing fetched archive to: \(archiveLocation.path)")
8283
try archiveData.write(to: archiveLocation)
8384
} catch {
8485
fatalError("Failed to fetch and save resource with error: \(error)")
8586
}
86-
print("Archive saved to: \(archiveLocation.path)")
87+
printError("Archive saved to: \(archiveLocation.path)")
8788

8889
extractArchive(for: resource)
8990
}
9091

9192
static func extractArchive(for resource: ResourceDefinition) {
92-
print("Extracting archive...")
93+
printError("Extracting archive...")
9394

9495
let archivePath = resource.archiveURL.path
9596

Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ let package = Package(
2525
],
2626
targets: [
2727
.target(name: "ImageClassificationModels", path: "Models/ImageClassification"),
28-
.target(name: "Datasets", path: "Datasets"),
28+
.target(name: "Datasets", dependencies: ["ModelSupport"], path: "Datasets"),
2929
.target(name: "ModelSupport", path: "Support"),
3030
.target(
3131
name: "Autoencoder", dependencies: ["Datasets", "ModelSupport"], path: "Autoencoder"),

Support/Image.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,12 @@ public struct Image {
8181
}
8282
}
8383

84-
public func saveImage(_ tensor: Tensor<Float>, size: (Int, Int), directory: String, name: String) throws {
84+
public func saveImage(_ tensor: Tensor<Float>, size: (Int, Int), directory: String, name: String)
85+
throws
86+
{
8587
try createDirectoryIfMissing(at: directory)
8688
let reshapedTensor = tensor.reshaped(to: [size.0, size.1, 1])
8789
let image = Image(tensor: reshapedTensor)
88-
let outputURL = URL(fileURLWithPath:"\(directory)\(name).jpg")
90+
let outputURL = URL(fileURLWithPath: "\(directory)\(name).jpg")
8991
image.save(to: outputURL)
9092
}

Support/Stderr.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import Foundation
2+
3+
var stderr = FileHandle.standardError
4+
5+
extension FileHandle: TextOutputStream {
6+
public func write(_ string: String) {
7+
guard let data = string.data(using: .utf8) else { return }
8+
self.write(data)
9+
}
10+
}
11+
12+
public func printError(_ message: String) {
13+
print(message, to: &stderr)
14+
}

0 commit comments

Comments
 (0)