[Python] Rewrite python request to upload image data via api in SwiftUI

Discussão em 'Python' iniciado por Stack, Outubro 6, 2024.

  1. Stack

    Stack Membro Participativo

    I rewrote the code as such, but it looks like it wont function the same way. and also, not sure how to rewrite the "Files" data using UIimage for a captured image.

    Here is the python code i needed to rewrite:

    import json
    import requests

    # Run inference on an image
    url = "URL"
    headers = {"x-api-key": "Token"}
    data = {"model": "Specific model"}
    with open("image.jpg", "rb") as f:
    response = requests.post(url, headers=headers, data=data, files={"file": f})

    # Check for successful response
    response.raise_for_status()

    # Print inference results
    print(json.dumps(response.json(), indent=2))


    Here is how i tried to rewrite it

    import UIKit

    func uploadImage(photo: UIImage) async {
    // Define the API endpoint and your API key
    let apiURL = URL(string: "URL")!
    let apiKey = "Token"

    guard let imageData = photo.jpegData(compressionQuality: 1.0) else {
    print("Could not convert image to JPEG data.")
    return
    }

    // Create the URL request
    var request = URLRequest(url: apiURL)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
    request.setValue(apiKey, forHTTPHeaderField: "x-api-key")

    // Create the JSON payload
    let base64Image = imageData.base64EncodedString()
    let jsonPayload: [String: Any] = [
    "model": "Specific model",
    "file": base64Image
    ]

    guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonPayload) else {
    print("Could not serialize JSON data.")
    return
    }
    request.httpBody = jsonData

    // Perform the network request
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
    print("Error: \(error.localizedDescription)")
    return
    }
    guard let data = data else {
    print("No data received.")
    return
    }

    // Handle the response
    do {
    if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    print("Response JSON: \(jsonResponse)")
    return
    // Parse and use the response data
    }
    } catch let jsonError {
    print("JSON Error: \(jsonError.localizedDescription)")
    return
    }
    }
    task.resume()
    }



    I have tried to use an external API and match the response and what they both send and they are both calling and sending the same data. but the swift code is not sending the same data in the same format as the python code, and also not sure how to include the "Files" part in the swift code and request protocol

    Continue reading...

Compartilhe esta Página