Using Google Translate

From Lazarus wiki
Revision as of 09:38, 27 August 2013 by BigChimp (talk | contribs)
Jump to navigationJump to search

Overview

Google Translate has several front ends. If you want to translate many texts you have to pay and get a key.

https://developers.google.com/translate/v2/getting_started

Simple example for casual translations

This example demonstrats how to query the translator via the TFPHTTPClient and parsing the first array of the returned JSON. Even though this example is written using Lazarus, it can be easily adapted for use with FPC.

uses
  lazlogger, fpjson, fphttpclient, HTTPDefs;

function DownloadText(const URL: string): TStrings;
var
  client: TFPHTTPClient;
  doc: TStringList;
begin
  Result:=nil;
  doc:=TStringList.Create;
  client:=TFPHTTPClient.Create(nil);
  try
    client.Get(URL,doc);
    Result:=doc;
    doc:=nil;
  finally
    doc.Free;
    client.Free;
  end;
end;

function AskGoogleTranslate(OriginalText, SourceLang, TargetLang: string;
  out TranslatedText, ErrorMessage: string): boolean;
var
  doc: TStrings;
  URL: String;
  JSON: String;
  p: PChar;
  i: Integer;
  StartPos: PChar;
  Line: TJSONStringType;
  Level: Integer;
begin
  Result:=false;
  ErrorMessage:='';
  TranslatedText:='';
  if (SourceLang='') or (TargetLang='') then begin
    ErrorMessage:='missing language parameter';
    exit;
  end;
  if OriginalText='' then exit;

  // download JSON
  URL:='http://translate.google.com/translate_a/t?client=t'
    +'&text='+HTTPEncode(OriginalText)
    +'&sl='+SourceLang
    +'&tl='+TargetLang
    +'&sc=1'
    +'&ssel=0&tsel=0'
    +'&ie=UTF-8&oe=UTF-8'
    ;
  try
    doc:=DownloadText(URL);
  except
    on E: Exception do begin
      debugln(['AskGoogleTranslate failed URL=',URL,' Error=',E.Message]);
      ErrorMessage:='query failed: '+E.Message;
      exit;
    end;
  end;
  try
    // parse JSON
    // For example:
    //  [[["Erster Satz . ","First sentence.","",""],["Zweiter Satz . ","Second sentence.","",""]],
    JSON:=doc.Text;
    p:=PChar(JSON);
    Level:=0;
    i:=0;
    repeat
      case p^ of
      #0: break;
      '[':
        begin
          inc(Level);
          i:=0;
        end;
      ']':
        begin
          dec(Level);
          if Level=1 then break;
        end;
      ',':
        inc(i);
      '"':
        begin
          inc(p);
          StartPos:=p;
          repeat
            case p^ of
            #0,'"': break;
            '\':
              begin
                inc(p);
                if p^=#0 then break;
              end;
            end;
            inc(p);
          until false;
          if i=0 then begin
            Line:=JSONStringToString(copy(JSON,StartPos-PChar(JSON)+1,p-StartPos));
            TranslatedText:=TranslatedText+Line;
          end;
          if p^=#0 then break;
        end;
      end;
      inc(p);
    until false;
  finally
    doc.Free;
  end;
  Result:=true;
end;

// here is an example how to translate English(en) to German(de)
procedure TForm1.Button1Click(Sender: TObject);
var
  ErrorMessage: string;
  TranslatedText: string;
begin
  if not AskGoogleTranslate('First sentence. Second sentence.','en','de',TranslatedText,ErrorMessage)
  then begin
    debugln(['AskGoogleTranslate failed: ',ErrorMessage]);
  end else begin
    debugln(['TForm1.FormCreate Translation: ',TranslatedText]);
  end;
end;