Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to upload a document use this API #3

Open
Squallerxp opened this issue Mar 10, 2021 · 0 comments
Open

How to upload a document use this API #3

Squallerxp opened this issue Mar 10, 2021 · 0 comments

Comments

@Squallerxp
Copy link

Hello,

I try to use Document Import function from Microsoft Custom Translator API Preview 1.0 to upload a document to Customer Translator Protal but failed.

The API I use is below
/api/texttranslator/v1.0/documents/import
Upload files for processing. Documents are created asynchronously. Upload status can be checked using the returned job id
from https://custom-api.cognitive.microsofttranslator.com/swagger/#!/Documents/ApiTexttranslatorV1_0DocumentsImportPost

there is my code below,

    static void Main(string[] args)
    {
        client.LoadCredentials();
        clientId = AccessTokenClient.ClientId;

        ''' ''' '''

        // Get the categories from the Custom Translator api. This just tests that we have a valid auth token.
        Console.WriteLine("Calling Custom Translator categories API to verify auth...");
        restClient = new RestClient(apiEndpoint);
        GetCategories(idToken);

        string result = ComboFile(idToken);

        Console.WriteLine();
        Console.WriteLine($"Press any key to exit.");
        Console.ReadKey();
    }

    public static String ComboFile(string token)
    {
        string filepath = @"C:\test.xlsx";                                      // Enter local path for combo file
        DocumentDetailsForImportRequest documentdetails = new DocumentDetailsForImportRequest();
        documentdetails.DocumentName = Path.GetFileName(filepath);    // Enter document name
        documentdetails.DocumentType = "training";                              // values = training/ tuning/ testing
        documentdetails.IsParallel = false;                                     // Enter if this is a parallel document. values = true, false
        documentdetails.FileDetails = new List<FileForImportRequest>();
        string result = ImportComboDocument("Bearer " + token, workspaceId, filepath, documentdetails);
        return result;
    }

    public static string ImportComboDocument(string authtoken, string workspaceid, string filepath, DocumentDetailsForImportRequest documentdetails)
    {
        string result = "";
        string host = "https://custom-api.cognitive.microsofttranslator.com";   // prod
        string apipath = $"/api/texttranslator/v1.0/documents/import?workspaceId={Uri.EscapeUriString(workspaceid)}";
        FileForImportRequest combofile = new FileForImportRequest();
        combofile.Name = Path.GetFileName(filepath);
        combofile.OverwriteIfExists = false;
        //combofile.Language = "";
        //combofile.Type = "";

        documentdetails.FileDetails.Add(combofile);
        var details = new List<DocumentDetailsForImportRequest>() { documentdetails };
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", authtoken);
        string uri = host + apipath;

        HttpResponseMessage response = new HttpResponseMessage();
        MultipartFormDataContent formData = new MultipartFormDataContent();

        FileStream targetlanguagestream = File.OpenRead(filepath);
        HttpContent targetfileStreamContent = new StreamContent(targetlanguagestream);
        formData.Add(targetfileStreamContent, "Files", combofile.Name);

        string stringdata = JsonConvert.SerializeObject(details, Formatting.Indented);
        StringContent stringcontent = new StringContent(stringdata);
        formData.Add(stringcontent, "DocumentDetails");

        try
        {
            response = client.PostAsync(uri, formData).Result;
            result = response.Content.ReadAsStringAsync().Result;
            response.EnsureSuccessStatusCode();
        }
        catch (Exception e)
        {
            result = e.Message + ". " + e.InnerException;
        }
        return result;
    }

after running
response = client.PostAsync(uri, formData).Result;
the response is
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Access-Control-Expose-Headers: Location, Content-Disposition
Request-Context: appId=cid-v1:347e3f37-b249-4148-861e-bcb47f147755
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
api-supported-versions: 1.0
Date: Wed, 10 Mar 2021 08:09:19 GMT
Server: Kestrel
X-Powered-By: ASP.NET
Content-Type: application/json; charset=utf-8
}}

would you have any suggest on my issue, thanks.

there have two classes used for this document uploading

public class DocumentDetailsForImportRequest
{
    public string DocumentName { get; set; }
    public string DocumentType { get; set; } //values = training/ tuning/ testing
    public bool IsParallel { get; set; }
    public List<FileForImportRequest> FileDetails { get; set; }
}

public class FileForImportRequest
{
    public string Name { get; set; }
    public string Language { get; set; }
    public string Type { get; set; }
    public bool OverwriteIfExists { get; set; }
}

I want upload a combodocument,
How can I set the values for FileForImportRequest.Language and FileForImportRequest.Type.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant