sergeipetrov philschmid HF staff commited on
Commit
6e88679
0 Parent(s):

Duplicate from philschmid/clip-zero-shot-image-classification

Browse files

Co-authored-by: Philipp Schmid <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pb filter=lfs diff=lfs merge=lfs -text
18
+ *.pickle filter=lfs diff=lfs merge=lfs -text
19
+ *.pkl filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - vision
4
+ - zero-shot-image-classification
5
+ - endpoints-template
6
+ library_name: generic
7
+ ---
8
+
9
+ # Fork of [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) for a `zero-sho-image-classification` Inference endpoint.
10
+
11
+ This repository implements a `custom` task for `zero-shot-image-classification` for 🤗 Inference Endpoints. The code for the customized pipeline is in the [pipeline.py](https://huggingface.co/philschmid/clip-zero-shot-image-classification/blob/main/pipeline.py).
12
+
13
+ To use deploy this model a an Inference Endpoint you have to select `Custom` as task to use the `pipeline.py` file. -> _double check if it is selected_
14
+
15
+ ### expected Request payload
16
+
17
+ ```json
18
+ {
19
+ "image": "/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAMCAgICAgMC....", // base64 image as bytes
20
+ "candiates":["sea","palace","car","ship"]
21
+ }
22
+ ```
23
+
24
+ below is an example on how to run a request using Python and `requests`.
25
+
26
+ ## Run Request
27
+
28
+ 1. prepare an image.
29
+
30
+ ```bash
31
+ !wget https://huggingface.co/datasets/mishig/sample_images/resolve/main/palace.jpg
32
+ ```
33
+
34
+ 2. run request
35
+
36
+ ```python
37
+ import json
38
+ from typing import List
39
+ import requests as r
40
+ import base64
41
+
42
+ ENDPOINT_URL = ""
43
+ HF_TOKEN = ""
44
+
45
+
46
+ def predict(path_to_image: str = None, candiates: List[str] = None):
47
+ with open(path_to_image, "rb") as i:
48
+ b64 = base64.b64encode(i.read())
49
+
50
+ payload = {"inputs": {"image": b64.decode("utf-8"), "candiates": candiates}}
51
+ response = r.post(
52
+ ENDPOINT_URL, headers={"Authorization": f"Bearer {HF_TOKEN}"}, json=payload
53
+ )
54
+ return response.json()
55
+
56
+
57
+ prediction = predict(
58
+ path_to_image="palace.jpg", candiates=["sea", "palace", "car", "ship"]
59
+ )
60
+ ```
61
+
62
+ expected output
63
+
64
+ ```python
65
+ [{'label': 'palace', 'score': 0.9996134638786316},
66
+ {'label': 'car', 'score': 0.0002602009626571089},
67
+ {'label': 'ship', 'score': 0.00011758189066313207},
68
+ {'label': 'sea', 'score': 8.666840585647151e-06}]
69
+ ```
70
+
71
+
config.json ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openai/clip-vit-base-patch32",
3
+ "architectures": [
4
+ "CLIPModel"
5
+ ],
6
+ "initializer_factor": 1.0,
7
+ "logit_scale_init_value": 2.6592,
8
+ "model_type": "clip",
9
+ "projection_dim": 512,
10
+ "text_config": {
11
+ "_name_or_path": "",
12
+ "add_cross_attention": false,
13
+ "architectures": null,
14
+ "attention_dropout": 0.0,
15
+ "bad_words_ids": null,
16
+ "bos_token_id": 0,
17
+ "chunk_size_feed_forward": 0,
18
+ "cross_attention_hidden_size": null,
19
+ "decoder_start_token_id": null,
20
+ "diversity_penalty": 0.0,
21
+ "do_sample": false,
22
+ "dropout": 0.0,
23
+ "early_stopping": false,
24
+ "encoder_no_repeat_ngram_size": 0,
25
+ "eos_token_id": 2,
26
+ "finetuning_task": null,
27
+ "forced_bos_token_id": null,
28
+ "forced_eos_token_id": null,
29
+ "hidden_act": "quick_gelu",
30
+ "hidden_size": 512,
31
+ "id2label": {
32
+ "0": "LABEL_0",
33
+ "1": "LABEL_1"
34
+ },
35
+ "initializer_factor": 1.0,
36
+ "initializer_range": 0.02,
37
+ "intermediate_size": 2048,
38
+ "is_decoder": false,
39
+ "is_encoder_decoder": false,
40
+ "label2id": {
41
+ "LABEL_0": 0,
42
+ "LABEL_1": 1
43
+ },
44
+ "layer_norm_eps": 1e-05,
45
+ "length_penalty": 1.0,
46
+ "max_length": 20,
47
+ "max_position_embeddings": 77,
48
+ "min_length": 0,
49
+ "model_type": "clip_text_model",
50
+ "no_repeat_ngram_size": 0,
51
+ "num_attention_heads": 8,
52
+ "num_beam_groups": 1,
53
+ "num_beams": 1,
54
+ "num_hidden_layers": 12,
55
+ "num_return_sequences": 1,
56
+ "output_attentions": false,
57
+ "output_hidden_states": false,
58
+ "output_scores": false,
59
+ "pad_token_id": 1,
60
+ "prefix": null,
61
+ "problem_type": null,
62
+ "pruned_heads": {},
63
+ "remove_invalid_values": false,
64
+ "repetition_penalty": 1.0,
65
+ "return_dict": true,
66
+ "return_dict_in_generate": false,
67
+ "sep_token_id": null,
68
+ "task_specific_params": null,
69
+ "temperature": 1.0,
70
+ "tie_encoder_decoder": false,
71
+ "tie_word_embeddings": true,
72
+ "tokenizer_class": null,
73
+ "top_k": 50,
74
+ "top_p": 1.0,
75
+ "torch_dtype": null,
76
+ "torchscript": false,
77
+ "transformers_version": "4.16.0.dev0",
78
+ "use_bfloat16": false,
79
+ "vocab_size": 49408
80
+ },
81
+ "text_config_dict": null,
82
+ "transformers_version": null,
83
+ "vision_config": {
84
+ "_name_or_path": "",
85
+ "add_cross_attention": false,
86
+ "architectures": null,
87
+ "attention_dropout": 0.0,
88
+ "bad_words_ids": null,
89
+ "bos_token_id": null,
90
+ "chunk_size_feed_forward": 0,
91
+ "cross_attention_hidden_size": null,
92
+ "decoder_start_token_id": null,
93
+ "diversity_penalty": 0.0,
94
+ "do_sample": false,
95
+ "dropout": 0.0,
96
+ "early_stopping": false,
97
+ "encoder_no_repeat_ngram_size": 0,
98
+ "eos_token_id": null,
99
+ "finetuning_task": null,
100
+ "forced_bos_token_id": null,
101
+ "forced_eos_token_id": null,
102
+ "hidden_act": "quick_gelu",
103
+ "hidden_size": 768,
104
+ "id2label": {
105
+ "0": "LABEL_0",
106
+ "1": "LABEL_1"
107
+ },
108
+ "image_size": 224,
109
+ "initializer_factor": 1.0,
110
+ "initializer_range": 0.02,
111
+ "intermediate_size": 3072,
112
+ "is_decoder": false,
113
+ "is_encoder_decoder": false,
114
+ "label2id": {
115
+ "LABEL_0": 0,
116
+ "LABEL_1": 1
117
+ },
118
+ "layer_norm_eps": 1e-05,
119
+ "length_penalty": 1.0,
120
+ "max_length": 20,
121
+ "min_length": 0,
122
+ "model_type": "clip_vision_model",
123
+ "no_repeat_ngram_size": 0,
124
+ "num_attention_heads": 12,
125
+ "num_beam_groups": 1,
126
+ "num_beams": 1,
127
+ "num_hidden_layers": 12,
128
+ "num_return_sequences": 1,
129
+ "output_attentions": false,
130
+ "output_hidden_states": false,
131
+ "output_scores": false,
132
+ "pad_token_id": null,
133
+ "patch_size": 32,
134
+ "prefix": null,
135
+ "problem_type": null,
136
+ "pruned_heads": {},
137
+ "remove_invalid_values": false,
138
+ "repetition_penalty": 1.0,
139
+ "return_dict": true,
140
+ "return_dict_in_generate": false,
141
+ "sep_token_id": null,
142
+ "task_specific_params": null,
143
+ "temperature": 1.0,
144
+ "tie_encoder_decoder": false,
145
+ "tie_word_embeddings": true,
146
+ "tokenizer_class": null,
147
+ "top_k": 50,
148
+ "top_p": 1.0,
149
+ "torch_dtype": null,
150
+ "torchscript": false,
151
+ "transformers_version": "4.16.0.dev0",
152
+ "use_bfloat16": false
153
+ },
154
+ "vision_config_dict": null
155
+ }
handler.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from PIL import Image
3
+ from io import BytesIO
4
+ from transformers import pipeline
5
+ import base64
6
+
7
+
8
+ class EndpointHandler():
9
+ def __init__(self, path=""):
10
+ self.pipeline=pipeline("zero-shot-image-classification",model=path)
11
+
12
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
13
+ """
14
+ data args:
15
+ images (:obj:`string`)
16
+ candiates (:obj:`list`)
17
+ Return:
18
+ A :obj:`list`:. The list contains items that are dicts should be liked {"label": "XXX", "score": 0.82}
19
+ """
20
+ inputs = data.pop("inputs", data)
21
+
22
+ # decode base64 image to PIL
23
+ image = Image.open(BytesIO(base64.b64decode(inputs['image'])))
24
+
25
+ # run prediction one image wit provided candiates
26
+ prediction = self.pipeline(images=[image], candidate_labels=inputs["candiates"])
27
+ return prediction[0]
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 224,
3
+ "do_center_crop": true,
4
+ "do_normalize": true,
5
+ "do_resize": true,
6
+ "feature_extractor_type": "CLIPFeatureExtractor",
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "resample": 3,
18
+ "size": 224
19
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a63082132ba4f97a80bea76823f544493bffa8082296d62d71581a4feff1576f
3
+ size 605247071
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": {"content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "eos_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "unk_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "pad_token": "<|endoftext|>"}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "bos_token": {"content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "eos_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "pad_token": "<|endoftext|>", "add_prefix_space": false, "errors": "replace", "do_lower_case": true, "name_or_path": "./clip_ViT_B_32/"}
vocab.json ADDED
The diff for this file is too large to render. See raw diff