|
2. Asosiy ma`lumotlar bilan tanishish Kengaytirilgan funksiyalar
|
bet | 4/7 | Sana | 24.05.2023 | Hajmi | 27.87 Kb. | | #64200 |
Bog'liq Masudbek TJKM 8-LABusing System;
using System.Net.Http;
using Newtonsoft.Json;
public class TranslationService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
public TranslationService(string apiKey)
{
_httpClient = new HttpClient();
_apiKey = apiKey;
}
public async Task TranslateText(string text, string sourceLanguage, string targetLanguage)
{
string apiUrl = $"https://translation.googleapis.com/language/translate/v2?key={_apiKey}";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("q", text),
new KeyValuePair("source", sourceLanguage),
new KeyValuePair("target", targetLanguage)
});
var response = await _httpClient.PostAsync(apiUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var translationResult = JsonConvert.DeserializeObject(responseContent);
return translationResult.Data.Translations[0].TranslatedText;
}
else
{
throw new Exception("Translation request failed.");
}
}
public async Task DetectLanguage(string text)
{
string apiUrl = $"https://translation.googleapis.com/language/translate/v2/detect?key={_apiKey}";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("q", text)
});
var response = await _httpClient.PostAsync(apiUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var detectionResult = JsonConvert.DeserializeObject(responseContent);
return detectionResult.Data.Detections[0][0].Language;
}
else
{
throw new Exception("Language detection request failed.");
}
}
}
public class TranslationResult
{
[JsonProperty("data")]
public TranslationData Data { get; set; }
}
public class TranslationData
{
[JsonProperty("translations")]
public Translation[] Translations { get; set; }
}
public class Translation
{
[JsonProperty("translatedText")]
public string TranslatedText { get; set; }
}
public class LanguageDetectionResult
{
[JsonProperty("data")]
public LanguageDetectionData Data { get; set; }
}
public class LanguageDetectionData
{
[JsonProperty("detections")]
public DetectedLanguage[][] Detections { get; set; }
}
public class DetectedLanguage
{
[JsonProperty("language")]
public string Language { get; set; }
}
public class Program
{
static async Task Main(string[] args)
{
string apiKey = "YOUR_API_KEY"; // Replace with your actual Google Translate API key
var translationService = new TranslationService(apiKey);
Console.Write("Enter the text to translate: ");
|
| |