GoLang

From Code Trash
Jump to: navigation, search

OCR in Golang Version 2


//go get -u cloud.google.com/go/vision/apiv1
//check the imagefromuri in google vision apiv1
//set GOOGLE_APPLICATION_CREDENTIALS=C:\dev\go\jach-ocr-gcp-be4a172c9cda.json
package main

import (
	"fmt"
	"net"
	"os"
    "bytes"
    "time"
    "strings"
    "regexp"
    "strconv"
    "encoding/base64"
    "encoding/json"
    "image"
    _ "image/jpeg"
    _ "image/png"
    "image/jpeg"
    "context"
    "reflect"
    
    vision "cloud.google.com/go/vision/apiv1"
)

const cHost = "127.0.0.1"
const cPort = "8080"
const cType = "tcp"
const tFilename = "captcha-image-temp.jpg";

func main() {
	fmt.Println("\nStarting server ...")

	con, err := net.Listen(cType, cHost+":"+cPort)
	if err != nil {
		fmt.Println("Unable to listen " + err.Error())
		os.Exit(1)
	}
	defer con.Close()

	for {
        fmt.Println("Waiting for incoming connection ...");
        
		c, err := con.Accept()
		if err != nil {
			fmt.Println("Error accepting incoming connection: ", err.Error());
			return;
		}
		fmt.Println("Client connected: " + c.RemoteAddr().String());
        
		readit(c);
	}
}

const BSIZE = 1024;

func readit(con net.Conn) {

    tbuff := make([]byte, BSIZE);
    var buff []byte;
    var tBytes uint32 = 0;
    
    for {
        nBytes, err := con.Read(tbuff);

        if err != nil {
            fmt.Println("ERR: " + err.Error());
            con.Close();
            return;            
        }

        tBytes += uint32(nBytes);
        
        if(nBytes < BSIZE) {
            tbuff = tbuff[0:nBytes];
            buff = append(buff, tbuff...);
            break;
        } else {
            buff = append(buff, tbuff...);
        }
    }
    
    rstr := prossit(buff);
    
    con.Write([]byte(rstr));
    con.Close();    
}

func prossit(buff []byte) (string){

    rstr := "";
    
    fmt.Println("Request:::::::::::::::\n", string(buff[:]));
 
    newline := bytes.LastIndex(buff, []byte("\r\n\r\n"));        
    newline += 4;        
    header := string(buff[:newline]);    
    
    if(strings.HasPrefix(string(header), "OPTIONS")) {
        rstr = "HTTP/1.1 204 No Content\r\n" + 
                "Date: " + time.Now().Format(time.RFC1123) + "\r\n" + 
                "Server: Apache/2.0.61 (Unix)\r\n" + 
                "Access-Control-Allow-Origin: *\r\n" + 
                "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n" + 
                "Access-Control-Allow-Headers: Content-Type\r\n" + 
                "Connection: Close\r\n\r\n";
    } else {
    
        re := regexp.MustCompile("Content-Length: (?P<digit>[0-9]+)");
        match := re.FindStringSubmatch(header);    
        fmt.Println(match);
        
        if len(match) > 1 {
            conlen, err := strconv.Atoi(match[1]); 
            if err != nil {
                fmt.Println(err.Error());
                return "";
            }
            fmt.Println(conlen);
        } else {
            fmt.Println("Match did not return 2");
            fmt.Println(match);
            return "";
        }

        ret := writeit(buff[newline:])
        if(ret != "") {
            keyv := make(map[string]string);
            keyv["convtext"] = ret;
            jsons, _ := json.Marshal(keyv);
            ret = string(jsons);
        } else {
            ret = "Unable to process. Try again later";
        }
        
        rstr = "HTTP/1.1 200 OK\r\n" + 
                "Content-Length: " + strconv.Itoa(len(ret)) + "\r\n" + 
                "Content-Type: plain/text\r\n" + 
                "Access-Control-Allow-Origin: *\r\n" + 
                "Connection: Close\r\n\r\n" + ret;                   
    }
    
    fmt.Println("Response string is:", rstr);

    return rstr;
}


func writeit(buff []byte) string {

    suff := bytes.Index(buff, []byte(";base64"));
    fmt.Println("suff is : ", suff);
    
    if(suff < 0) {
        fmt.Println("Invalid post data");
        return "";
    }
    
    nbuff := string(buff[23:]);
    ret := "";
    
    switch string(buff[5:suff]) {
        
        case "image/jpeg":
        
            reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(nbuff));
            img, dim, err := image.Decode(reader);
            if err != nil {
                fmt.Println(err);
            } else {
                fmt.Println("success", reflect.TypeOf(img), dim);
                
                fp, err := os.OpenFile(tFilename, os.O_WRONLY|os.O_CREATE, 0777);
                if(err == nil) {
                    jpeg.Encode(fp, img, nil);
                    fp.Close();
                    ret = visionapi(tFilename);
                }
            }            
            break;
        
        case "image/png":
            fmt.Println("PNG: Not implemented");            
            break;
            
        default:
            fmt.Println("Invalid image type");    
    }

    return ret;
}

func visionapi(filename string) string {
    
    ctx := context.Background()

    defer func() string {
        if err:= recover(); err != nil {
            fmt.Println(err);
        }
        return "";
    }();
    
    // Creates a client.
    client, err := vision.NewImageAnnotatorClient(ctx)
    if err != nil {
        panic("Failed to create client: " + err.Error())
    }
    defer client.Close()    
    
    file, err := os.Open(filename)
    if err != nil {
        panic("Failed to open file: " + filename + " - " + err.Error());
    }
    
    image, err := vision.NewImageFromReader(file);
    if err != nil {
        panic("Failed to create image from file: " + err.Error());
    }
    
    text, err := client.DetectTexts(ctx, image, nil, 10)
    if err != nil {
        panic("Failed to detect text: " + err.Error())
    }

    txt := strings.TrimSuffix(text[0].Description, "\n");
    fmt.Println("Text is: " + txt);
    
    return txt;
}


OCR golang Version 1

//go get -u cloud.google.com/go/vision/apiv1
//check the imagefromuri in google vision apiv1
package main

import (
	"fmt"
	"net"
	"os"
    "bytes"
    "time"
    "strings"
    "regexp"
    "strconv"
    "encoding/base64"
    "image"
    _ "image/jpeg"
    _ "image/png"
    "image/jpeg"
    "context"
    "reflect"
    
    vision "cloud.google.com/go/vision/apiv1"
)

const cHost = "127.0.0.1"
const cPort = "8080"
const cType = "tcp"

func main() {
	fmt.Println("\nStarting server ...")

	con, err := net.Listen(cType, cHost+":"+cPort)
	if err != nil {
		fmt.Println("Unable to listen " + err.Error())
		os.Exit(1)
	}
	defer con.Close()

	for {
        fmt.Println("Waiting for incoming connection ...");
        
		c, err := con.Accept()
		if err != nil {
			fmt.Println("Error accepting incoming connection: ", err.Error());
			return;
		}
		fmt.Println("Client connected: " + c.RemoteAddr().String());
        
		readit(c);
	}
}

const BSIZE = 1024;

func readit(con net.Conn) {

    tbuff := make([]byte, BSIZE);
    var buff []byte;
    var tBytes uint32 = 0;
    
    for {
        nBytes, err := con.Read(tbuff);

        if err != nil {
            fmt.Println("ERR: " + err.Error());
            con.Close();
            return;            
        }

        tBytes += uint32(nBytes);
        
        if(nBytes < BSIZE) {
            tbuff = tbuff[0:nBytes];
            buff = append(buff, tbuff...);
            break;
        } else {
            buff = append(buff, tbuff...);
        }
    }
    
    rstr := prossit(buff);
    
    con.Write([]byte(rstr));
    con.Close();    
}

func prossit(buff []byte) (string){

    rstr := "";
 
        newline := bytes.LastIndex(buff, []byte("\r\n\r\n"));        
        newline += 4;        
        header := string(buff[:newline]);    
    
    if(strings.HasPrefix(string(header), "OPTIONS")) {
        rstr = "HTTP/1.1 204 No Content\r\n" + 
                "Date: " + time.Now().Format(time.RFC1123) + "\r\n" + 
                "Server: Apache/2.0.61 (Unix)\r\n" + 
                "Access-Control-Allow-Origin: *\r\n" + 
                "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n" + 
                "Access-Control-Allow-Headers: Content-Type\r\n" + 
                "Connection: Close\r\n\r\n";
    } else {
    
        re := regexp.MustCompile("Content-Length: (?P<digit>[0-9]+)");
        match := re.FindStringSubmatch(header);    
        fmt.Println(match);
        
        if len(match) > 1 {
            conlen, err := strconv.Atoi(match[1]); 
            if err != nil {
                fmt.Println(err.Error());
                return "";
            }
            fmt.Println(conlen);
        } else {
            fmt.Println("Match did not return 2");
            fmt.Println(match);
            return "";
        }
        
        writeit(buff[newline:])
    
        rstr = "HTTP/1.1 200 OK\r\n" + 
                "Content-Length: 5\r\n" + 
                "Content-Type: plain/text\r\n" + 
                "Access-Control-Allow-Origin: *\r\n" + 
                "Connection: Close\r\n\r\n" + 
                "Hello";
    }

    return rstr;
}

func writeit(buff []byte) {

    suff := bytes.Index(buff, []byte(";base64"));
    nbuff := string(buff[23:]);
    
    switch string(buff[5:suff]) {
        
        case "image/jpeg":
        
            reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(nbuff));
            img, dim, err := image.Decode(reader);
            if err != nil {
                fmt.Println(err);
            } else {
                fmt.Println("success", reflect.TypeOf(img), dim);
                
                fp, err := os.OpenFile("chitta-temp.jpg", os.O_WRONLY|os.O_CREATE, 0777);
                if(err == nil) {
                    jpeg.Encode(fp, img, nil);
                    fp.Close();
                    visionapi("chitta-temp.jpg");
                }
            }
            
            break;
        
        case "image/png":
            fmt.Println("png");
            break;
            
        default:
            fmt.Println("invalid");    
    }    
}

func visionapi(filename string) {
    
    ctx := context.Background()
    
    // Creates a client.
    client, err := vision.NewImageAnnotatorClient(ctx)
    if err != nil {
        fmt.Println("Failed to create client: ", err)
        return;
    }
    defer client.Close()
    
    file, err := os.Open(filename)
    if err != nil {
        fmt.Println("Failed to open file: ", filename);
        return;
    }
    
    image, err := vision.NewImageFromReader(file);
    if err != nil {
        fmt.Println("Faied to create image from file: ", err);
        return;
    }
    
    text, err := client.DetectTexts(ctx, image, nil, 10)
    if err != nil {
        fmt.Println("Failed to detect text: ", err)
        return;
    }
    fmt.Println("Test is : ",text);
    
}


Content script

document.body.style.border = "2px solid red";

/*
var sam = document.getElementsByName('districtCode')[0];
for(var i=0; i<sam.options.length; i++)
    if(sam.options[i].text.toLowerCase().lastIndexOf('namakkal') + 1)
        alert(i);
*/


function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = 280;
   canvas.height = 70;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}  


function pageone() {

    document.getElementsByName('districtCode')[0].selectedIndex = 17;
    document.getElementsByName('areaType')[0].checked = true;
    document.forms['checkForm'].submit();
}

function pagetwo() {

    document.getElementsByName('talukCode')[0].selectedIndex = 5;
    document.getElementsByName('talukCode')[0].onchange();
    //window.getVillages(document.forms[0].districtCode.value,'02')
    window.setTimeout(function() { 
        document.getElementsByName('villageCode')[0].selectedIndex = 50;
        document.getElementsByName('viewOpt')[1].click();
        document.getElementsByName('viewOption')[1].click();
    }, 1000)
}

    if(document.getElementById('areaType')) {
        pageone();
    }
  
    if(document.getElementsByName('villageCode').length) {
        pagetwo();
        
        var imgobj = document.getElementById('captchaImg');
        console.log(imgobj);
        imgobj.addEventListener('load', function() { 
            
            var url = getDataUrl(imgobj);            
            var jax = new XMLHttpRequest();
            jax.open('POST', 'http://localhost:8080/');
            jax.setRequestHeader('Content-Type', 'text/plain');
            jax.send(url);
            jax.onreadystatechange = function() {
                if(jax.readyState == 4) {

                    try {
                        var obj = JSON.parse(jax.responseText);
                        if(obj.convtext)
                            document.getElementsByName('captcha')[0].value = obj.convtext;
                        console.log(jax.responseText);                                    
                    }catch(e) {
                        console.log(e);
                    }
                }
            }
        }, false)
    }
    

/*

function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}  

function selo() {
    var jax = new XMLHttpRequest();
            jax.open('post', 'http://localhost:8080/', false);
            jax.setRequestHeader('Content-Type', 'text/plain');
            jax.send(url);
            console.log(jax.responseText);
            console.log(JSON.parse(str));
}

var imgobj = document.getElementById('captchaImg');
var url = getDataUrl(imgobj);

var imgobj = document.getElementsByTagName('img')[0]; 
var url = getDataUrl(imgobj);

*/


Manifest

{

    "manifest_version": 2,
    "name": "Chitta Injection",
    "version": "1.0",

    "description": "Chitta injection.",

    "icons": {
        "48": "dogicon.png",
        "96": "dogicon.png"
    },

    "content_scripts": [
        {
            "matches": ["*://*.eservices.tn.gov.in/eservicesnew/land/*"],
            "js": ["cs.js"],
            "run_at": "document_end"
        }
    ],
    "permissions": [
        "http://*/"
    ],
    
    "browser_action": {
    "browser_style": true,
    "default_icon": {
        "16": "dogicon.png",
        "32": "dogicon.png"
        }
    },
    "background": {
        "scripts": ["background.js"]
    }    
}