Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
1863 connectés 

  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  Problème avec la traduction google traduction api et c#

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

Problème avec la traduction google traduction api et c#

n°2282973
rahmoune
Posté le 03-06-2016 à 14:26:20  profilanswer
 

Bonjour,
Je suis nouveau dans le domaine, je suis entrain de coder un programme de traduction en c# et google traduction api v2,j'ai réspetcer toutes les formalités pour le compte google, le problème est quand je compile, au lieu d'avoir la traduction je reçoit seulement le mot (data), est ce qu'il y a quelqu'un qui a une idée, voilà mon code et merci d'avance.
 
public string Translate(string sourceText,string sourceLanguage,string targetLanguage)
        {
            // Initialize
            this.Error = null;
            string translation = string.Empty;
             
            //string apKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
 
            try
            {
               /*string url = string.Format("https://www.googleapis.com/language/translate/v2?key=" + apKey+
                                "&q=" + sourceText+
                               "&source=" + sourceLanguage+
                               "&target=" + targetLanguage);
 
                string outputFile = Path.GetTempFileName();
                using (WebClient wc = new WebClient())
                {
                    wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0         Safari/537.36" );
                    wc.DownloadFile(url, outputFile);
}
}
 private void btnTranslate_Click(object sender, EventArgs e)
        {
            traductionRichTextBox.Text = string.Empty;
            traductionRichTextBox.Update();
            traduction = null;
 
            // Translate the text
            try
            {
                this.Cursor = Cursors.WaitCursor;
 
                traductionRichTextBox.Text = Translate(sourceRichTextBox.Text.Trim(), (string)fromComboBox.SelectedItem, (string)toComboBox.SelectedItem);
                if (Error == null)
                {
                    this.traductionRichTextBox.Update();
                }
                else
                {
                    MessageBox.Show(g.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

mood
Publicité
Posté le 03-06-2016 à 14:26:20  profilanswer
 

n°2282976
Moumoule
Posté le 03-06-2016 à 15:28:15  profilanswer
 

A mon avis, le problème vient du fait que tu recois un objet JSON en retour:
 
{
 "data": {
  "translations": [
   {
    "translatedText": "Hallo Welt"
   }
  ]
 }
}
 
Tu dois atteindre translatedText : data.translations, après pour translatedText tu dois faire gaffe car c'est un array ! De ce fait, data.translations.translatedText ne marchera pas. Pour le premier élément: data.translations[0].translatedText
 
Note: le résult de la fonction Translate est un string. De ce fait, tu dois impérativement parser ce JSON pour pouvoir accéder aux propriétés de l'objet:
 
// namespace:  System.Web.Script.Serialization
JavaScriptSerializer parser = new JavaScriptSerializer();
parser.Deserialize<Classe_custom>(response_de_la_fonction_translate);
 
Classe_custom  est une classe qui reprend la structure de la réponse (https://cloud.google.com/translate/v2/quickstart#before-you-begin)


Message édité par Moumoule le 03-06-2016 à 15:28:28
n°2282987
rahmoune
Posté le 03-06-2016 à 18:40:31  profilanswer
 

Bonjour Moumoule,
J'utilise même pas Json, mon problème je pense que c'est côté de appkey, même si j'ai vérifié dans google translate, je vois que tut est correct, l'app est activé. Je dis ça pqr ce que j'ai un autre url qui fonctionne, mais c'est pas un api v2, il est comme  gratuit le voila:
string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
                                            sourceLanguage,
                                            targetLanguage,
                                            sourceText);
Mais moi je veux que le programme foctionne avec appkey.
 
Merci d'avance pour ta réponse.

n°2283090
Moumoule
Posté le 06-06-2016 à 11:00:17  profilanswer
 

rahmoune a écrit :

Bonjour Moumoule,
J'utilise même pas Json, mon problème je pense que c'est côté de appkey, même si j'ai vérifié dans google translate, je vois que tut est correct, l'app est activé. Je dis ça pqr ce que j'ai un autre url qui fonctionne, mais c'est pas un api v2, il est comme  gratuit le voila:
string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
                                            sourceLanguage,
                                            targetLanguage,
                                            sourceText);
Mais moi je veux que le programme foctionne avec appkey.
 
Merci d'avance pour ta réponse.


 
A mon avis tu as pas compris ce que je voulais dire.
 
Le résultat de l'appel de l'API est un JSON. De ce fait, de ton côté, tu vas devoir traiter ce JSON:
 

Code :
  1. Translating text
  2. This section demonstrates a few ways to request translations. To run each example, copy the URL and paste it into your browser. Don't forget to replace YOUR_API_KEY with your actual API key.
  3. The URL for a request has the following format:
  4. https://www.googleapis.com/language [...] parameters
  5. Three query parameters are required with each translation request:
  6.     API key: Use the key parameter to identify your application.
  7.     Target language: Use the target parameter to specify the language you want to translate into.
  8.     Source text string: Use the q parameter to specify the text to translate.
  9. All other query parameters are optional. The URL for GET requests, including parameters, must be less than 2K characters.
  10. Translating a single string
  11. To translate a string, just make a request using the required parameters. Here is an example that specifies the source language, using the optional source query parameter:
  12. https://www.googleapis.com/language [...] lo%20world
  13. If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:
  14. 200 OK
  15. {
  16.     "data": {
  17.         "translations": [
  18.             {
  19.                 "translatedText": "Hallo Welt"
  20.             }
  21.         ]
  22.     }
  23. }
  24. In this example, the response is an array containing a single translatedText field with the translation.


 
Après, si tu as des problème authentification (appkey), ça c'est autre chose. Après, quand je regarde ta fonction Translate, je vois pas de retour (manque pas un return de la variable translation ? Tu garnis quand la variable translation ? )

n°2283134
rahmoune
Posté le 06-06-2016 à 20:58:38  profilanswer
 

Bonjour,
 
Pour la variable translation, je l'ai mauqué en séelectionnant la méthode. Mais ce que je veux savoir, ou je placerai les lignes pour parcer Json, par ce que je n'ai pas d'autres classes, j'ai la méthode de traduction et le boutton, peut tu m'expliquer plus et si ce n'est pas trop, tu peut ajouter un exemple dans mon code.
 
Merci d'avance

n°2283185
Moumoule
Posté le 07-06-2016 à 11:30:26  profilanswer
 

Bon, normalement je fais pas de code à la demande comme ca car y a les ressources disponibles sur le net ... en masse même. Soit:
 

Code :
  1. public string Translate(string sourceText,string sourceLanguage,string targetLanguage)
  2.         {
  3.             // Initialize  
  4.             this.Error = null;
  5.             string translation = string.Empty;
  6.            
  7.             //string apKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  
  8.             try
  9.             {
  10.                string url = string.Format("https://www.googleapis.com/language/translate/v2?key=" + apKey+
  11.                                 "&q=" + sourceText+
  12.                                "&source=" + sourceLanguage+
  13.                                "&target=" + targetLanguage);
  14.                 string outputFile = Path.GetTempFileName();
  15.                 using (WebClient wc = new WebClient())
  16.                 {
  17.                     wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0         Safari/537.36" );
  18.                 wc.DownloadFile(url, outputFile);
  19.                  translation = wc.DownloadString(url);
  20.                  return translation
  21. } catch (Exception ex) {
  22.             throw new Exception(ex.toString());
  23. }
  24. }
  25. private void btnTranslate_Click(object sender, EventArgs e)
  26.         {
  27.             traductionRichTextBox.Text = string.Empty;
  28.             traductionRichTextBox.Update();
  29.             traduction = null;
  30.             // Translate the text  
  31.             try
  32.             {
  33.                 this.Cursor = Cursors.WaitCursor;
  34.                 string retourTranslate = Translate(sourceRichTextBox.Text.Trim(), (string)fromComboBox.SelectedItem, (string)toComboBox.SelectedItem);
  35.                
  36.                 traductionRichTextBox.Text = retourTranslate;
  37.                 if (Error == null)
  38.                 {
  39.                     this.traductionRichTextBox.Update();
  40.                 }
  41.                 else
  42.                 {
  43.                     MessageBox.Show(g.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  44.                 }
  45.             }
  46.             catch (Exception ex)
  47.             {
  48.                 MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  49.             }
  50.             finally
  51.             {
  52.                 this.Cursor = Cursors.Default;
  53.             }
  54.         }
  55. class responseAPI {
  56.         // Si c'est du JSON, tu vas devoir décrire le résultat (voir parser.Deserialize)
  57. }


 
Ce qui est important c'est de voir à quoi ressemble la variable "retourTranslate". Si c'est du JSON, tu dois parser ce JSON (après  string retourTranslate = Translate(sourceRichTextBox.Text.Trim(), (string)fromComboBox.SelectedItem, (string)toComboBox.SelectedItem); )
 
Par contre pour parser un JSON en c#, tu as un petit snippet dans un de mes précédants posts. Sinon => google est ton ami =)


Message édité par Moumoule le 07-06-2016 à 11:32:28
n°2283396
rahmoune
Posté le 09-06-2016 à 13:39:58  profilanswer
 

Bonjour Moumoune,
 
Merci beaucoup mon problème est resolu, c'était la deserialisation de Json qui causait un problème, alors j'ai ajouté 3 classesavec le datcontract, et j'ai fait l'appel dans la déserialisation et ça marchait. Voilà mon code fonctionnel:
 
public string Translate(string sourceText,string sourceLanguage,string targetLanguage)
        {
            // Initialize  
            this.Error = null;
            string translation = string.Empty;
           
            //string apKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  
            try
            {
               string url = string.Format("https://www.googleapis.com/language/translate/v2?key=" + apKey+
                                "&q=" + sourceText+
                               "&source=" + sourceLanguage+
                               "&target=" + targetLanguage);
                string outputFile = Path.GetTempFileName();
                using (WebClient wc = new WebClient())
                {
                    wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0         Safari/537.36" );
                 translation = wc.DownloadString(url);
                 
                  resultat = HttpUtility.HtmlDecode(resultat);
 
                  JavaScriptSerializer oSerializer = new JavaScriptSerializer();
                 GgleTranslation oTraduction = oSerializer.Deserialize<GgleTranslation>(resultat);
 
                traduction = oTraduction.Data.Translations[0].TranslatedText;
                 return translation
} catch (Exception ex) {
            throw new Exception(ex.toString());
}
}
private void btnTranslate_Click(object sender, EventArgs e)
        {
            traductionRichTextBox.Text = string.Empty;
            traductionRichTextBox.Update();
            traduction = null;
            // Translate the text  
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string retourTranslate = Translate(sourceRichTextBox.Text.Trim(), (string)fromComboBox.SelectedItem,             (string)toComboBox.SelectedItem);
               
                traductionRichTextBox.Text = retourTranslate;
                if (Error == null)
                {
                    this.traductionRichTextBox.Update();
                }
                else
                {
                    MessageBox.Show(g.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
 [DataContract]
    public class GgleTranslation
    {
        [DataMember(Name = "data" )]
        public Data Data { get; set; }
    }
 
    [DataContract]
    public class Data
    {
        [DataMember(Name = "translations" )]
        public List<Translation> Translations { get; set; }
    }
 
    [DataContract]
    public class Translation
    {
        [DataMember(Name = "translatedText" )]
        public string TranslatedText { get; set; }
    }

n°2283427
Moumoule
Posté le 09-06-2016 à 16:47:53  profilanswer
 

rahmoune a écrit :

c'était la deserialisation de Json qui causait un problème, alors j'ai ajouté 3 classesavec le datcontract, et j'ai fait l'appel dans la déserialisation et ça marchait.


 
C'est le terme que je cherchais, déserialisation.
 

Citation :

traduction = oTraduction.Data.Translations[0].TranslatedText;


 
Fait juste attention (je pense que tu le sais déjà), cela va te renvoyer la première traduction de la liste Translation.
 
Content d'avoir pu aider !


Message édité par Moumoule le 09-06-2016 à 16:48:52

Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  Problème avec la traduction google traduction api et c#

 

Sujets relatifs
Probleme d'enregistrementProblème, besoin d'aide svp!
Mettre une légende sur une google mapPetit problème avec mon formulaire d'inscription/connexion
Java : Problème affichage à partir d'un dossier txtProbléme de paginations en php/sql
probleme avec un panier pour un site e commerceProbleme avec l'exportation de mes programmes en C++
Problème en Python pour un projet de balle rebondissanteProblème Processing Bataille Navale
Plus de sujets relatifs à : Problème avec la traduction google traduction api et c#


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR