├── .github ├── demo.gif ├── index-flow.png └── query-flow.png ├── toy_data ├── .DS_Store ├── 0GhwfyDcAoM.mp4 └── uTNL3WXEexA.mp4 ├── requirements.txt ├── scripts └── download_model.sh ├── search-flow.yml ├── index-flow.yml ├── .gitignore ├── app.py ├── executors.py ├── README.md └── LICENSE /.github/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/.github/demo.gif -------------------------------------------------------------------------------- /toy_data/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/toy_data/.DS_Store -------------------------------------------------------------------------------- /.github/index-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/.github/index-flow.png -------------------------------------------------------------------------------- /.github/query-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/.github/query-flow.png -------------------------------------------------------------------------------- /toy_data/0GhwfyDcAoM.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/toy_data/0GhwfyDcAoM.mp4 -------------------------------------------------------------------------------- /toy_data/uTNL3WXEexA.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/example-video-search/HEAD/toy_data/uTNL3WXEexA.mp4 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | jina==3.4.4 2 | docarray==0.13.14 3 | numpy==1.20 4 | ffmpeg-python==0.2.0 5 | librosa==0.8.1 6 | webvtt-py==0.4.6 7 | pillow==8.4.0 8 | -------------------------------------------------------------------------------- /scripts/download_model.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | export MODEL_DIR=.cache 3 | 4 | mkdir -p ${MODEL_DIR} 5 | if [ ! -f "${MODEL_DIR}/AudioCLIP-Full-Training.pt" ]; then 6 | echo "Downloading model" 7 | echo "------ Download AudioCLIP model ------" 8 | wget -q https://github.com/AndreyGuzhov/AudioCLIP/releases/download/v0.1/AudioCLIP-Full-Training.pt 9 | file="$(ls -lh ./)" && echo $file 10 | mv AudioCLIP-Full-Training.pt ${MODEL_DIR}/AudioCLIP-Full-Training.pt 11 | 12 | else 13 | echo "Model already exists! Skipping." 14 | fi 15 | 16 | if [ ! -f "${MODEL_DIR}/bpe_simple_vocab_16e6.txt.gz" ]; then 17 | echo "Downloading vocab" 18 | echo "------ Download vocab ------" 19 | wget -q https://github.com/AndreyGuzhov/AudioCLIP/releases/download/v0.1/bpe_simple_vocab_16e6.txt.gz 20 | mv bpe_simple_vocab_16e6.txt.gz ${MODEL_DIR}/bpe_simple_vocab_16e6.txt.gz 21 | else 22 | echo "Vocab already exists! Skipping." 23 | fi 24 | -------------------------------------------------------------------------------- /search-flow.yml: -------------------------------------------------------------------------------- 1 | jtype: Flow 2 | version: '1' 3 | with: 4 | protocol: 'http' 5 | cors: True 6 | port_expose: $JINA_PORT 7 | executors: 8 | - name: text_encoder 9 | uses: jinahub+docker://AudioCLIPTextEncoder/v0.5 10 | uses_with: 11 | traversal_paths: '@r' 12 | volumes: $MODEL_MOUNT_CACHE 13 | - name: image_indexer 14 | uses: jinahub://SimpleIndexer/v0.15 15 | uses_with: 16 | match_args: 17 | limit: $TOP_K 18 | traversal_ldarray: '@r' 19 | traversal_rdarray: '@c' 20 | uses_metas: 21 | workspace: $JINA_WORKSPACE/image_indexer 22 | volumes: $WORKSPACE_MOUNT 23 | needs: text_encoder 24 | - name: audio_indexer 25 | uses: jinahub://SimpleIndexer/v0.15 26 | uses_with: 27 | match_args: 28 | limit: $TOP_K 29 | traversal_ldarray: '@r' 30 | traversal_rdarray: '@c' 31 | uses_metas: 32 | workspace: $JINA_WORKSPACE/audio_indexer 33 | volumes: $WORKSPACE_MOUNT 34 | needs: text_encoder 35 | - name: 'merger' 36 | uses: 'jinahub://MatchMerger/v0.3' 37 | uses_with: 38 | default_traversal_paths: '@r' 39 | needs: ['image_indexer', 'audio_indexer'] 40 | - name: ranker 41 | uses: MixRanker 42 | uses_with: 43 | modality_list: 44 | - 'audio' 45 | - 'image' 46 | top_k: 1 47 | py_modules: 48 | - executors.py 49 | 50 | -------------------------------------------------------------------------------- /index-flow.yml: -------------------------------------------------------------------------------- 1 | jtype: Flow 2 | version: '1' 3 | with: 4 | protocol: 'http' 5 | cors: True 6 | port_expose: $JINA_PORT 7 | executors: 8 | - name: frame_extractor 9 | uses: jinahub://VideoLoader/v0.6 10 | install_requirements: True 11 | uses_with: 12 | modality_list: 13 | - 'image' 14 | - 'audio' 15 | uses_requests: 16 | '/index': 'extract' 17 | - name: image_filter 18 | uses: FilterModality 19 | uses_with: 20 | modality: 'image' 21 | py_modules: 22 | - executors.py 23 | needs: frame_extractor 24 | - name: image_encoder 25 | uses: jinahub+docker://AudioCLIPImageEncoder/v0.6 26 | uses_with: 27 | traversal_paths: '@c' 28 | volumes: $MODEL_MOUNT_CACHE 29 | needs: image_filter 30 | - name: image_indexer 31 | uses: jinahub://SimpleIndexer/v0.15 32 | uses_metas: 33 | workspace: $JINA_WORKSPACE/image_indexer 34 | volumes: $WORKSPACE_MOUNT 35 | needs: ['image_encoder'] 36 | - name: audio_filter 37 | uses: FilterModality 38 | uses_with: 39 | modality: 'audio' 40 | py_modules: 41 | - executors.py 42 | needs: frame_extractor 43 | - name: audio_segmenter 44 | uses: AudioSegmenter 45 | uses_with: 46 | traversal_paths: '@c' 47 | chunk_strip: 10 48 | chunk_duration: 5 49 | py_modules: 50 | - executors.py 51 | needs: audio_filter 52 | - name: audio_encoder 53 | uses: jinahub+docker://AudioCLIPEncoder/v0.6 54 | uses_with: 55 | traversal_paths: '@c' 56 | volumes: $MODEL_MOUNT_ASSETS 57 | needs: audio_segmenter 58 | - name: audio_indexer 59 | uses: jinahub://SimpleIndexer/v0.15 60 | uses_metas: 61 | workspace: $JINA_WORKSPACE/audio_indexer 62 | volumes: $WORKSPACE_MOUNT 63 | needs: audio_encoder 64 | - name: join_all 65 | needs: ['image_indexer', 'audio_indexer'] 66 | 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | models/ 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | pip-wheel-metadata/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | 133 | # PyCharm 134 | .idea/ 135 | 136 | # Mac OS X 137 | .DS_Store 138 | toy_data/.DS_Store 139 | 140 | # Project 141 | workspace -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import click 4 | 5 | from jina import Flow 6 | from jina.types.request import Request 7 | from docarray import Document, DocumentArray 8 | 9 | 10 | def config(): 11 | cur_dir = os.path.dirname(os.path.abspath(__file__)) 12 | model_dir = os.path.join(cur_dir, '.cache') 13 | workspace_dir = os.path.join(cur_dir, 'workspace') 14 | os.environ['JINA_PORT'] = '45678' # the port for accessing the RESTful service, i.e. http://localhost:45678/docs 15 | os.environ['JINA_WORKSPACE'] = './workspace' # the directory to store the indexed data 16 | os.environ['TOP_K'] = '50' # the maximal number of results to return 17 | os.environ['MODEL_MOUNT_ASSETS'] = f'{model_dir}:/workdir/.cache' 18 | os.environ['MODEL_MOUNT_CACHE'] = f'{model_dir}:/workdir/.cache' 19 | os.environ['WORKSPACE_MOUNT'] = f'{workspace_dir}:/workdir/workspace' 20 | 21 | 22 | def get_docs(data_path): 23 | for fn in glob.glob(os.path.join(data_path, '*.mp4')): 24 | yield Document(uri=fn, id=os.path.basename(fn)) 25 | 26 | 27 | def check_search(resp: Request): 28 | for doc in resp.docs: 29 | print(f'Query text: {doc.text}') 30 | print(f'Matches:') 31 | for m in doc.matches: 32 | print(f'+- id: {m.id}, score: {m.scores["cosine"].value}, timestamp: {m.tags["timestamp"]}, link: {m.uri}') 33 | print('-'*10) 34 | 35 | 36 | @click.command() 37 | @click.option('--mode', '-m', type=click.Choice(['restful', 'grpc', 'restful_query']), default='restful') 38 | @click.option('--directory', '-d', type=click.Path(exists=True), default='toy_data') 39 | def main(mode, directory): 40 | config() 41 | workspace = os.environ['JINA_WORKSPACE'] 42 | if os.path.exists(workspace) and mode not in ['restful_query', 'grpc_query']: 43 | print( 44 | f'\n +-----------------------------------------------------------------------------------+ \ 45 | \n | 🤖🤖🤖 | \ 46 | \n | The directory {workspace} already exists. Please remove it before indexing again. | \ 47 | \n | 🤖🤖🤖 | \ 48 | \n +-----------------------------------------------------------------------------------+' 49 | ) 50 | return -1 51 | if mode == 'grpc': 52 | override_dict = { 53 | 'protocol': 'grpc', 54 | 'cors': False} 55 | else: 56 | override_dict = {} 57 | 58 | if mode in ['grpc', 'restful']: 59 | with Flow.load_config('index-flow.yml', override_with=override_dict) as f: 60 | f.post(on='/index', inputs=get_docs(directory), request_size=1) 61 | 62 | print('index completed.') 63 | 64 | with Flow.load_config('search-flow.yml', override_with=override_dict) as f: 65 | print('ready for searching.') 66 | if mode == 'grpc': 67 | f.post( 68 | on='/search', 69 | inputs=DocumentArray([ 70 | Document(text='bicycle bell ringing'), 71 | Document(text='typing on a keyboard'), 72 | Document(text='a young girl'), 73 | ]), 74 | on_done=check_search) 75 | elif mode in ['restful', 'restful_query']: 76 | f.block() 77 | 78 | 79 | if __name__ == '__main__': 80 | main() 81 | -------------------------------------------------------------------------------- /executors.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Iterable 2 | from collections import defaultdict 3 | 4 | import numpy as np 5 | 6 | from jina import Executor, requests 7 | from docarray import Document, DocumentArray 8 | 9 | 10 | _ALLOWED_METRICS = ['min', 'max', 'mean_min', 'mean_max'] 11 | DEFAULT_FPS = 1 12 | 13 | 14 | class FilterModality(Executor): 15 | def __init__(self, 16 | modality: str = None, 17 | *args, 18 | **kwargs): 19 | super().__init__(*args, **kwargs) 20 | self.modality = modality 21 | 22 | @requests 23 | def filter(self, docs: DocumentArray, **kwargs): 24 | for doc in docs: 25 | chunks = filter(lambda d: d.modality == self.modality, doc.chunks) 26 | doc.chunks = chunks 27 | return docs 28 | 29 | 30 | class AudioSegmenter(Executor): 31 | def __init__(self, chunk_duration: int = 10, chunk_strip: int = 1, 32 | traversal_paths: str = None, *args, **kwargs): 33 | super().__init__(*args, **kwargs) 34 | self.chunk_duration = chunk_duration # seconds 35 | self.strip = chunk_strip 36 | self.traversal_paths = traversal_paths 37 | 38 | @requests(on=['/search', '/index']) 39 | def segment(self, docs: DocumentArray, 40 | parameters: dict = None, **kwargs): 41 | traversal_paths = parameters.get('traversal_paths', self.traversal_paths) 42 | for idx, doc in enumerate(docs[traversal_paths]): 43 | sample_rate = doc.tags['sample_rate'] 44 | chunk_size = int(self.chunk_duration * sample_rate) 45 | strip = parameters.get('chunk_strip', self.strip) 46 | strip_size = int(strip * sample_rate) 47 | num_chunks = max(1, int((doc.tensor.shape[0] - chunk_size) / strip_size)) 48 | chunk_array = DocumentArray() 49 | for chunk_id in range(num_chunks): 50 | beg = chunk_id * strip_size 51 | end = beg + chunk_size 52 | if beg > doc.tensor.shape[0]: 53 | break 54 | chunk_array.append( 55 | Document( 56 | tensor=doc.tensor[beg:end], 57 | offset=idx, 58 | location=[beg, end], 59 | tags=doc.tags, 60 | modality='audio' 61 | ) 62 | ) 63 | ts = (beg / sample_rate) if sample_rate != 0 else 0 64 | chunk_array[chunk_id].tags['timestamp'] = ts 65 | chunk_array[chunk_id].tags['video'] = doc.id 66 | docs[idx].chunks = chunk_array 67 | 68 | 69 | class MixRanker(Executor): 70 | """ 71 | Aggregate the matches and overwrite document.matches with the aggregated results. 72 | """ 73 | def __init__( 74 | self, 75 | metric: str = 'cosine', 76 | ranking: str = 'min', 77 | top_k: int = 10, 78 | modality_list: Iterable[str] = ('image', 'audio'), 79 | *args, 80 | **kwargs, 81 | ): 82 | super().__init__(*args, **kwargs) 83 | 84 | if ranking not in _ALLOWED_METRICS: 85 | raise ValueError( 86 | f'ranking should be one of {_ALLOWED_METRICS}, got "{ranking}"', 87 | ) 88 | 89 | self.metric = metric 90 | self.ranking = ranking 91 | self.top_k = top_k 92 | self.modality_list = modality_list 93 | 94 | @requests(on='/search') 95 | def merge_matches(self, docs: DocumentArray, parameters=None, **kwargs): 96 | if not docs: 97 | return 98 | top_k = int(parameters.get('top_k', self.top_k)) 99 | for doc in docs: 100 | parents_matches = defaultdict(list) 101 | for m in doc.matches: 102 | if m.modality in self.modality_list: 103 | parents_matches[m.parent_id].append(m) 104 | new_matches = [] 105 | for match_parent_id, matches in parents_matches.items(): 106 | best_id = 0 107 | if self.ranking == 'min': 108 | best_id = np.argmin([m.scores[self.metric].value for m in matches]) 109 | elif self.ranking == 'max': 110 | best_id = np.argmax([m.scores[self.metric].value for m in matches]) 111 | new_match = matches[best_id] 112 | new_match.id = matches[best_id].parent_id 113 | new_match.scores = {self.metric: matches[best_id].scores[self.metric]} 114 | timestamp = matches[best_id].tags['timestamp'] 115 | if new_match.modality == 'image': 116 | new_match.tags['timestamp'] = float(timestamp) / DEFAULT_FPS 117 | vid = new_match.id.split('.')[0] 118 | # reconstruct the YouTube URL based on the vid 119 | new_match.uri = f'https://www.youtube.com/watch?v={vid}#t={int(timestamp)}s' 120 | new_matches.append(new_match) 121 | 122 | # Sort the matches 123 | doc.matches = new_matches 124 | if self.ranking == 'min': 125 | doc.matches.sort(key=lambda d: d.scores[self.metric].value) 126 | elif self.ranking == 'max': 127 | doc.matches.sort(key=lambda d: -d.scores[self.metric].value) 128 | doc.matches = doc.matches[:top_k] 129 | doc.pop('embedding') 130 | 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Build A Video Search System using Jina 2 | 3 | **NOTE**: The simplified version of this example is at [feat-simple-tutorial](https://github.com/jina-ai/example-video-search/tree/feat-simple-tutorial) branch, which contains the full codes for the tutorial at [docs.jina.ai](https://docs.jina.ai/tutorials/video-search) 4 | 5 | Imagine that you remember one specific scene from a movie, for example the scene from 6 | The Lord of the Rings where Gandalf is figthing the dragon Balrog. Unfortunately, you forgot both 7 | the name Gandalf and Balrog and also in which of the three movies the scene occurred. How could you find the correct scene in the movie now? 8 | This is where this example can help you. This Video Search System allows you to search in movies based on text. 9 | This means you could search _'Old wizard fighting dragon'_ and the search system would return the correct movie and timestamp of the scene. 10 | 11 | **Table of Contents** 12 | - [Build A Video Search System using Jina](#build-a-video-search-system-using-jina) 13 | - [Overview](#overview) 14 | - [🐍 Build the app with Python](#-build-the-app-with-python) 15 | - [🗝️ Requirements](#️-requirements) 16 | - [👾 Step 1. Clone the repo and install Jina](#-step-1-clone-the-repo-and-install-jina) 17 | - [Step 2. Download the AudioCLIP model.](#step-2-download-the-audioclip-model) 18 | - [🏃 Step 3. Index your data](#-step-3-index-your-data) 19 | - [🔎 Step 4: Query your data](#-step-4-query-your-data) 20 | - [🌀 Flow diagram](#-flow-diagram) 21 | - [Indexing](#indexing) 22 | - [Querying](#querying) 23 | - [🔮 Overview of the files](#-overview-of-the-files) 24 | - [⏭️ Next steps](#️-next-steps) 25 | - [👩‍👩‍👧‍👦 Community](#-community) 26 | - [🦄 License](#-license) 27 | 28 | 29 | ## Overview 30 | | About this example: | | 31 | | ------------- | ------------- | 32 | | Learnings | How to search through both image frames and audio of a video. | 33 | | Used for indexing | Video Files. | 34 | | Used for querying | Text Query (e.g. "girl studying engineering") | 35 | | Dataset used | Choose your own videos | 36 | | Model used | [AudioCLIP](https://github.com/AndreyGuzhov/AudioCLIP) | 37 | 38 | In this example, we create a video search system that retrieves the videos based on short text descriptions of the scenes. The main challenge is to enable the user to search videos _**without**_ using any labels or text information about the videos. 39 | 40 | 41 | We choose to use Audio CLIP models to encode the video frames and audios 42 | 43 | Jina searches both the image frames and the audio of the video and returns 44 | the matched video and a timestamp. 45 | 46 | _____ 47 | 48 | ## 🐍 Build the app with Python 49 | 50 | These instructions explain how to build the example yourself and deploy it with Python. 51 | 52 | 53 | ### 🗝️ Requirements 54 | 55 | 1. You have a working Python 3.7 or 3.8 environment and a installation of [Docker](https://docs.docker.com/get-docker/). Ensure that you set enough memory resources(more than 6GB) to docker. You can set it in settings/resources/advanced in Docker. 56 | 2. You have at least 5 GB of free space on your hard drive. 57 | 3. You have installed `ffmpeg` and it is available from the command line (it's in your `PATH` environment variable). On Ubuntu, this should cover it: `sudo apt-get install -y ffmpeg` 58 | 4. We recommend creating a [new Python virtual environment](https://docs.python.org/3/tutorial/venv.html) to have a clean installation of Jina and prevent dependency conflicts. 59 | ```shell 60 | python -m venv venv 61 | source venv/bin/activate 62 | ``` 63 | 64 | ### 👾 Step 1. Clone the repo and install Jina 65 | 66 | Begin by cloning the repo, so you can get the required files and datasets. 67 | 68 | ```sh 69 | git clone https://github.com/jina-ai/example-video-search 70 | cd example-video-search 71 | ```` 72 | In your terminal, you should now be located in the *example-video-search* folder. Let's install Jina and the other required Python libraries. For further information on installing Jina check out [our documentation](https://docs.jina.ai/chapters/core/setup/). 73 | 74 | ```sh 75 | pip install -r requirements.txt 76 | ``` 77 | 78 | ### Step 2. Download the AudioCLIP model. 79 | We recommend you to download the AudioCLIP model in advance. 80 | To do that, run: 81 | ```bash 82 | bash scripts/download_model.sh 83 | ``` 84 | 85 | ### 🏃 Step 3. Index your data 86 | To quickly get started, you can index a [small dataset](toy-data) to make sure everything is working correctly. 87 | 88 | To index the toy dataset, run 89 | ```bash 90 | python app.py -m grpc 91 | ``` 92 | After indexing, the search flow is started automatically and three simple test queries are performed. 93 | The results are displayed in your terminal. 94 | 95 | We recommend you come back to this step later and index more data. 96 | 97 | ### 🔎 Step 4: Query your data 98 | After indexing once, you can query without indexing by running 99 | 100 | ```bash 101 | python app.py -m restful_query 102 | ``` 103 | 104 | Afterwards, you can query with 105 | 106 | ```bash 107 | curl -X 'POST' 'localhost:45678/search' \ 108 | -H 'accept: application/json' \ 109 | -H 'Content-Type: application/json' \ 110 | -d '{"data": [{"text": "this is a highway"}]}' 111 | ``` 112 | 113 | The retrieved results contains the video filename (id) and the best matched frame in that video together with its 114 | timestamp. 115 | 116 | 117 | ![](.github/demo.gif) 118 | 119 | 120 | You can also add more parameters to the query: 121 | ```sh 122 | curl -X POST -d '{"parameters":{"top_k": 5}, "data": ["a black dog and a spotted dog are fighting"]}' -H 'accept: application/json' -H 'Content-Type: application/json' 'http://localhost:45678/search' 123 | ``` 124 | 125 | Once you run this command, you should see a JSON output returned to you. This contains the video uri and the timestamp, which together determine one part of the video that matches the query text description. 126 | By default, the `toy_data` contains two videos clipped from YouTube. 127 | 128 | 129 | ## 🌀 Flow diagram 130 | This diagram provides a visual representation of the Flows in this example; Showing which executors are used in which order. 131 | Remember, our goal is to compare vectors representing the semantics of images and audio with vectors encoding the semantics of short text descriptions. 132 | 133 | ### Indexing 134 | ![](.github/index-flow.png) 135 | As you can see, the Flow that Indexes the data contains two parallel branches: 136 | - Image: Encodes image frames from the video and indexes them. 137 | - Audio: Encodes audio of the images and indexes it. 138 | 139 | ### Querying 140 | ![](.github/query-flow.png) 141 | The query flow is different to the index flow. We are encoding the text input using the AudioCLIP model and then 142 | compare the embeddings with the audio and image embeddings we have stored in the indexers. 143 | Then, the indexers add the closest matches to the documents. 144 | 145 | ## 🔮 Overview of the files 146 | 147 | | | | 148 | | -------------------- | ---------------------------------------------------------------------------------------------------------------- | 149 | | 📃 `index-flow.yml` | YAML file to configure indexing Flow | 150 | | 📃 `search-flow.yml` | YAML file to configure querying Flow | 151 | | 📃 `executors.py` | File that contains Ranker and ModalityFilter executors | 152 | | 📂 `workspace/` | Folder to store indexed files (embeddings and documents). Automatically created after the first indexing | 153 | | 📂 `toy-data/` | Folder to store the toy dataset for the example | 154 | | 📃 `app.py` | Main file that runs the example | 155 | 156 | 157 | ## ⏭️ Next steps 158 | 159 | Did you like this example and are you interested in building your own? For a detailed tutorial on how to build your Jina app check out [How to Build Your First Jina App](https://docs.jina.ai/chapters/my_first_jina_app/#how-to-build-your-first-jina-app) guide in our documentation. 160 | 161 | To learn more about Jina concepts, check out the [cookbooks](https://github.com/jina-ai/jina/tree/master/.github/2.0/cookbooks). 162 | 163 | If you have any issues following this guide, you can always get support from our [Slack community](https://slack.jina.ai) . 164 | 165 | ## 👩‍👩‍👧‍👦 Community 166 | 167 | - [Slack channel](https://slack.jina.ai) - a communication platform for developers to discuss Jina. 168 | - [LinkedIn](https://www.linkedin.com/company/jinaai/) - get to know Jina AI as a company and find job opportunities. 169 | - [![Twitter Follow](https://img.shields.io/twitter/follow/JinaAI_?label=Follow%20%40JinaAI_&style=social)](https://twitter.com/JinaAI_) - follow us and interact with us using hashtag `#JinaSearch`. 170 | - [Company](https://jina.ai) - know more about our company, we are fully committed to open-source! 171 | 172 | ## 🦄 License 173 | 174 | Copyright (c) 2021 Jina AI Limited. All rights reserved. 175 | 176 | Jina is licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/jina-ai/jina/blob/master/LICENSE) for the full license text. 177 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------