Commit ·
cebad5c
1
Parent(s): c49a9ad
enable multiple image outputs
Browse filesFiles changed (12)
- .gitignoreAdded+1
- README.md+1-1
- app.py+30-14
- src/__pycache__/classification_model.cpython-312.pyc
- src/__pycache__/model_data.cpython-312.pyc
- src/classification_model.py+27-11
- src/data/classification_result.pyAdded+6
- src/model_data.py → src/data/model_data.pyRenamed+2
- src/interface.pyAdded+8
- src/models/clip_vit.pyAdded+12
- src/models/mobilenet_v3.pyAdded+13
- src/util/extract.pyAdded+10
1__pycache__8 unmodified lines91011121314158 unmodified linespinned: false---## RUN Gradio Locally```pip install gradiogradio app.py8 unmodified lines91011121314158 unmodified linespinned: false---## RUN Gradio Locally (With Auto Reload)```pip install gradiogradio app.py
1 unmodified line2345678910111213141516171819202122232425262728293031323334352 unmodified lines3839404142434445464748491 unmodified lineimport requestsimport randomfrom src.classification_model import ClassificationModel#only for dummy dataresponse = requests.get("https://git.io/JJkYN")labels = response.text.split("\n")clf = ClassificationModel()model_names = clf.get_model_names()output_labels = []def predict(models, img_urls, img_files):print(f'model choosen: {models}')model_predictions = {}#set all labels visibility to falsefor i, name in enumerate(model_names):model_predictions[output_labels[i]] = gr.Label(label=f'# {name}', visible=False)print(f'id {i} invisible')for m in models:idx = model_names.index(m)print(f' {m} idx: ', idx)result = {labels[random.randrange(0, len(labels))]: random.uniform(0, 1.0) for i in range(5)}model_predictions[output_labels[idx]] = gr.Label(label=f'# {m}, 3 seconds', value=result, visible=True)return model_predictionswith gr.Blocks() as demo:gr.Markdown("# Image Classification Benchmark")with gr.Row():with gr.Column(scale=1):2 unmodified linesimg_files = gr.File(label='Upload Files',file_count='multiple', file_types=['image'])apply = gr.Button("Classify", variant='primary')with gr.Column(scale=1):for name in clf.get_model_names():output_labels.append(gr.Label(label=f'# {name}'))apply.click(fn=predict,inputs=[model, img_urls, img_files],outputs=output_labels)if __name__ == "__main__":1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748492 unmodified lines52535455565758596061626364651 unmodified lineimport requestsimport randomfrom src.classification_model import ClassificationModelfrom src.util.extract import extract_image_urls#only for dummy data# response = requests.get("https://git.io/JJkYN")# labels = response.text.split("\n")clf = ClassificationModel()model_names = clf.get_model_names()output_labels = []output_images = []max_input_image = 10def predict(models, img_url, img_files):print(f'model choosen: {models}')model_predictions = {}#set all labels visibility to falsefor label in output_labels:model_predictions[label] = gr.Label(label=f'# {name}', visible=False)#set all images visibility yo hiddenfor img in output_images:model_predictions[img] = gr.Image(visible=False)sources = extract_image_urls(img_url) + (img_files or [])for i, source in enumerate(sources):print(f'{i} type: {type(source)} --> {source}')if i >= max_input_image: breakfor j, m in enumerate(models):results = clf.classify(m, source)print(f'{m} --> {results}')idx = j + (len(model_names)*i) #getting index of labellabel_value = {raw.class_name: raw.confidence for raw in results}model_predictions[output_labels[idx]] = gr.Label(label=f'# {m}, 3 seconds', value=label_value, visible=True)model_predictions[output_images[i]] = gr.Image(visible=True, value=source, label=f'image {i}') # set image visibility to truereturn model_predictionswith gr.Blocks() as demo:gr.Markdown("# Image Classification Benchmark")gr.Markdown("You can input at maximum 10 images at once (urls or files)")with gr.Row():with gr.Column(scale=1):2 unmodified linesimg_files = gr.File(label='Upload Files',file_count='multiple', file_types=['image'])apply = gr.Button("Classify", variant='primary')with gr.Column(scale=1):for i in range(max_input_image):output_images.append(gr.Image(interactive=False, visible= (i==0)))for name in clf.get_model_names():output_labels.append(gr.Label(label=f'# {name}', visible= (i==0)))apply.click(fn=predict,inputs=[model, img_urls, img_files],outputs=output_images+output_labels)if __name__ == "__main__":
12341 unmodified line67891011124 unmodified lines1718192021222324252627282930from .model_data import ModelDataclass ClassificationModel:"""1 unmodified line"""def __init__(self):self.models = self.initialize_models()def get_model_names(self):return [model.name for model in self.models]4 unmodified linesreturn modelraise Exception(f'Model {model_name} not found')def initialize_models(self):return [ModelData('clip-vit-base-patch32'),ModelData('mobilenet_v3')]def load_model(self):"""Loads the model from the model path."""raise NotImplementedError123456789101 unmodified line121314151617184 unmodified lines232425262728293031323334353637383940414243444546from typing import Listfrom urllib.request import urlopenfrom PIL import Imagefrom .data.model_data import ModelDatafrom .models.mobilenet_v3 import MobilenetV3from .models.clip_vit import ClipVitfrom .data.classification_result import ClassificationResultclass ClassificationModel:"""1 unmodified line"""def __init__(self):self.load_model()def get_model_names(self):return [model.name for model in self.models]4 unmodified linesreturn modelraise Exception(f'Model {model_name} not found')def load_model(self):self.models = [ModelData('clip-vit-base-patch32', model_class=ClipVit()),ModelData('mobilenet_v3', model_class=MobilenetV3())]def classify(self, model_name, image) -> List[ClassificationResult]:#print type of imageprint('>> image type -->',type(image))#convert image to pilimg = self.image_to_pil(image)model = self.get_model_data(model_name)return model.model_class.classify_image(img)def image_to_pil(self, image):#if image is starts with https (means url), then download itif image.startswith('https'):return Image.open(urlopen(image))return Image.open(image)
123456from dataclasses import dataclass
@dataclassclass ClassificationResult: class_name: str confidence: float12345from dataclasses import dataclass@dataclassclass ModelData:name: str1234567from dataclasses import dataclassfrom src.interface import ModelInterface@dataclassclass ModelData:name: strmodel_class: ModelInterface
12345678from .data.classification_result import ClassificationResultfrom abc import ABC, abstractmethodfrom typing import List
class ModelInterface(ABC): @abstractmethod def classify_image(self, image) -> List[ClassificationResult]: pass123456789101112from typing import Listfrom src.interface import ModelInterfacefrom src.data.classification_result import ClassificationResult
class ClipVit(ModelInterface): def __init__(self): print('init... vlip vit model')
def classify_image(self, image) -> List[ClassificationResult]: class_name = "Example Result" confidence = 0.85 return [ClassificationResult(class_name=class_name, confidence=confidence)]12345678910111213from typing import Listimport randomfrom src.interface import ModelInterfacefrom src.data.classification_result import ClassificationResult
class MobilenetV3(ModelInterface): def __init__(self): print('init... mobilenet v3 model')
def classify_image(self, image) -> List[ClassificationResult]: results = [ClassificationResult(class_name=f'example class ({i+1})', confidence=random.uniform(0, 1.0)) for i in range(5)] return results12345678910import re
def extract_image_urls(text): # Regular expression to match image URLs pattern = re.compile(r'https?://[^\s]+\.jpg|https?://[^\s]+\.jpeg|https?://[^\s]+\.png|https?://[^\s]+\.gif|https?://[^\s]+\.bmp|https?://[^\s]+\.webp')
# Find all matches in the input text matches = pattern.findall(text)
return matches.gitignoreAdded+1
README.md+1-1
app.py+30-14
src/__pycache__/classification_model.cpython-312.pyc
src/__pycache__/model_data.cpython-312.pyc
src/classification_model.py+27-11
src/data/classification_result.pyAdded+6
src/model_data.py → src/data/model_data.pyRenamed+2
src/interface.pyAdded+8
src/models/clip_vit.pyAdded+12
src/models/mobilenet_v3.pyAdded+13
src/util/extract.pyAdded+10