CodeIgniterの学習 57 - ヤフーの画像検索apiと形態素解析apiを組み合わせてお遊びアプリを作る-その2(現在のコード完成度25%)
一昨日のエントリー
「CodeIgniterでヤフーの画像検索apiと形態素解析apiを組み合わせてお遊びアプリを作ることにした」
の第二回目。
今日は取りあえず、単純な画像検索を出来るようにしてみる。
前回から10%くらい進捗。
(キャッシュ機構とか、DB格納とか、ページネーションとかはまだ。)
(動作環境とか、作りたい機能とかは一回目を参照のこと)
現在の画面
こんなかんじ。取りあえず画像が表示されるようになった。クリックすると元画像の載っているURLに飛ぶ。(画像直リンクではなく、画像のリファラ元に飛ばしている。)
もっとムフフな画像をのせたい所だけど、一応真面目路線なブログなので自重。
次は、ページネーション、キャッシュ機構、形態素解析(写真のコメントから単語を抽出)にとりかかる。
コード
前回とだいぶ変わった。全部貼っておく。ちなみにデータ取得部分は、
http://codeigniter.com/wiki/Curl_library/の
File:curl-library-1-1.zipのバグを修正して使っているのだが、
環境依存を避けるため、ここではfile_get_contents()に置き換えている。(俺はcurlが好きだからcurlを使う。)
1:コントローラ… application/controllers/yaimg.php
こんなかんじ。特に難しいところはない。
モデル内のquery_api()メソッド内で問い合わせを行い、
$this -> Mod_yaimg->get('image_result');で、結果を取得している。
<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); /** * Yahooの画像検索APIを使ってみるテスト */ /** * * @author : dix3 * @link : http://d.hatena.ne.jp/dix3/ */ class Yaimg extends Controller { // コンストラクタ function Yaimg() { parent :: Controller(); //親のコンストラクタを呼ぶ //$this -> load -> helper( array('form', 'html', 'text', 'string') ); //ヘルパのロード $this -> load -> helper( array( 'url','form', 'html', 'text', 'string','date' ) ); //ヘルパのロード //ライブラリのロード $this -> load -> library( 'form_validation' ); $this -> load -> library( 'lib_yaimg' ); $this -> load -> model( 'Mod_yaimg' ); //モデルのロード } // デフォルトインデックス function index() { $data = array(); $data = $this -> Mod_yaimg -> set_init_data(); //画面に固定値のデータをセット $data['result_body'] = array(); $data['result_msg'] = ''; // バリデーションのルール設定 $this -> form_validation -> set_rules( 'keyword', $this -> Mod_yaimg -> get( 'input_keyword_value' ), 'trim|required|min_length[2]|max_length[64]|xss_clean' ); // バリデーション処理の実行 if ( ( TRUE === $this -> form_validation -> run() ) && ( $this -> input -> post( 'keyword', true ) !== $this -> Mod_yaimg -> get( 'default_keyword' ) ) ) { // apiに接続して結果を取得する if($this -> Mod_yaimg -> query_api( array( 'keyword' => $this -> input -> post( 'keyword', true ) ) )){ $image_result = $this -> Mod_yaimg->get('image_result'); $data['result_body'] = $image_result['result'];//結果データ //todo:後でわかりやすい文字列にする $data['result_msg'] = 'total:'.$image_result['attributes']['total'].' position:'.$image_result['attributes']['position'].' count:'.$image_result['attributes']['count']; }else{ $data['result_body'] = array(); $data['result_msg'] = $this -> Mod_yaimg -> get( 'msg_no_result' ); } } $this -> load -> view( 'yaimg_index', $data ); //ビューにデータを渡す } } /** * End of file yaimg.php */ /** * Location: ./application/controllers/yaimg.php */ ?>
2:ビュー… application/views/yaimg_index.php
htmlヘルパの、img()と、urlヘルパのanchor()を使っている。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja"> <head> <title><?= $svs_title ?></title> <?= meta('Content-Type','text/html; charset=utf-8','http-equiv') ?> <?= meta('Content-language',$header_lang,'http-equiv') ?> <?= meta('Pragma','no-cache','http-equiv') ?> <?= meta('Cache-Control','no-cache','http-equiv') ?> <?= meta('Expires','Thu, 01 Dec 1994 23:59:59 GMT','http-equiv') ?> <?= meta('Distribution','Global') ?> <?= meta('Author','dix3') ?> <?= meta('Robots','index,nofollow') ?> <?= $header_js ?> <?= $header_css ?> </head> <body> <div> <?= heading($svs_description,3) ?> <?= form_open('yaimg') ?> <?= form_input(array('name'=>'keyword','style'=>'width:250px;','onclick'=>"javascript:this.value='';"),set_value('keyword',$default_keyword)) ?> <?= form_submit('submit',$submit_button_value) ?> <?= validation_errors('<div class="error">','</div>'); ?> <?php if($result_msg){ ?><div class='result_msg'><?= $result_msg ?></div><?php } ?> <?= form_close() ?> </div> <hr> <div class='result_body'> <?php foreach($result_body as $k => $v){ $img_tag = img(array('src'=>$v['thumbnail']['url'], 'style'=>"width:{$v['thumbnail']['width']};height:{$v['thumbnail']['height']};", 'title'=>$v['summary'].' '.$v['refererurl'].' '.$v['filesize'], 'alt'=>$v['title'], )); echo anchor($v['refererurl'],$img_tag,array('target'=>'_blank'))."\n"; } ?> </div> <?= $urchin_tag ?> </body> </html>
3:モデル… application/models/mod_yaimg.php
てきとう。いろいろ追加してたらこうなった。形態素解析の所はまだ呼び出されない。- apiに接続するパラメータを組み立てて、file_get_contents()でxmlデータを取得後、
- simplexml_load_string()でxmlをオブジェクトに変換し、
- その後、オブジェクトを配列に変換している。(オブジェクトが使いにくいから。配列万歳)
set() get() は、その場のふいんき(なぜか変換ry。ゆるゆるスクリプト言語万歳。
PHP5限定になっちゃった。まーいいや。
apiから取得できるパラーメータの仕様は、
このへん http://developer.yahoo.co.jp/webapi/search/imagesearch/v1/imagesearch.html
(昔と若干変わっているっぽいけど、取りあえず動くので、パラメータ等は後で精査する。まず動くところ迄なんとかもっていく。)
<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); /** * * @author : dix3 * @link : http://d.hatena.ne.jp/dix3/ */ class Mod_yaimg extends Model { var $mod_config; var $image_api_arr = array(); var $parse_api_arr = array(); var $image_result = array(); var $image_api_status = false; var $parse_api_status = false; // コンストラクタ function Mod_yaimg() { parent :: Model(); $this -> _init(); //初期化 } // 初期化 function _init() { $this -> load -> helper( 'html' ); $this -> load -> helper( 'yaimg' ); //$this -> load -> library( 'curl' ); //curlライブラリのロード $this -> load -> config( 'yaimg_config', true ); $this -> mod_config = $this -> config -> item( 'yaimg_config' ); } // 画面に固定値のデータをセット function set_init_data() { $arr = array( 'svs_title' , 'svs_description' , 'header_lang' , 'header_js' , 'header_css' , 'input_keyword_value', 'default_keyword' , 'submit_button_value' , 'urchin_tag', ); $data = array(); foreach( $arr as $v ) { $data[$v] = $this -> get( $v ); } return $data; } // 値取得 function get( $v ) { switch ( $v ) { case 'header_js': return header_js( $this -> _get_mod_config( $v ) ); //yaimgヘルパのheader_jsタグ break; case 'header_css': return link_tag( $this -> _get_mod_config( $v ) ); //htmlヘルパのlink_tag break; case 'urchin_tag': return $this -> _get_urchin_tag(); //urchinタグ break; case 'image_api_arr': return $this -> image_api_arr; //画像取得結果の配列 break; case 'parse_api_arr': return $this -> parse_api_arr; //形態素解析取得結果の配列 break; case 'image_result': return $this -> image_result; //画像取得結果を扱いやすい形に変換した配列 break; case 'image_api_status': return $this -> image_api_status; //画像検索結果の取得件数有り真偽 break; case 'parse_api_status': return $this -> parse_api_status; // 形態素解析検索結果の取得件数有り真偽 break; default: return $this -> _get_mod_config( $v ); //configファイルの設定値 break; } } // configファイルから設定値を読みとる function _get_mod_config( $v ) { $v = strtoupper( $v ); return isset( $this -> mod_config[$v] ) ? $this -> mod_config[$v] : ''; } // 画像取得結果の配列をセット function _set_image_api_arr( $arr = array() ) { if ( is_array( $arr ) ) { $this -> image_api_arr = $arr; } } // 形態素解析取得結果の配列をセット function _set_parse_api_arr( $arr = array() ) { if ( is_array( $arr ) ) { $this -> parse_api_arr = $arr; } } // 画像検索結果の戻り値を扱いやすい形に加工してセットする function _set_image_result() { $arr = $this -> get( 'image_api_arr' ); if ( isset( $arr['@attributes'] ) ) { $ret['attributes']['total'] = $arr['@attributes']['totalresultsavailable']; $ret['attributes']['count'] = $arr['@attributes']['totalresultsreturned']; $ret['attributes']['position'] = $arr['@attributes']['firstresultposition']; $ret['result'] = isset( $arr['result'] ) ? $arr['result'] : array(); if ( ( int ) $ret['attributes']['total'] > 0 ) { $this -> _set_image_api_status( TRUE ); //取得件数有り真偽 }else { $this -> _set_image_api_status( FALSE ); //取得件数有り真偽 } }else { $ret['attributes']['total'] = ''; $ret['attributes']['count'] = ''; $ret['attributes']['position'] = ''; $ret['result'] = array(); $this -> _set_image_api_status( FALSE ); //取得件数有り真偽 } $this->image_result = $ret; } // 画像検索結果の取得件数有り真偽をセット function _set_image_api_status( $flg ) { $this -> image_api_status = ( $flg ) ? TRUE : FALSE ; } // 形態素解析検索結果の取得件数有り真偽をセット function _set_parse_api_status( $flg ) { $this -> parse_api_status = ( $flg ) ? TRUE : FALSE ; } // apiに接続して結果を取得する function query_api( $params = array() ) { $keyword = isset( $params['keyword'] ) ? $this -> input -> xss_clean( strip_tags( $params['keyword'] ) ) : ''; $sentence = ''; if ( $keyword ) { $this -> _query_image_api( $keyword ); //画像検索apiに接続 } if ( $sentence ) { $this -> _query_parse_api( $sentence ); //形態素解析apiに接続 } return $this->get('image_api_status');//画像が見つかったらtrue } // 画像検索apiに接続して結果を取得する function _query_image_api( $keyword = '' ) { if ( !( $url = $this -> _get_ya_url( 'image_api', $keyword ) ) ) { return array(); } usleep( 5000 );//連続してつながないようにウエイトが必要 //$data = $this -> curl -> get( $url ); //curlライブラリ経由でリクエストを投げレスポンスデータを取得 $data = file_get_contents($url); if ( $data ) { $obj = @simplexml_load_string( $data ); //xmlのパース // 取り回しが面倒なので配列に変換 $this -> _set_image_api_arr( $this -> _convert_obj_to_arr( $obj ) ); } // 画像検索結果の戻り値を扱いやすい形に加工してセットする $this ->_set_image_result(); } // 面倒なのでオブジェクトを再帰的に配列に変換 function _convert_obj_to_arr( $p ) { if ( is_object( $p ) ) { $ret = array(); $arr = get_object_vars( $p ); foreach( $arr as $k => $v ) { $key = strtolower( $k ); //キーは小文字で統一 if(empty($v)){ $ret[$key] =''; }else{ $ret[$key] = $this -> _convert_obj_to_arr( $v ); } } }elseif ( is_array( $p ) ) { $ret = array(); foreach( $p as $k => $v ) { $key = strtolower( $k ); //キーは小文字で統一 if(empty($v)){ $ret[$key] =''; }else{ $ret[$key] = $this -> _convert_obj_to_arr( $v ); } } }else { $ret = $p; } return $ret; } // 形態素解析apiに接続して単語をばらした結果を配列で取得する function _query_parse_api( $sentence = '' ) { $ret = false; if ( !( $url = $this -> _get_ya_url( 'parse_api', $sentence ) ) ) { return $ret; } usleep( 5000 );//連続してつながないようにウエイトが必要 //$data = $this -> curl -> get( $url ); //curlライブラリ経由でリクエストを投げレスポンスデータを取得 $data = file_get_contents($url); if ( $data ) { $obj = @simplexml_load_string( $data ); //xmlのパース $regexp_ng1 = '#'.$this -> get( 'ng_parse_word1' ).'#iu'; $w = preg_quote( str_replace( ',', '|', rtrim( trim( $this -> get( 'ng_parse_word2' ), ',' ) ) ) ); $regexp_ng2 = "#^({$w})$#iu"; // レスポンスデータの分解 if ( isset( $obj -> uniq_result -> word_list -> word ) ) { $arr = array(); foreach( $obj -> uniq_result -> word_list -> word as $v ) { if ( $v -> count < 1 ) { continue; } if ( preg_match( $regexp_ng1, $v -> surface ) ) { continue; //不要な単語を除外 } if ( preg_match( $regexp_ng2, $v -> surface ) ) { continue; //不要な単語を除外 } $this -> _set_parse_api_arr( array( "sentence" => $v -> surface, "count" => $v -> count, "pos" => $v -> pos ) ); $ret = true; } } } return $ret; } // URLの組み立て function _get_ya_url( $ptn, $str ) { if ( !$str ) { return ''; } $str = $this -> input -> xss_clean( strip_tags( $str ) ); $appid = $this -> get( 'appid' ); switch ( $ptn ) { case 'parse_api':// 形態素解析用URLの組み立て $enc_str = urlencode( mb_substr( $str , 0, 1016 ) ); $url = $this -> get( 'parse_api_url' ); $url = str_replace( '%appid%', $appid, $url ); $url = str_replace( '%sentence%', $enc_str, $url ); return $url; break; case 'image_api':// 画像検索用URLの組み立て $enc_str = urlencode( $str ); $url = $this -> get( 'image_api_url' ); $url = str_replace( '%appid%', $appid, $url ); $url = str_replace( '%keyword%', $enc_str, $url ); $site_lock_url_list = $this -> get( 'site_lock_url_list' ); //検索対象のURLを限定 if ( $site_lock_url_list ) { $s_arr = explode( ',', trim( str_replace( ' ', '', $site_lock_url_list ) ) ); $image_api_site_lock_url = '&site=' . implode( '&site=', $s_arr ); $url = str_replace( '%image_api_site_lock_url%', $image_api_site_lock_url, $url ); } $arr = array( 'image_api_adult_ok', 'image_api_similar_ok', 'image_api_language', 'image_api_country', 'image_api_results_count', 'image_api_startpage_num', ); foreach( $arr as $v ) { $url = str_replace( "%{$v}%", $this -> get( $v ), $url ); } // echo($url); return $url; break; default: return ''; break; } } // google-analyticsのタグを取得 function _get_urchin_tag() { $uacct_no = $this -> get( 'uacct_no' ); if ( !$uacct_no ) { return ''; } $ret = <<<___END___ <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("{$uacct_no}"); pageTracker._trackPageview(); </script> ___END___; return $ret; } } //endofclass /** * End of file mod_yaimg.php */ /** * Location: ./application/models/mod_yaimg.php */ ?>
4:ライブラリ… application/libraries/lib_yaimg.php
まだ何もない。前回と変わらず。<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); /* * @author: dix3 * @link : http://d.hatena.ne.jp/dix3/ */ class Lib_yaimg { function Lib_yaimg() { } } //endofclass /** * End of file lib_yaimg.php */ /** * Location: ./application/libraries/lib_yaimg.php */ ?>
5:ヘルパー… application/helpers/yaimg_helper.php
ヘッダのjavascriptを読みこむ用。前回と変わらず。<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); /* * @author: dix3 * @link : http://d.hatena.ne.jp/dix3/ */ if ( ! function_exists( 'header_js' ) ) { // scriptの読み込みタグ生成 // 例: header_js('js/hogehoge.js');で // <script src="js/hogehoge.js" type="text/javascript"></script> // を作る function header_js( $src_str = '', $charset = '' ) { $ret = ''; if ( $src_str ) { if ( $charset ) { $cstr = ' charset="' . $charset . '" ' ; }else { $cstr = '' ; } $ret .= '<script language="javascript" type="text/javascript" src="' . $src_str . '"' . $cstr . "></script>\n"; } return $ret; } } /* End of file yaimg_helper.php */ /* Location: ./application/helpers/yaimg_helper.php */ ?>
6:設定ファイル… application/config/yaimg.php
可変の設定値部分を外部に切り出した。前回から大幅に追加変更有り。
appidはやふーで調べて取ってください。これを取らないと動きません。
(使える条件がいろいろ書いているので要チェック。
俺もまだ開発途中なので画面上にヤフーのリンクとか貼ってない。)
詳細はここ http://developer.yahoo.co.jp/webapi/search/imagesearch/v1/imagesearch.html
<?php if ( ! defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); /** * * @author : dix3 * @link : http://d.hatena.ne.jp/dix3/ */ $config['SVS_TITLE'] = 'ヤフー画像検索 WEBAPIテスト'; //タイトル $config['SVS_NAME'] = 'yaimg_search'; //サービス名 $config['SVS_DESCRIPTION'] = 'ヤフー画像検索と形態素解析の実験'; //ページタイトル $config['HEADER_LANG'] = 'ja'; //Content-language $config['HEADER_JS'] = 'js/yaimg.js'; //javascriptの相対パス $config['HEADER_CSS'] = 'css/yaimg.css'; //cssの相対パス $config['INPUT_KEYWORD_VALUE'] = 'キーワード'; //キーワード欄の名称 $config['SUBMIT_BUTTON_VALUE'] = 'ぽちっとな!画像検索'; //サブミットボタン名 $config['DEFAULT_KEYWORD'] = 'なんかいれて'; //キーワード欄のデフォルト値 $config['UACCT_NO'] = ''; //google-analyticsのurchinのタグ // yahooのアプリケーションID appid(自分で取得する) $config['APPID'] = ''; //yahooのappid(自分でとる) // API接続URLのテンプレート // yahooの形態素解析apiのURL #$config['PARSE_API_URL'] = 'http://api.jlp.yahoo.co.jp/MAService/V1/parse?appid=%appid%&results=uniq&uniq_filter=9&sentence=%sentence%'; $config['PARSE_API_URL'] = 'http://jlp.yahooapis.jp/MAService/V1/parse?appid=%appid%&results=uniq&uniq_filter=9&sentence=%sentence%'; // yahooの画像検索apiのURL #$config['IMAGE_API_URL'] = 'http://api.search.yahoo.co.jp/ImageSearchService/V1/imageSearch?appid=%appid%&query=%keyword%&adult_ok=%image_api_adult_ok%&similar_ok=%image_api_similar_ok%&language=%image_api_language%&country=%image_api_country%%image_api_site_lock_url%&results=%image_api_results_count%&start=%image_api_startcount_num%'; $config['IMAGE_API_URL'] = 'http://search.yahooapis.jp/ImageSearchService/V1/imageSearch?appid=%appid%&query=%keyword%&adult_ok=%image_api_adult_ok%&similar_ok=%image_api_similar_ok%&language=%image_api_language%&country=%image_api_country%%image_api_site_lock_url%&results=%image_api_results_count%&start=%image_api_startcount_num%'; // 画像検索APIのパラメータ $config['IMAGE_API_ADULT_OK'] = '1'; //アダルト OK:1,NG:0 $config['IMAGE_API_SIMILAR_OK'] = '1'; //SIMILAR OK:1,NG:0 $config['IMAGE_API_LANGUAGE'] = 'ja'; //言語 ja $config['IMAGE_API_COUNTRY'] = 'ja'; //国 ja $config['IMAGE_API_RESULTS_COUNT'] = '50'; //一回の問い合わせのデータ取得件数 $config['IMAGE_API_START_NUM'] = '1'; //検索結果のn番目から表示 $config['SITE_LOCK_URL_LIST'] = ''; //画像検索を特定のサイト内に限定するときに指定 // $config['SITE_LOCK_URL_LIST'] = 'hatena.ne.jp,example.com';//画像検索を特定のサイト内に限定するときに指定。カンマ区切りで複数指定可 // 形態素解析での抽出対象外ワード、正規表現で指定 $config['NG_PARSE_WORD1'] = '[-+_0-9\s0123456789]+'; // 形態素解析での抽出対象外ワード、カンマ区切りで指定 $config['NG_PARSE_WORD2'] = '上記,別,名前,名無し,投稿,片手,クリック,サイト,ジャンプ,リンク,http,www,sage,jpg,日,月,火,水,木,金,先週,今週,来週,版,先月,今月,来月,archives,net,jump,img,ttp,this,is,of,on,a,it,set,let,open,close,parent,document,javascript,the,she,he,its,get,あ,い,す,氏,用'; //合致したデータが無いときのメッセージ $config['MSG_NO_RESULT'] = '該当するデータは見つかりませんでした。'; /** * End of file yaimg.php */ /** * Location: ./application/config/yaimg.php */ ?>
7:javascriptファイル… ドキュメントルート/js/yaimg.js
前回と変わらず。(hogeは動作確認用ダミー。)//@author : dix3 //@url : http://d.hatena.ne.jp/dix3 var hoge=function(){ try{ window.alert('hoge'); }catch(e){ window.alert(e); } }
8:cssファイル… ドキュメントルート/css/yaimg.css
少し変更。/* author : dix3 */ /* link : http://d.hatena.ne.jp/dix3/ */ body{ color:#fff; background:#111; } hr { color:#eeeeee; height:1px; } h1,h2,h3{ font-size:1em; } a, a:visited { color: #111; border:1px solid #fff; text-decoration: none; } a:hover { color: #ffd700; background: inherit; } .error{ background:#ff0000; color:#fff; padding:3px; font-weight:bold; display:inline; } .result_msg{ background:#ffd700; color:#111; padding:3px; font-weight:bold; display:inline; } .result_body{ text-decoration: none; margin:20px 0 0 0; padding:5px; } .result_body a:link, .result_body a:visited, .result_body a:hover, .result_body a:active{ border:0px; } img{ border:2px solid #111; } img:hover{ border:2px solid #ffd700; }
だんだんそれっぽくなってきた。
基本はただのPHPなので、CodeIgniterらしさのようなものは目立たないかもしれない。だがそれでいいのだ。
つづく。
(08/12/27一部ヘルパとライブラリのロード部分ソース記述訂正)
誤)
$this->load->helper('hoge','fuga','moga');
↓
正)
$this->load->helper(array('hoge','fuga','moga'));
誤)
$this->load->library('aaa','bbb');
↓
正)
$this->load->library('aaa'); $this->load->library('bbb');
に訂正
(訂正終わり)
09/02/22 一部修正
- ヘルパのロードに 'url','date'を追加(autoloadで読みこんでいたため)
- cssに img , img : hover 追加