<commit_before>//
//  MemoriesViewController.swift
//  Nostalgia
//
//  Created by <NAME> on 12/25/16.
//  Copyright © 2016 ddApps. All rights reserved.
//

import UIKit
import AVFoundation // Microphone Access
import Photos       // Photo Library Access
import Speech       // Speech Transcription

class MemoriesViewController: UICollectionViewController {
    
    // array of URLs for the memories
    var memories = [URL]()
    
    
    // MARK: - View Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadMemories()
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        checkPermissions()
    }
    
    
    // MARK: - Check Permission Method
    
    func checkPermissions() {
        // check status for all three permissions
        let photosAuthorized = PHPhotoLibrary.authorizationStatus() == .authorized
        let recordingAuthorized = AVAudioSession.sharedInstance().recordPermission() == .granted
        let transcribeAuthorized = SFSpeechRecognizer.authorizationStatus() == .authorized
        
        // aggregate all three status into a single boolean
        let authorized = photosAuthorized && recordingAuthorized && transcribeAuthorized
        
        // if we are missing one then show the first run screen
        if !authorized {
            if let vc = storyboard?.instantiateViewController(withIdentifier: "FirstRun") {
                navigationController?.present(vc, animated: true, completion: nil)
            }
        }
    }
    
    
    // MARK: - Helper Method to Find Document Directory
    
    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        
        return documentsDirectory
    }
    
    
    // MARK: - Load Memories Function
    
    func loadMemories() {
        memories.removeAll()
        
        // attempt to load all memories in our document directory
        guard let files = try? FileManager.default.contentsOfDirectory(at: getDocumentsDirectory(), includingPropertiesForKeys: nil, options: []) else { return }
        
        // loop over every file 
        for file in files {
            let filename = file.lastPathComponent
            
            // check that it ends with ".thumb" so we don't count each memory more than once
            if filename.hasSuffix(".thumb") {
                // get the root name of the memory (ie, without its path extension)
                let noExtension = filename.replacingOccurrences(of: ".thumb", with: "")
                
                // create a full path from the memory
                let memoryPath = getDocumentsDirectory().appendingPathComponent(noExtension)
                
                // add it to the memories array
                memories.append(memoryPath)
            }
        }
        
        // reload the list of memories
        collectionView?.reloadSections(IndexSet(integer: 1))
    }

}<commit_msg>Import photos with UIImagePickerController and add thumbnails<commit_after>//
//  MemoriesViewController.swift
//  Nostalgia
//
//  Created by <NAME> on 12/25/16.
//  Copyright © 2016 ddApps. All rights reserved.
//

import UIKit
import AVFoundation // Microphone Access
import Photos       // Photo Library Access
import Speech       // Speech Transcription

class MemoriesViewController: UICollectionViewController {
    
    // array of URLs for the memories
    var memories = [URL]()
    
    
    // MARK: - View Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add a nav bar button to add a photo
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhoto))
        
        loadMemories()
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        checkPermissions()
    }
    
    
    // MARK: - Check Permission Method
    
    func checkPermissions() {
        // check status for all three permissions
        let photosAuthorized = PHPhotoLibrary.authorizationStatus() == .authorized
        let recordingAuthorized = AVAudioSession.sharedInstance().recordPermission() == .granted
        let transcribeAuthorized = SFSpeechRecognizer.authorizationStatus() == .authorized
        
        // aggregate all three status into a single boolean
        let authorized = photosAuthorized && recordingAuthorized && transcribeAuthorized
        
        // if we are missing one then show the first run screen
        if !authorized {
            if let vc = storyboard?.instantiateViewController(withIdentifier: "FirstRun") {
                navigationController?.present(vc, animated: true, completion: nil)
            }
        }
    }
    
    
    // MARK: - Helper Method to Find Document Directory
    
    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        
        return documentsDirectory
    }
    
    
    // MARK: - Load and Save Memories Functions
    
    func loadMemories() {
        memories.removeAll()
        
        // attempt to load all memories in our document directory
        guard let files = try? FileManager.default.contentsOfDirectory(at: getDocumentsDirectory(), includingPropertiesForKeys: nil, options: []) else { return }
        
        // loop over every file 
        for file in files {
            let filename = file.lastPathComponent
            
            // check that it ends with ".thumb" so we don't count each memory more than once
            if filename.hasSuffix(".thumb") {
                // get the root name of the memory (ie, without its path extension)
                let noExtension = filename.replacingOccurrences(of: ".thumb", with: "")
                
                // create a full path from the memory
                let memoryPath = getDocumentsDirectory().appendingPathComponent(noExtension)
                
                // add it to the memories array
                memories.append(memoryPath)
            }
        }
        
        // reload the list of memories
        collectionView?.reloadSections(IndexSet(integer: 1))
    }
    
    
    func saveNewMemory(image: UIImage) {
        // create a unique name for the memory using seconds
        let memoryName = "memory-\(Date().timeIntervalSince1970)"
        
        // use the unique name to create filenames for the full size image and thumbnail
        let imageName = memoryName + ".jpg"
        let thumbnailName = memoryName + ".thumb"
        
        do {
            // create a URL where we can write a jpg to
            let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
            
            // convert the UIImage to a JPEG data object
            if let jpegData = UIImageJPEGRepresentation(image, 80) {
                // write data to URL we created
                try jpegData.write(to: imagePath, options: [.atomicWrite])
            }
            // create thumbnail
            if let thumbnail = resize(image: image, to: 200) {
                let imagePath = getDocumentsDirectory().appendingPathComponent(thumbnailName)
                if let jpegData = UIImageJPEGRepresentation(thumbnail, 80) {
                    try jpegData.write(to: imagePath, options: [.atomicWrite])
                }
            }
            
        } catch {
            print("saveMemory: Failed to write to disk.")
        }
    }
    
    
    // MARK: - Add Photo Function
    
    func addPhoto() {
        let vc = UIImagePickerController()
        vc.modalPresentationStyle = .formSheet
        vc.delegate = self
        navigationController?.present(vc, animated: true)
    }
    
    
    // MARK: - Resize Photo Helper Method
    
    func resize(image: UIImage, to width: CGFloat) -> UIImage? {
        // calculate how much we need to bring our width size to match our target size
        let scale = width / image.size.width
        
        // bring the height down by the same amount to preserve the aspect ratio
        let height = image.size.height * scale
        
        // create a new image context we can draw into
        UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0)
        
        // draw the original image into the context
        image.draw(in: CGRect(x: 0, y:0, width: width, height: height))
        
        // pull out the resized version
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // end the context so UIKit can clean up
        UIGraphicsEndImageContext()
        
        // return resized image
        return newImage
    }

}


extension MemoriesViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        dismiss(animated: true)
        
        if let possibleImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            saveNewMemory(image: possibleImage)
            loadMemories()
        }
    }
    
}
{'fraction_non_alphanumeric': 0.07529286474973376, 'fraction_numerical': 0.004046858359957401, 'mean_word_length': 1.9652668140195768, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5105498', 'n_tokens_mistral': 2403, 'n_tokens_neox': 2298, 'n_words': 735}