Translating Languages In Delphi
Asked Answered
M

3

6

I have been looking for ages now for some code that can translate any language to another but none of the code I find works.
I know Google has a good translate API but I can't get anyone's Delphi code on it to work.
There is always an error that comes in the way. Any help would be much appreciated, I need a program that can translate ASAP of my final school project.

Metopic answered 19/9, 2011 at 19:40 Comment(2)
Could you show us what you have so far and we can help you solve the problems. We don't want to do your school project for you.Zhang
I think you should clarify your question. IMO, you are looking for code that performs a translation by calling a webservice, DLL, or other API to do the translation. "Code that can translate any language to another" probably requires a PhD in linguistics in addition to advanced CS skills.Vital
B
3

Maybe you did not find Marco Cantu's works?Works with REST/AJAX/Delphi

But as RRUZ said, the Google Translate API is only available now as a paid service.

Bundelkhand answered 20/9, 2011 at 1:34 Comment(4)
Thank you, this code looks very promising, more than google translate. The exe given works 100% on my pc but when i open the code and try to compile i get an error, i think i am missing a unit. It tells me that in "TIdUri.ParamsEncode (strIn)" ParamsEncode is an undeclared identifier. And it says the same about "PosEx" that comes up later.Metopic
Thank you, i just installed Delphi 7 and this code works perfectly. Its easier than Google's API anyway :)Metopic
@MichaelMcQuirk, be careful because the project listed in the marco cantu page uses a old version of the Google Language API Family which is deprecated.Quietism
Hey, as @Quietism said, Google is taking down some of the old API, and I am not sure how long this will work. So, besides I think this really answer your question, you should research more if you want use this. Edit: I've tested it in Delphi 7 and Delphi 2010 before and worked perfectly.Bundelkhand
Q
11

The Google Translate API is a good option, but now is available only as a paid service. Instead you can try the Microsoft Translator V2 API, check this article Using the Microsoft Translator V2 API from delphi for more details about how use this API from delphi.

UPDATE This is the same demo project of the article modified to be compatible with your version of delphi.

program MicrosoftTranslatorApi;

{$APPTYPE CONSOLE}

uses
  ShellApi,
  ActiveX,
  Classes,
  ComObj,
  Variants,
  Windows,
  WinInet,
  SysUtils;

const
   MicrosoftTranslatorTranslateUri = 'http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=%s&text=%s&from=%s&to=%s';
   MicrosoftTranslatorDetectUri    = 'http://api.microsofttranslator.com/v2/Http.svc/Detect?appId=%s&text=%s';
   MicrosoftTranslatorGetLngUri    = 'http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForTranslate?appId=%s';
   MicrosoftTranslatorGetSpkUri    = 'http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForSpeak?appId=%s';
   MicrosoftTranslatorSpeakUri     = 'http://api.microsofttranslator.com/v2/Http.svc/Speak?appId=%s&text=%s&language=%s';
   //this AppId if for demo only please be nice and use your own , it's easy get one from here http://msdn.microsoft.com/en-us/library/ff512386.aspx
   BingAppId                       = '73C8F474CA4D1202AD60747126813B731199ECEA';
   Msxml2_DOMDocument              = 'Msxml2.DOMDocument.6.0';

procedure WinInet_HttpGet(const Url: string;Stream:TStream);overload;
const
BuffSize = 1024*1024;
var
  hInter   : HINTERNET;
  UrlHandle: HINTERNET;
  BytesRead: DWORD;
  Buffer   : Pointer;
begin
  hInter := InternetOpen('', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(hInter) then
    try
      Stream.Seek(0,0);
      GetMem(Buffer,BuffSize);
      try
          UrlHandle := InternetOpenUrl(hInter, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
          if Assigned(UrlHandle) then
          begin
            repeat
              InternetReadFile(UrlHandle, Buffer, BuffSize, BytesRead);
              if BytesRead>0 then
               Stream.WriteBuffer(Buffer^,BytesRead);
            until BytesRead = 0;
            InternetCloseHandle(UrlHandle);
          end;
      finally
        FreeMem(Buffer);
      end;
    finally
     InternetCloseHandle(hInter);
    end;
end;

function WinInet_HttpGet(const Url: string): string;overload;
Var
  StringStream : TStringStream;
begin
  Result:='';
    StringStream:=TStringStream.Create('');
    try
        WinInet_HttpGet(Url,StringStream);
        if StringStream.Size>0 then
        begin
          StringStream.Seek(0,0);
          Result:=StringStream.ReadString(StringStream.Size);
        end;
    finally
      StringStream.Free;
    end;
end;

function TranslateText(const AText,SourceLng,DestLng:string):string;
var
   XmlDoc : OleVariant;
   Node   : OleVariant;
begin
  Result:=WinInet_HttpGet(Format(MicrosoftTranslatorTranslateUri,[BingAppId,AText,SourceLng,DestLng]));
  XmlDoc:= CreateOleObject(Msxml2_DOMDocument);
  try
    XmlDoc.Async := False;
    XmlDoc.LoadXML(Result);
    if (XmlDoc.parseError.errorCode <> 0) then
     raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);
    Node:= XmlDoc.documentElement;
    if not VarIsClear(Node) then
     Result:=XmlDoc.Text;
  finally
     XmlDoc:=Unassigned;
  end;
end;

function DetectLanguage(const AText:string ):string;
var
   XmlDoc : OleVariant;
   Node   : OleVariant;
begin
  Result:=WinInet_HttpGet(Format(MicrosoftTranslatorDetectUri,[BingAppId,AText]));
  XmlDoc:= CreateOleObject(Msxml2_DOMDocument);
  try
    XmlDoc.Async := False;
    XmlDoc.LoadXML(Result);
    if (XmlDoc.parseError.errorCode <> 0) then
     raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);
    Node:= XmlDoc.documentElement;
    if not VarIsClear(Node) then
      Result:=XmlDoc.Text;
  finally
     XmlDoc:=Unassigned;
  end;
end;

function GetLanguagesForTranslate: TStringList;
var
   XmlDoc : OleVariant;
   Node   : OleVariant;
   Nodes  : OleVariant;
   lNodes : Integer;
   i      : Integer;
   sValue : string;
begin
  Result:=TStringList.Create;
  sValue:=WinInet_HttpGet(Format(MicrosoftTranslatorGetLngUri,[BingAppId]));
  XmlDoc:= CreateOleObject(Msxml2_DOMDocument);
  try
    XmlDoc.Async := False;
    XmlDoc.LoadXML(sValue);
    if (XmlDoc.parseError.errorCode <> 0) then
     raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);
    Node:= XmlDoc.documentElement;
    if not VarIsClear(Node) then
    begin
      Nodes := Node.childNodes;
       if not VarIsClear(Nodes) then
       begin
         lNodes:= Nodes.Length;
           for i:=0 to lNodes-1 do
            Result.Add(Nodes.Item(i).Text);
       end;
    end;
  finally
     XmlDoc:=Unassigned;
  end;
end;

function GetLanguagesForSpeak: TStringList;
var
   XmlDoc : OleVariant;
   Node   : OleVariant;
   Nodes  : OleVariant;
   lNodes : Integer;
   i      : Integer;
   sValue : string;
begin
  Result:=TStringList.Create;
  sValue:=WinInet_HttpGet(Format(MicrosoftTranslatorGetSpkUri,[BingAppId]));
  XmlDoc:= CreateOleObject(Msxml2_DOMDocument);
  try
    XmlDoc.Async := False;
    XmlDoc.LoadXML(sValue);
    if (XmlDoc.parseError.errorCode <> 0) then
     raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);
    Node:= XmlDoc.documentElement;
    if not VarIsClear(Node) then
    begin
      Nodes := Node.childNodes;
       if not VarIsClear(Nodes) then
       begin
         lNodes:= Nodes.Length;
           for i:=0 to lNodes-1 do
            Result.Add(Nodes.Item(i).Text);
       end;
    end;
  finally
     XmlDoc:=Unassigned;
  end;
end;

procedure Speak(const FileName,AText,Lng:string);
var
  Stream : TFileStream;
begin
  Stream:=TFileStream.Create(FileName,fmCreate);
  try
    WinInet_HttpGet(Format(MicrosoftTranslatorSpeakUri,[BingAppId,AText,Lng]),Stream);
  finally
     Stream.Free;
  end;
end;

var
 lng       : TStringList;
 i         : Integer;
 FileName  : string;

begin
 try
    CoInitialize(nil);
    try
      Writeln(TranslateText('Hello World','en','es'));
      Writeln(DetectLanguage('Hello World'));

      Writeln('Languages for translate supported');
      lng:=GetLanguagesForTranslate;
      try
        for i:=0 to lng.Count-1 do
         Writeln(lng[i]);
      finally
        lng.free;
      end;

      Writeln('Languages for speak supported');
      lng:=GetLanguagesForSpeak;
      try
        for i:=0 to lng.Count-1 do
         Writeln(lng[i]);
      finally
        lng.free;
      end;

      FileName:=ExtractFilePath(ParamStr(0))+'Demo.wav';
      Speak(FileName,'This is a demo using the Microsoft Translator Api from delphi, enjoy','en');
      ShellExecute(0, 'open', PChar(FileName),nil,nil, SW_SHOWNORMAL) ;

    finally
      CoUninitialize;
    end;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.
Quietism answered 19/9, 2011 at 19:54 Comment(4)
Okay, for all those that want an example of the errors i am receiving, here is a case where i got 2 errors. (I'm referring to theroadtodelphi.wordpress.com/2011/05/30/… ) My first error i get when i try this code is that the class file "Generics.Collections" does not exist. I have googling a site that allows you to download the .pas file but i cant find any. The second error i get, i presume i get it because of the first error, is that on line 64 (full code at bottom of page) i get an error saying that there are to many actual parameters.Metopic
(continued) obviously the compiler does not know what TEncoding.UTF8 is. I asume it must be on the missing "Generics.Collections" file.Metopic
@MichaelMcQuirk it seems which you are using a old version of delphi, please include your version of delphi to help you.Quietism
@Quietism Please the link of Using the Microsoft Translator V2 API from delphi included in your answer.Transpire
B
3

Maybe you did not find Marco Cantu's works?Works with REST/AJAX/Delphi

But as RRUZ said, the Google Translate API is only available now as a paid service.

Bundelkhand answered 20/9, 2011 at 1:34 Comment(4)
Thank you, this code looks very promising, more than google translate. The exe given works 100% on my pc but when i open the code and try to compile i get an error, i think i am missing a unit. It tells me that in "TIdUri.ParamsEncode (strIn)" ParamsEncode is an undeclared identifier. And it says the same about "PosEx" that comes up later.Metopic
Thank you, i just installed Delphi 7 and this code works perfectly. Its easier than Google's API anyway :)Metopic
@MichaelMcQuirk, be careful because the project listed in the marco cantu page uses a old version of the Google Language API Family which is deprecated.Quietism
Hey, as @Quietism said, Google is taking down some of the old API, and I am not sure how long this will work. So, besides I think this really answer your question, you should research more if you want use this. Edit: I've tested it in Delphi 7 and Delphi 2010 before and worked perfectly.Bundelkhand
M
0

First of all, you can not find a 100% tool to translate from a language to another. You can have a tool which is doing some(more or less) of the job for you, but you need to 'polish' the rest. As RRUZ said, you can use the Microsoft's translator but what I've said applies also in this case. Any tool of this type will cost you money. Google's translate is quite good, but you need to pay for it.

PS: I don't think that at school they ask you to create a tool which is translating from any language to any language. Maybe a small tool which can prove you got the concept. just my 2 cents...

Moonlit answered 19/9, 2011 at 20:43 Comment(1)
Well, actually the project i have is that I need to make a program that can teach its user a new language. Using Google Translate's API is just one of the small(but very important) components of the program. Most of the project is done, I just need a way to translate text.Metopic

© 2022 - 2024 — McMap. All rights reserved.