wtorek, 25 września 2012

Parser mapa UKE + crawler


Poniżej zamieszczam kod źródłowy aplikacji, którą napisałem do parsowania danych z mapy UKE mapa.uke.gov.pl.





Struktura bazy MySQL

  mysql> explain mapa;
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| id             | int(20)      | NO   | PRI | NULL    |       |
| miejsce        | varchar(255) | NO   |     | NULL    |       |
| ogolem         | int(20)      | NO   |     | NULL    |       |
| indywidualni   | int(20)      | NO   |     | NULL    |       |
| biznesowi      | int(20)      | NO   |     | NULL    |       |
| t_ogolem       | int(20)      | NO   |     | NULL    |       |
| t_indywidualni | int(20)      | NO   |     | NULL    |       |
| t_biznesowi    | int(20)      | NO   |     | NULL    |       |
| op_int         | int(20)      | NO   |     | NULL    |       |
| op_tel         | int(20)      | NO   |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
10 rows in set (0.00 sec)


Plik func.php

  <?php

function polacz()
{
$dbname='uke';
$dbhost='localhost';
$dbuser='root';
$dbpass='pass';

        $link = mysql_connect($dbhost,$dbuser,$dbpass);
        mysql_select_db($dbname);
        return $link;
}

function tabulka($tabelka)
{
$dom = new DOMDocument();
//load the html
$html = $dom->loadHTMLFile($tabelka);

  //discard white space
$dom->preserveWhiteSpace = false;

  //the table by its tag name
$tables = $dom->getElementsByTagName('table');


    //get all rows from the table
$rows = $tables->item(0)->getElementsByTagName('tr');
  // get each column by tag name
$cols = $rows->item(0)->getElementsByTagName('th');
$row_headers = NULL;
foreach ($cols as $node) {
    //print $node->nodeValue."\n";
    $row_headers[] = $node->nodeValue;
}

$table = array();
  //get all rows from the table
$rows = $tables->item(0)->getElementsByTagName('tr');
foreach ($rows as $row)
{
   // get each column by tag name
    $cols = $row->getElementsByTagName('td');
    $row = array();
    $i=0;
    foreach ($cols as $node) {
        # code...
        //print $node->nodeValue."\n";
        if($row_headers==NULL)
            $row[] = $node->nodeValue;
        else
            $row[$row_headers[$i]] = $node->nodeValue;
        $i++;
    }
    $table[] = $row;
}
return $table;
//var_dump($table);
}



function spider($id){
//echo $id."\n";
$id_miejsca = explode("=",$id);
//echo $id_miejsca[1]."\n";
$intro = file_get_contents("$id");

$regex = '#\<div id="firstText"\>(.+?)\<div id="secondText">#s';  
preg_match($regex, $intro, $matches); // LICZBA ABONENTOW OGOLEM
$match = $matches[0];


$regex_io = '#\<td class="titleCell"  valign="top"\>(.+?)\<\/td\>#s';
preg_match($regex_io, $match, $matches_io);
$match_io = $matches_io[0];
$op_int = preg_replace('/[^0-9]/','', $match_io);
echo 'operatorzy'.$op_int;   // WYNIK - OPERATORZY INTERNET

echo "\n\n";

//echo $match;
$regex_f = '#\<td  class="cell" colspan="3"\>(.+?)\<\/table\>#s';  // LICZBA ABONENTOW OGOLEM
preg_match($regex_f, $match, $matches_f); // LICZBA ABONENTOW OGOLEM
$match_f = $matches_f[0];
//echo $match_f;   // WYNIK - PIERWSZA TABELA INTERNET

$regex_s = '#\<div id="secondText"\>(.+?)\<\/body\>#s';  
preg_match($regex_s, $intro, $matches_s); // LICZBA ABONENTOW OGOLEM
$match_s = $matches_s[0];
//echo 'DRUGI_DIV:'.$match_s;


$regex_io2 = '#\<td class="titleCell"  valign="top"\>(.+?)\<\/td\>#s';
preg_match($regex_io2, $match_s, $matches_io2);
$match_io2 = $matches_io2[0];
$op_int2 = preg_replace('/[^0-9]/','', $match_io2); // WYNIK - OPERATORZY TELEFONU


$regex_ts = '#\<td  class="cell" colspan="3"\>(.+?)\<\/table\>#s'; 
preg_match($regex_ts, $match_s, $matches_ts); // LICZBA ABONENTOW OGOLEM
$match_ts = $matches_ts[0]; // WYBIK DRUGA TABELA TELEFON


$tab = '<table><tr>'.$match_f;
$tab2 = '<table><tr>'.$match_ts;

$file = "/tmp/html.$id_miejsca[1]";
$file = trim($file);
system("echo '$tab' > $file");


$file2 = "/tmp/tel.$id_miejsca[1]";
$file2 = trim($file2);
system("echo '$tab2' > $file2");


$res = tabulka($file);
$res2 = tabulka($file2);
/
$ogol = $res[0][2];
$ind = $res[1][2];
$biz = $res[2][2];

$t_ogol = $res2[0][2];
$t_ind = $res2[1][2];
$t_biz = $res2[2][2];



$regex = '#\<div\>(.+?)\<\/div\>#s';//  ZWRACA GMINE/POWIAT
preg_match($regex, $intro, $matches); //  ZWRACA GMINE/POWIAT
$match = $matches[0];

$miejsce = explode("-",$match);
$miejscowosc =ltrim($miejsce[1]);
$miejscowosc = iconv("ISO-8859-2","UTF-8",$miejscowosc);
polacz();
$insert = "INSERT INTO mapa (id,miejsce,ogolem,indywidualni,biznesowi,t_ogolem,t_indywidualni,t_biznesowi,op_int,op_tel) values ('$id_miejsca[1]','$miejscowosc','$ogol','$ind','$biz','$t_ogol','$t_ind','$t_biz','$op_int','$op_int2')";
mysql_query($insert);
echo $insert."\n";
}


?>

Sitemap generator [CRAWLER]

Zbieranie linków ze strony WWW:
wget --spider --recursive --no-verbose --output-file=wgetlog.txt http://example.com sed -n "s@.\+ URL:\([^ ]\+\) .\+@\1@p" wgetlog.txt | sed "s@&@\&@" > sedlog.txt

Mirrorowanie strony:
wget --mirror --limit-rate=250k --wait=1 -erobots=off --no-parent --page-requisites --convert-links --no-host-directories --cut-dirs=2 --directory-prefix=DIR http://www.example.com/index.php

środa, 29 sierpnia 2012

Kolejki

Prosta kolejka w Asterisk

queues.conf

[CallCenter]
music=default
strategy=rrmemory
joinempty = yes
timeout=15
retry=1
wrapuptime=0
maxlen = 1
announce-frequency = 10
announce-holdtime = no
member => SIP/123,0
member => SIP/124,0



extensions.conf

exten => 13,1,Queue(CallCenter)


asterisk*CLI>

asterisk*CLI> queue show CallCenter
CallCenter has 0 calls (max 1) in 'rrmemory' strategy (5s holdtime, 18s talktime), W:0, C:2, A:0, SL:0.0% within 0s
   Members:
      SIP/124 (Not in use) has taken 1 calls (last was 281 secs ago)
      SIP/123 (Not in use) has taken 1 calls (last was 279 secs ago)
   No Callers

Jeśli chcesz aby tylko jeden SIP odbierał jedną rozmowę to koniecznie w sip.conf daj mu call-limit=1, wtedy  asterisk pokaże in use. 




piątek, 17 sierpnia 2012

Rozpoznawanie mowy przez Asterisk [Speech recognition]

Skonfigurowanie Asteriska tak aby zamieniał test na mowę mamy za sobą. Dzisiaj chciałbym zaprezentować kolejny skrypt AGI autora Lefteris Zafiris, który to pozwala zamieniać mowę na słowo pisane.

Potrzebne paczki:
Perl
perl-libwww

Instalacja samego AGI podobnie jak we wcześniejszym poście bardzo prosta i polega na skopiowaniu pliku 
speech-recog.agi do katalogu ze skryptami AGI w asterisku ( u mnie /usr/share/asterisk/agi-bin/ ). 

a w /etc/asterisk/extensions.conf przykładowo dla języka polskiego:

exten => 0,1,Answer()
exten => 0,n,agi(speech-recog.agi,pl-PL)
exten => 0,n,Verbose(1,The text you just said is: ${utterance})
exten => 0,n,Verbose(1,The probability to be right is: ${confidence})
exten => 0,n,Hangup()

wtorek, 14 sierpnia 2012

Asterisk syntezator mowy [Text to speech]

Chcesz aby Twój asterisk w końcu przemówił?
Wystarczy zastosować skrypt AGI, który przerobi nasz tekst na mowę dzięki usłudze Google Translate.

Co będzie potrzebne?
AGI stworzone przez Lefteris Zafiris, które można pobrać z tąd

Oraz trochę niezbędnego softu:
- perl
- perl-libwww
- sox
- mpg123


Cała instalacja jest naprawdę trywialna. Należy skopiować googletts.agi do katalogu ze skryptami AGI w asterisku ( u mnie /usr/share/asterisk/agi-bin/ ).

Została tylko edycja extensions.conf

exten => 4832XXXXXXX,1,Answer()
exten => 4832XXXXXXX,2,agi(googletts.agi,"Asterisk juz mowi.",pl)


Projekt asterisk-googletts: zaf.github.com/asterisk-googletts

poniedziałek, 13 sierpnia 2012

Instalacja dahdi - Debian


Przyszedł czas na MeetMe w Asterisku stojącym na Debianie, więc krótka notka dla tych, którzy mieli przyjemność spotkać się z:

app_meetme.c:1097 build_conf: Unable to open pseudo device


apt-get install dkms

wget http://downloads.digium.com/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz

tar zxvf dahdi-linux-complete-current.tar.gz 

make all
make install
make config
modprobe dahdi_dummy


to powinno załatwić wszystkie problemy ;)

-- Executing [4832XXXXXXX@incoming:1] MeetMe("SIP/black-00000036", "1234") in new stack

wtorek, 7 sierpnia 2012

Połączenie przychodzące do wielu kont SIP - Asterisk


W razie potrzeby skierowania połączenia przychodzącego do kilku  innych numerów (w tym przypadku 3 wewnętrznych kont SIP) można zastosować poniższe rozwiązanie

/etc/asterisk/extensions.conf


[global]
SIP_GROUP=SIP/100&SIP/101&SIP/102

[context]
exten => 1,n,Ringing
exten => 1,n,Wait(2)
exten => 1,n,Dial(${SIP_GROUP},60,r)


poniedziałek, 11 czerwca 2012

Logowanie na SSH przez PHP


Install: libssh2-1-dev libssh2-php
Source:


<?php
if (!function_exists("ssh2_connect")) die("funkcja ssh2_connect nie istnieje ");
// logowanie
if(!($con = ssh2_connect("192.168.15.214", 22))){
    echo "fail: NIE MOGE USTANOWIC POLACZENIA\n";
} else {
    // autentykacja
    if(!ssh2_auth_password($con, "root", "XxXx3")) {
        echo "fail: NIE MOGE POPRAWNIE ZALOGOWAC\n";
    } else {
        // jest OK
        echo "okay: ZALOGOWANO\n";

        // WYKONANIE KOMENDY
        if (!($stream = ssh2_exec($con, "ps -aux"))) {
            echo "fail: NIE MOGE WYKONAC POLECENIA\n";
        } else {
            stream_set_blocking($stream, true);
            $data = "";
//         $uf = fread($stream,4096);
//          echo $uf;
            while ($buf = fread($stream,4096)) {
                $data .= $buf;
echo $data;
            }
            fclose($stream);
        }
    }
}
?>