Skip to content

Commit

Permalink
Merge pull request #32 from renatocamara/bugfix
Browse files Browse the repository at this point in the history
If the JSON is an object, you should use JObject.Parse instead of JArray. Fixes #32
  • Loading branch information
paul-iveylabs authored Aug 28, 2024
2 parents 09a9aa0 + 9ea19c0 commit b52d748
Showing 1 changed file with 49 additions and 18 deletions.
67 changes: 49 additions & 18 deletions 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public async Task OnGetAsync()

// Make a GET request to the Text Translation API to get a list of all supported languages
string endpoint = $"{translatorEndpoint}/languages?api-version=3.0&scope=translation";

HttpResponseMessage response = await _httpClient.GetAsync(endpoint);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Expand All @@ -55,7 +55,7 @@ public async Task OnGetAsync()

foreach (var language in languageData.Translation)

Check warning on line 56 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.
{
Languages.Add(new SelectListItem { Value = language.Key.ToString(), Text = $"{language.Value["name"]} ({language.Value["nativeName"]})"});
Languages.Add(new SelectListItem { Value = language.Key.ToString(), Text = $"{language.Value["name"]} ({language.Value["nativeName"]})" });
}
}

Expand All @@ -67,15 +67,15 @@ public async Task<IActionResult> OnPostProcessInputAsync(string InputText, strin
string originalText = InputText;

// If FromLanguage is Default, detect the language
if(FromLanguage == "default")
if (FromLanguage == "default")
{
try
{
object[] body = new object[] { new { Text = originalText } };
var requestBody = JsonSerializer.Serialize(body);
using var client = new HttpClient();
using var request = new HttpRequestMessage();

// Build the request
string path = "/detect?api-version=3.0";
request.Method = HttpMethod.Post;
Expand All @@ -86,7 +86,7 @@ public async Task<IActionResult> OnPostProcessInputAsync(string InputText, strin

// Send the request and get response
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);

// Read the response as a string
string result = await response.Content.ReadAsStringAsync();

Expand All @@ -103,22 +103,20 @@ public async Task<IActionResult> OnPostProcessInputAsync(string InputText, strin
{
FromLanguage = "en";
}

}

// If ToLanguage is Default, set it to en
if(ToLanguage == "default")
if (ToLanguage == "default")
{
ToLanguage = "en";
}

// Build the translation request
// If MaskProfanity is true, mask profanity
string route = $"/translate?api-version=3.0&from={FromLanguage}&to={ToLanguage}";
if(MaskProfanity)
if (MaskProfanity)
{
route = $"/translate?api-version=3.0&from={FromLanguage}&to={ToLanguage}&profanityAction=Marked";

}
object[] translateBody = new object[] { new { Text = originalText } };
var translateRequestBody = JsonSerializer.Serialize(translateBody);
Expand All @@ -135,21 +133,54 @@ public async Task<IActionResult> OnPostProcessInputAsync(string InputText, strin

// Read the response as a string
string translateResult = await translateResponse.Content.ReadAsStringAsync();

// Parse the JSON response and get the translated text
JArray translateJson = JArray.Parse(translateResult);
JObject responseJson = JObject.Parse(translateJson[0].ToString());
string translatedText = translateJson[0]["translations"][0]["text"].ToString();

Console.WriteLine("API Response: " + translateResult);

if (string.IsNullOrEmpty(translateResult))
{
ViewData["TranslatedText"] = "Translation response is empty.";
}
else
{
// Check if the JSON is an array or an object
if (translateResult.Trim().StartsWith("["))
{
// Parse the JSON response and get the translated text
JArray translateJson = JArray.Parse(translateResult);
if (translateJson[0]["translations"] != null)
{
string translatedText = translateJson[0]["translations"][0]["text"].ToString();

Check warning on line 151 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.

Check warning on line 151 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.

Check warning on line 151 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.
ViewData["TranslatedText"] = translatedText;
ViewData["TranslateResponse"] = translateJson;
}
else
{
ViewData["TranslatedText"] = "No translations found in the response.";
}
}
else
{
// Handle the case where the JSON is an object
JObject translateJson = JObject.Parse(translateResult);
if (translateJson["translations"] != null)
{
string translatedText = translateJson["translations"][0]["text"].ToString();

Check warning on line 166 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.

Check warning on line 166 in 03-nlp/01-TranslateText/Pages/Translate.cshtml.cs

View workflow job for this annotation

GitHub Actions / ci (03-nlp/01-TranslateText/TranslateText.csproj) / build

Dereference of a possibly null reference.
ViewData["TranslatedText"] = translatedText;
ViewData["TranslateResponse"] = translateJson;
}
else
{
ViewData["TranslatedText"] = "No translations found in the response.";
}
}
}

ViewData["TranslateMethod"] = translateRequest.Method;
ViewData["TranslateUri"] = translateRequest.RequestUri;
ViewData["TranslateBody"] = translateRequest.Content.ReadAsStringAsync().Result.ToString();;
ViewData["TranslateResponse"] = responseJson;
ViewData["TranslateBody"] = translateRequest.Content.ReadAsStringAsync().Result.ToString();

ViewData["OriginalText"] = originalText;
ViewData["FromLanguage"] = FromLanguage;
ViewData["ToLanguage"] = ToLanguage;
ViewData["TranslatedText"] = translatedText;

await OnGetAsync();
return Page();
Expand Down

0 comments on commit b52d748

Please sign in to comment.