2. Asosiy ma`lumotlar bilan tanishish Kengaytirilgan funksiyalar




Download 27.87 Kb.
bet4/7
Sana24.05.2023
Hajmi27.87 Kb.
#64200
1   2   3   4   5   6   7
Bog'liq
Masudbek
TJKM 8-LAB
using 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: ");

Download 27.87 Kb.
1   2   3   4   5   6   7




Download 27.87 Kb.

Bosh sahifa
Aloqalar

    Bosh sahifa



2. Asosiy ma`lumotlar bilan tanishish Kengaytirilgan funksiyalar

Download 27.87 Kb.