IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage Delphi Discussion :

Traduction en ligne en chinois simplifié


Sujet :

Langage Delphi

  1. #1
    Membre confirmé

    Inscrit en
    Novembre 2002
    Messages
    749
    Détails du profil
    Informations forums :
    Inscription : Novembre 2002
    Messages : 749
    Points : 500
    Points
    500
    Par défaut Traduction en ligne en chinois simplifié
    Bonjour a tous,

    j'essaie de développer un petit code qui se connecte au net (azure.microsoft.com) pour traduire des expressions dans diverses langues. En fait c'est quelque chose de très semblable à "Google traduction".

    Cela semble fonctionner dans les deux langues que je comprends et même si je comprends rien aux langues asiatiques, je vois que cela en marche pas ( caractères affichés "?"). Cela fait déjà quelque temps que je tourne en ronds.

    Comme je ne sais même pas vous expliquer ou disons bien formuler le problème ( mais qui doit est un problème de conversion UTF8, UTF16 ou autre), je vous joint les sources de deux codes (très court) ci dessous, mais aussi en pièces jointes pour fournir la DFM de programme de test de la DLL.

    1) Un code à compiler de la DLL qui permet de traduire les mot via le net.
    2) Un code a compiler "TestDLL" pour utiliser et tester le résultat de la traduction.

    Delphi : XE2
    OS : W7
    remarque tout est dans une seul répertoire et la DLL compilé et dans le même répertoire de que le programme de test.

    Si quelqu'un a un peu de temps en perdre.. cela serait sympa d'y jeter un coup d’œil.

    => N'ayant pas trouvé beaucoup d'infos sur ce type de travail, je pense qu'il sera utile à tous les gens qui auront des besoins similaires.


    Code pour le programme de test.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
     
    unit TestDLLTraducteur;
     
    interface
     
    uses
      Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
      Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AdvEdit;
     
    type
      TForm1 = class(TForm)
        btnTraduire: TButton;
        IDClient: TEdit;
        SecretClient: TEdit;
        LabelIDClient: TLabel;
        LabelSecretClient: TLabel;
        btnInit: TButton;
        Button1: TButton;
        LangueSource: TEdit;
        LangueCible: TEdit;
        TexteCible: TAdvEdit;
        TexteSource: TAdvEdit;
        TexteCible1: TAdvEdit;
        LangueCible1: TEdit;
        TexteCible2: TAdvEdit;
        LangueCible2: TEdit;
        procedure btnInitClick(Sender: TObject);
        procedure btnTraduireClick(Sender: TObject);
        procedure Button1Click(Sender: TObject);
        procedure FormShow(Sender: TObject);
      private
        { Déclarations privées }
      public
        { Déclarations publiques }
      end;
     
    var
      Form1: TForm1;
     
    implementation
     
    {$R *.dfm}
     
    // Dll Traducteur
    var
      HandleDLLTraducteur         :Thandle;
      ExInitDLLTraducteur         :function(sclientSecret,sclientID:string):boolean;stdcall;
      ExTraduitTexteDLLTraducteur :function(sText,sFrom,sTo:Widestring):Widestring;stdcall;
      NomDLL                      :string;
      //------------------------------------------------------------------------------
    procedure LectureFonctionDLLTraducteur ;
    var
      sPath:string;
    begin
      NomDLL:='DLLTraducteur.DLL' ;
      sPath:=ExtractFilePath(Application.ExeName);
     
      HandleDLLTraducteur:=LoadLibrary(PChar(sPath+NomDLL));
      if HandleDLLTraducteur=0 then exit
      else
      begin
         @ExInitDLLTraducteur:=GetProcAddress(HandleDLLTraducteur,'ExInitDLLTraducteur');
           if @ExInitDLLTraducteur=nil then exit;
         @ExTraduitTexteDLLTraducteur:=GetProcAddress(HandleDLLTraducteur,'ExTraduitTexteDLLTraducteur');
           if @ExTraduitTexteDLLTraducteur=nil then exit;
      end;
    end;
    //------------------------------------------------------------------------------
    procedure TForm1.FormShow(Sender: TObject);
    begin
       btnInit.OnClick(nil);
    end;
    //------------------------------------------------------------------------------
    procedure TForm1.btnInitClick(Sender: TObject);
    var
      sTemp:string;
      sIDClient:string;
      sSecretClient:string;
    begin
         LectureFonctionDLLTraducteur;
         // on initialise la DLL
         sIDClient:=IDClient.Text;
         sSecretClient:=SecretClient.Text;
     
         if ExInitDLLTraducteur(sSecretClient,sIDClient)=true then
         begin
              btnTraduire.Enabled:=true;
              sTemp:='ok';
         end
         else sTemp:='nok';
    end;
    //------------------------------------------------------------------------------
    procedure TForm1.btnTraduireClick(Sender: TObject);
    var i:integer;
    begin
      TexteCible.Text:=ExTraduitTexteDLLTraducteur(TexteSource.Text,LangueSource.Text,LangueCible.Text);
      TexteCible1.Text:=ExTraduitTexteDLLTraducteur(TexteSource.Text,LangueSource.Text,LangueCible1.Text);
      TexteCible2.Text:=ExTraduitTexteDLLTraducteur(TexteSource.Text,LangueSource.Text,LangueCible2.Text);
     
      application.ProcessMessages;
    end;
    //------------------------------------------------------------------------------
    procedure TForm1.Button1Click(Sender: TObject);
    begin
       FreeLibrary(HandleDLLTraducteur);
       Application.Terminate;
    end;
     
    end.
    Code pour la DLL de traduction.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
     
    unit DLLUTraducteur;
     
    interface
     
    uses Classes,SysUtils,IdHTTP,IdTCPConnection,IdSSLOpenSSL,StrUtils,IdGlobal,HTTPApp,WinInet,DateUtils,
         System.WideStrUtils;
     
    function ExInitDLLTraducteur(sclientSecret,sclientID:string):boolean;stdcall;
    function ExTraduitTexteDLLTraducteur(sText,sFrom,sTo:Widestring):widestring;stdcall;
     
    implementation
     
    // exports des 2 fonctions
    Exports ExInitDLLTraducteur         Name 'ExInitDLLTraducteur';
    Exports ExTraduitTexteDLLTraducteur Name 'ExTraduitTexteDLLTraducteur';
     
    // variables globales
    var
    VarTimeStart : TDateTime;
    tokenAccess  : string;
    clientID     : string;
    clientSecret : string;
     
    //==============================================================================
    // Procedure de récupération des champs du token
    procedure SplitColumnsNoTrim(const AData: String; AStrings: TStrings; const ADelim: String=' ');
    var
       i: Integer;
       LDelim: Integer;
       LLeft: String;
       LLastPos: Integer;
    Begin
         Assert(Assigned(AStrings));
         AStrings.Clear;
         LDelim := Length(ADelim);
         LLastPos := 1;
     
         i := Pos(ADelim, AData);
     
         while I > 0 do
         begin
              LLeft:= Copy(AData, LLastPos, I-LLastPos);
              if LLeft > '' then
              begin
                   AStrings.AddObject(LLeft,Pointer(LLastPos));
              end;
     
              LLastPos := I + LDelim;
              i := PosIdx (ADelim, AData, LLastPos);
         end;
     
         if LLastPos <= Length(AData) then
         begin
              AStrings.AddObject(Copy(AData,LLastPos,MaxInt), Pointer(LLastPos));
         end;
    End;
    //==============================================================================
    // Fonction de récupèration d'un jeton d'accès au service :
    // paramètres d'entrée :
    // - aucun
    // paramètre de retour :
    // - string : jeton (token) à utiliser pour appel a la fonction de traduction
    function Translator_GetToken:string;
    const
      DatamarketAccessUri = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13';
    var
       tokenURL:string;
       lHTTP: TIdHTTP;
       Ts : TStringList;
       sTemp:string;
       LHandler: TIdSSLIOHandlerSocketOpenSSL;
       ResPost:TStringStream;
       Strings: TStringList;
    begin
         // on crée les composants
         Ts := TStringList.Create;
         ResPost := TStringStream.Create;
         Strings := TStringList.Create;
         lHTTP := TIdHTTP.Create(nil);
         LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
         // support SSL
         lHTTP.IOHandler:=LHandler;
     
         // les variables à renseigner
         tokenURL := 'grant_type=client_credentials&client_id=%s&client_secret=%s&scope=http://api.microsofttranslator.com';
     
         // creation TStringList avec renseignement des paramètres
         Ts.Add('grant_type=client_credentials');
         Ts.Add('client_id='+clientID);
         Ts.Add('client_secret='+clientSecret);
         Ts.Add('scope=http://api.microsofttranslator.com');
     
         // les entêtes
         lHTTP.Request.UserAgent := 'Mozilla/5.0 (compatible; Delphi)';
         lHTTP.Request.CustomHeaders.AddValue('Content-Type','application/x-www-form-urlencoded');
     
         // on poste le tout
         try
            lHTTP.Post(DatamarketAccessUri, Ts, ResPost);
            // on extrait le jeton
            SplitColumnsNoTrim(ResPost.DataString, Strings, ',');
            // le jeton se trouve sur la 2eme ligne du tableau : indice[1]
            sTemp := Strings[1];
            // on enlève le début de la chaine qui contient :'access_tonken:'
            delete(sTemp,1,16);
            // on enlève le dernier caractère contenant un guillemet
            delete(sTemp,length(sTemp),1);
            // on copie
            Result:=sTemp;
            // on démarre le compteur de temps
            VarTimeStart := now;
         finally
            lHTTP.Free;
         end;
     
    end;
    //==============================================================================
    // Fonction de traduction :
    // paramètres d'entrée :
    // - sToken : jeton d'accès valable 10 minutes
    // - sText : texte à traduire
    // - sFrom : langue origine
    // - sTo : langue souhaitée
    // paramètre de retour :
    // - string : texte traduit
     
    function Translator_Translate(sToken,sText,sFrom,sTo:Widestring):Widestring;
    const
      // Adresse du traducteur
      TranslatorAccessUri = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?Text=%s&From=%s&To=%s';
    var
      lHTTP: TIdHTTP;
      LHandler: TIdSSLIOHandlerSocketOpenSSL;
      sURL:string;
      sTemp:Widestring;
    begin
         // on crée le composant + support SSL
         lHTTP := TIdHTTP.Create(nil);
         LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
         lHTTP.IOHandler:=LHandler;
     
         // pour authentification
         lHTTP.Request.CustomHeaders.Add('Authorization: Bearer '+sToken);
     
         // formatage chaine d'envoi
         sURL := lHTTP.URL.PathEncode(Format(TranslatorAccessUri,[sText,sFrom,sTo]));
     
         // on appelle l'url de traduction
         try
            sTemp := lHTTP.Get(sURL);
            // on enlève le début de la chaine qui contient la chaine XML
            delete(sTemp,1,68);
            // on enlève les derniers caractères contenant la chaine XML
            delete(sTemp,length(sTemp)-8,9);
            // on copie
            Result:=sTemp;
         finally
            lHTTP.Free;
         end;
    end;
    //==============================================================================
    // Fonction checktime, on vérifie que les 10" ne soient pas écoulées
    // paramètres d'entrée :
    // - aucun
    // paramètre de retour :
    // - boolean : vrai si temps pas écoulé
    procedure CheckTokenTime;
    var  ActualTime:TDateTime;
         nTime:integer;
    begin
         if VarTimeStart=0 then  tokenAccess := Translator_GetToken() // on récupère un jeton
         else
         begin
              ActualTime:=now;
              nTime := trunc((frac(ActualTime) - frac(VarTimeStart)) * 24 * 60 * 60);
              if nTime > 580 then tokenAccess := Translator_GetToken(); // on récupère un jeton
         end;
    end;
    //==============================================================================
    // Fonction de traduction
    // paramètres d'entrée :
    // - sText : Texte à traduire
    // - sFrom : langue origine
    // - sTo : langue cible
    // paramètre de retour :
    // - string : texte traduit
    function ExTraduitTexteDLLTraducteur(sText,sFrom,sTo:Widestring):Widestring;stdcall;
    var R:widestring;
    begin
       // on initialise le token
       CheckTokenTime;
       // on traduit et on renvoie
       R := Translator_Translate(tokenAccess,sText,sFrom,sTo);
       Result:=Utf8ToWidestring(R);
     
     
    end;
    //==============================================================================
    //Fonction exportée d'initialisation des variables des champs identificateurs
    function ExInitDLLTraducteur(sclientSecret,sclientID:string):boolean;stdcall;
    begin
       Result:=false;
       if (sclientID = '') or (sclientSecret = '') then exit;
     
       clientID := sclientID;
       clientSecret := sclientSecret;
       Result:=true;
    end;
     
    end.
    Fichiers attachés Fichiers attachés

  2. #2
    Membre confirmé

    Inscrit en
    Novembre 2002
    Messages
    749
    Détails du profil
    Informations forums :
    Inscription : Novembre 2002
    Messages : 749
    Points : 500
    Points
    500
    Par défaut
    salut,

    Pour les gens intéressés,

    Voici une solution, fonctionnelle. Pour l'utiliser vous devez recupérer une clé d'utilisation du translator de chez microsoft. Voir le site dans le code.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
     
    unit DLLUTraducteur;
     
    interface
     
    uses Classes,SysUtils,IdHTTP,IdTCPConnection,IdSSLOpenSSL,StrUtils,IdGlobal,
         HTTPApp,WinInet,DateUtils,XMLDoc,XMLIntf,WideStrUtils,MSXML,ComObj;
     
    function ExTraduitTexteDLLTraducteur(sIDClient,sText,sFrom,sTo:Widestring):widestring;stdcall;
     
    implementation
     
    // exports des 2 fonctions
    Exports ExTraduitTexteDLLTraducteur Name 'ExTraduitTexteDLLTraducteur';
     
     
    //==============================================================================
    // Fonction de traduction :
    // paramètres d'entrée :
    //   - sIDClient : Clé client à récupérer chez  "https://api.datamarket.azure.com/Bing/"
    //   - sText     : texte à traduire
    //   - sFrom     : langue origine
    //   - sTo       : langue souhaitée
    // paramètre de retour :
    //   - string : texte traduit
    function Translator_Translate(sIDClient,sText,sFrom,sTo:string):string;
    const TranslatorAccessUri = 'https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=%s&From=%s&To=%s';
    var
      lHTTP: TIdHTTP;
      LHandler: TIdSSLIOHandlerSocketOpenSSL;
      sURL:string;
      sBuffer:unicodestring;
      responseStream : TStringStream;
      p:integer;
    begin
         // on crée le composant + support SSL
         lHTTP := TIdHTTP.Create(nil);
         LHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
         lHTTP.IOHandler:=LHandler;
         responseStream := TStringStream.Create('', TEncoding.UTF8);
     
         // pour authentification
         lHTTP.Request.ContentType := 'text/xml; charset=UTF-8';
         lHTTP.Request.ContentEncoding := 'UTF-8';
         lHTTP.HTTPOptions := [hoForceEncodeParams];
         lHTTP.Request.CharSet := 'UTF-8';
         lHTTP.Request.BasicAuthentication := true;
         lHTTP.Request.UserName := sIDClient;
         lHTTP.Request.Password := sIDClient;
     
         // formatage chaine d'envoi
         sText:=HTTPEncode(UTF8Encode(sText));
         sFrom:=HTTPEncode(sFrom);
         sTo:=HTTPEncode(sTo);
         sURL := Format(TranslatorAccessUri,['%27'+sText+'%27','%27'+sFrom+'%27','%27'+sTo+'%27']);
     
         lHTTP.Get(sURL,responseStream);
         sBuffer:=responseStream.DataString;
     
         p:=pos('<d:Text m:type="Edm.String">',sBuffer);
         p:=p+length('<d:Text m:type="Edm.String">')-1;
         delete(sBuffer,1,p);
         p:=pos('</d:Text></m:properties></content></entry></feed>',sBuffer);
         delete(sBuffer,p,length('</d:Text></m:properties></content></entry></feed>'));
     
         // on libere
         lHTTP.Free;
         Result:=sBuffer;
    end;
    //==============================================================================
    // Fonction de traduction
    // paramètres d'entrée :
    //   - sText : Texte à traduire
    //   - sFrom : langue origine
    //   - sTo : langue cible
    //paramètre de retour :
    //  - Widestring : texte traduit
    function ExTraduitTexteDLLTraducteur(sIDClient,sText,sFrom,sTo:Widestring):Widestring;stdcall;
    begin
      // on traduit et on renvoie
      Result := Translator_Translate(sIDClient,sText,sFrom,sTo);
    end;
    //==============================================================================
     
    end.
    Merci pour le développement de la DLL par : REMY COUSINIE

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 17/12/2010, 14h14
  2. Cherche logiciel de traduction en ligne de commande windows
    Par maxeur dans le forum Scripts/Batch
    Réponses: 7
    Dernier message: 13/07/2010, 09h56
  3. Application de traduction en ligne
    Par gege2061 dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 1
    Dernier message: 23/11/2009, 14h01
  4. Site de Traduction en ligne
    Par goldorax113 dans le forum Dépannage et Assistance
    Réponses: 9
    Dernier message: 25/10/2006, 21h24

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo