2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Bing Video Search API + vue + axiosで動画検索を導入

Last updated at Posted at 2020-01-07

はじめに

Azure Cognitive Servicesのサービスに知らないものが増えてたので気になったものを使ってみることにしました。
まずはBing Video Search APIから

ゴール

入力されたキーワードに沿った動画を検索して表示します。
『制限つき』となっているのは(詳細は後述しますが)"成人向け" の結果をフィルターで除外するパラメータ指定になります。
Art016.jpg

Bing Video Search APIは
Azure >> Cognitive Services >> Search >> Bing Video Search
と言うカテゴリになるようです。順に...

Microsoft Azure is ...
Microsoftが提供するクラウドコンピューティングプラットフォームです。

Cognitive Services is ...
Azureによる説明を借りると「ユーザーのニーズを見たり、聞いたり、話したり、理解したり、解釈したりするために、サポートされているインテリジェントなアルゴリズムをアプリ、Web サイト、ボットに組み込む方法を学習」するための人工知能に関連する技術を利用したクラウドサービスです。

Search is ...
広告の除外されたWeb ページ、画像、動画、ニュースを調べる機能を自サイトに導入することが容易となるAPI(Bing Search API群です。

Bing Video Search is ...
提供されたAPIの発行によりYouTube, MSN,Vimeoなどから動画を取得して表示させることが可能です。メタ情報を判別して作成者の情報、エンコード形式、ソースの閲覧数、ビデオの長さ、品質などによるフィルタが提供されています。

azure環境構築

azureのアカウントを作成頂き、『リソース、サービス、ドキュメントの検索』で「Bing Search」で検索します。Market Placeに「Bing Search」が表示されるので選択し以下のように入力します。nameは重複しない文字列を記述。pricing tierはf1、無料枠を選択しました
Art008.jpg

デプロイが完了するとリソースに移動を選択します
Art009.jpg

最初に表示されるQuick startのエンドポイントとkey1が必要になるのでコピー & 保管しておきます
Art010.jpg

実装

実装と言うほどのものではありませんが記述したものは以下となります。自力実装は150行ほどです。

ライブラリ

FW:Vue.js

著名すぎるので割愛

CSS:water.css

ページに読み込むだけでそれなりのデザインにしてくれます。デモを行うときなどに便利。

css(grid):iota.css

gridに特化したcssライブラリです。グリッドの一番外側のclass属性の設定のみで他はclass属性を汚さずに済みます。

index.js
const key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const url = "https://api.cognitive.microsoft.com/bing/v7.0/videos/search?q=";
Vue.component('container', {
    data: function() {
        return {
            //userInput: "",
            items: []
        }
    },
    methods: {
        search: function(event) {
            var self = this;
            let form = document.querySelector("#form");
            let query = bingSearchOptions(form)
            var option = {
                method: 'GET',
                url: encodeURI(url + query),
                headers: {
                    "Ocp-Apim-Subscription-Key": key,
                    "Accept": "application/json"
                }
            };
            axios(option).then(function(res) {
                self.items = res.data.value;
                console.log(JSON.stringify(self.items));
                return false;
            });
        }
    },
    template: `
		<div>
			<form id="form">
                <input type="text" name="userInput" id="userInput" style="display:inline-block"/>
                <select name="safe"  style="display:inline-block">
                    <option value="Strict">制限付き</option>
                    <option value="Moderate">中</option>
                    <option value="Off">オフ</option>
                </select>
                <button @click="search"  style="display:inline-block" type="button">検 索</button>
            </form>
            <div class="grid card">
                <div v-for="item in items">
                    <img :src="item.thumbnailUrl">
                    <h2>{{ item.creator.name }}</h2>
                    <p>{{ item.description.substring(0,45) }}...</p>
                </div>
            </div>

        </div>
        `
});

bingSearch.js
// クエリパラメータの付加は [サンプル](https://docs.microsoft.com/ja-jp/azure/cognitive-services/bing-video-search/tutorial-bing-video-search-single-page-app)を活かすことにしました。
function bingSearchOptions(form) {

    var options = [];
    // options.push("mkt=" + form.where.value);
    options.push("mkt=" + "ja-jp");
    //options.push("SafeSearch=" + (form.safe.checked ? "strict" : "off"));
    options.push("SafeSearch=" + (form.safe.value));

    // if (form.when.value.length) options.push("freshness=" + form.when.value);
    // var what = [];
    // for (var i = 0; i < form.what.length; i++)
    //     if (form.what[i].checked) what.push(form.what[i].value);
    // if (what.length) {
    //     options.push("modules=" + what.join(","));
    //     options.push("answerCount=9");
    // }
    // options.push("count=" + form.count.value);
    options.push("count=" + "12");
    //options.push("offset=" + form.offset.value);
    options.push("textDecorations=true");
    options.push("textFormat=HTML");
    return form.userInput.value + "&" + options.join("&");
}
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>Bing Video Search API + vue + axiosで動画検索を導入</title>
</head>
<body>
    <div id="app">
        <container></container>
    </div>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/light.min.css">
    <link rel="stylesheet" href="iota.css">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
    <script src="bingSearch.js"></script>
    <script src="index.js"></script>
    <script>
        new Vue({
            el: '#app'
        });
    </script>
</body>
</html>
style.css
body {
    max-width: 1200px;
}

h2 {
    font-size: 85%;
}

img {
    width: 100%;
}

.card p {
    font-size: 95%;
}

.card {
    padding-top: 25px;
    --cols-lg: 3;
    --cols-xl: 3;
}
result.json
[{
    "webSearchUrl": "https://www.bing.com/videos/search?q=%E3%83%94%E3%82%AB%E3%83%81%E3%83%A5%E3%82%A6%E3%80%80%E3%81%8A%E3%81%A3%E3%81%B1%E3%81%84&view=detail&mid=E6334F82F50821780104E6334F82F50821780104",
    "name": "【妖怪ウォッチ4】謎の美少女!?超絶かわいい女の子キター!#29",
    "description": "この動画はレベルファイブ著作物の利用許諾を受けて配信しています。 妖怪ウォッチ4 ぼくらは同じ空を見上げているついにスイッチで発売!舞台はなんと4つの世界!超絶バトルに憑依召喚!新妖怪登場も! チャンネル登録お願いし ...",
    "thumbnailUrl": "https://tse3.mm.bing.net/th?id=OVP._yn4UxTP-8jkAQmwZ-bDXAEsDh&pid=Api",
    "datePublished": "2019-06-21T02:30:01.0000000",
    "publisher": [{
        "name": "YouTube"
    }],
    "creator": {
        "name": "Dice channel"
    },
    "isAccessibleForFree": true,
    "isFamilyFriendly": true,
    "contentUrl": "https://www.youtube.com/watch?v=bbrOv38K75w",
    "hostPageUrl": "https://www.youtube.com/watch?v=bbrOv38K75w",
    "encodingFormat": "h264",
    "hostPageDisplayUrl": "https://www.youtube.com/watch?v=bbrOv38K75w",
    "width": 1280,
    "height": 720,
    "duration": "PT26M28S",
    "motionThumbnailUrl": "https://tse3.mm.bing.net/th?id=OM.BAF4IQj1gk8z5g_1573776621&pid=Api",
    "embedHtml": "&lt;iframe width=&quot;1280&quot; height=&quot;720&quot; src=&quot;https://www.youtube.com/embed/bbrOv38K75w?autoplay=1&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;",
    "allowHttpsEmbed": true,
    "viewCount": 27224,
    "thumbnail": {
        "width": 300,
        "height": 225
    },
    "videoId": "E6334F82F50821780104E6334F82F50821780104",
    "allowMobileEmbed": true,
    "isSuperfresh": false
}, {
    "webSearchUrl": "https://www.bing.com/videos/search?

・
・
・

クエリパラメータ

GETメソッドで送信しますがその際のクエリパラメータに以下のようなものを付加することができます。(以下は現在私が把握しているモノだけとなります)

パラメータ 内容
mkt 検索で使用される市場(場所と言語)で、今回ja-jpを設定
SafeSearch "成人向け" の結果をフィルターで除外する Bing のセーフサーチ機能を使用するかどうかを指定
freshness 動画の鮮度(オプションとして、最近の日、週、または月に検索を限定する)
answerCount 取得件数
textFormat HTMLを指定しました。がオブジェクトが返却されます。

結果

成人向けフィルタ未適用

Art014.jpg

同じキーワードで成人向けフィルタ適用

おっぱい画像がフィルタされているのがわかります。

Art015.jpg

結論

150行程で自サイトに簡単に動画検索を導入することができました。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?