Change model
Browse filesFiles changed (15)
- app_interogation.py+6-6
- docker-compose.yml+2
- images/dog.jpgAdded
- images/human.jpgAdded
- images/turtle.jpgAdded
- images/woman.jpgAdded
- my.dist.env+3-1
- requirements.txt+4-2
- src/modules/config.py+7-4
- src/modules/models/clip_model_loader.py+5-2
- src/modules/models/model_loader.pyAdded+53
- src/modules/models/transformers_model_loader.pyDeleted-37
- src/pages/interrogation.py+36-26
- src/repositories/images.py+5-5
- src/scenarios/interrogation.py+11-5
19 unmodified lines202122232324252625 unmodified lines525354555556575888 unmodified lines14714814915015015115215315415515515615715818 unmodified lines1771781791801801811821837 unmodified lines19119219319419419519619719 unmodified lines# ci_vith.clip_model = ci_vith.clip_model.to("cpu")
def image_analysis(image, clip_model_name):def image_analyse(image, clip_model_name): # move selected model to GPU and other model to CPU # if clip_model_name == MODELS[0]: # ci_vith.clip_model = ci_vith.clip_model.to("cpu")25 unmodified lines return medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranks
def image_to_prompt(image, clip_model_name, mode):def image_describe(image, clip_model_name, mode): # move selected model to GPU and other model to CPU # if clip_model_name == MODELS[0]: # ci_vith.clip_model = ci_vith.clip_model.to("cpu")88 unmodified lines flavor = gr.Label(label="Flavor", num_top_classes=5)
button = gr.Button("Analyze") button.click(image_analysis, inputs=[image, model], outputs=[medium, artist, movement, trending, flavor]) button.click(image_analyse, inputs=[image, model], outputs=[medium, artist, movement, trending, flavor])
examples = [['example01.jpg', MODELS[0]], ['example02.jpg', MODELS[0]]] ex = gr.Examples( examples=examples, fn=image_analysis, fn=image_analyse, inputs=[input_image, input_model], outputs=[medium, artist, movement, trending, flavor], cache_examples=True,18 unmodified lines examples = [['example01.jpg', MODELS[0], 'best'], ['example02.jpg', MODELS[0], 'best']] ex = gr.Examples( examples=examples, fn=image_to_prompt, fn=image_describe, inputs=[input_image, input_model, input_mode], outputs=[output_text, share_button, community_icon, loading_icon], cache_examples=True,7 unmodified lines gr.HTML(ARTICLE)
submit_btn.click( fn=image_to_prompt, fn=image_describe, inputs=[input_image, input_model, input_mode], outputs=[output_text, share_button, community_icon, loading_icon] )9 unmodified lines10111213141516179 unmodified lines environment: GRADIO_SERVER_NAME: 0.0.0.0 GRADIO_SERVER_PORT: 7860 HF_HOME: "/app/volume/.cache/hf" TRANSFORMERS_CACHE: "/app/volume/.cache/transformers" env_file: - my.env ports:1234456DEBUG_MODE=TrueGPU_MODE=False
CLIP_MODEL_NAME=****CACHE_DIR=/app/volume/.cache
MODEL_NAME=***2 unmodified lines3456767891011122 unmodified linesfairscaleftfyPillowtimmtransformers==4.37.2timm==0.9.12transformers==4.44.0open_clip_torch==2.14.0requestsclip-interrogator==0.5.4einops==0.8.0accelerate==0.32.114 unmodified lines15161718191819202122212223242526272814 unmodified lines "GPU_MODE", False ).lower() in ['true', '1']
self.clip_model_name = os.environ.get( "CLIP_MODEL_NAME", "" self.model_name = os.environ.get( "MODEL_NAME", "" ) self.transformers_model_name = os.environ.get( "TRANSFORMERS_MODEL_NAME", ""
self.cache_dir = os.environ.get( "CACHE_DIR", "/app/volume/.cache" ) self.models_cache_dir = self.cache_dir + "/models"
config = Config()15 unmodified lines161718191920212232 unmodified lines555657585859606112 unmodified lines747576777879808115 unmodified lines #self.model = None #return # TODO remove this line
model_config = InterrogatorConfig(clip_model_name=conf.clip_model_name) model_config = InterrogatorConfig(clip_model_name="ViT-L-14/openai") self.model = Interrogator(model_config)
if conf.gpu_mode:32 unmodified lines
return medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranks
def image_to_prompt(self, image_path, mode=DEFAULT_MODE): def image_describe(self, image_path, mode=DEFAULT_MODE): self.model.config.blip_num_beams = 64 self.model.config.chunk_size = 2048 self.model.config.flavor_intermediate_count = 102412 unmodified lines
return prompt
def image_ask(self, image_path, question): return 'Not implemented yet'
clip_model_loader = ClipModelLoader(ConfigObj)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import osimport torchfrom PIL import Imagefrom transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM
from src.utils.singleton import Singletonfrom src.modules.config import Config, config as ConfigObjfrom src.modules.logger import logger as Logger
class ModelLoader: __metaclass__ = Singleton
def __init__(self, conf: Config): #self._model = None #return # TODO remove this line
#print("Not implemented !!!") print(conf.model_name)
#revision = "2024-03-04" - verry slow #revision = "main" #does not work revision = "2024-05-08" if conf.gpu_mode: self._model = AutoModelForCausalLM.from_pretrained( conf.model_name, trust_remote_code=True, revision=revision, torch_dtype=torch.bfloat16, cache_dir=conf.models_cache_dir, attn_implementation="flash_attention_2" ).to("cuda") else: self._model = AutoModelForCausalLM.from_pretrained( conf.model_name, trust_remote_code=True, revision=revision, cache_dir=conf.models_cache_dir, ) self._tokenizer = AutoTokenizer.from_pretrained( conf.model_name, revision=revision, cache_dir=conf.models_cache_dir )
def image_describe(self, image_path): image = Image.open(image_path) enc_image = self._model.encode_image(image) return self._model.answer_question(enc_image, "Describe this image.", self._tokenizer)
def image_ask(self, image_path, question): image = Image.open(image_path) enc_image = self._model.encode_image(image) return self._model.answer_question( enc_image, question, self._tokenizer )
model_loader = ModelLoader(ConfigObj)12345678910111213141516171819202122232425262728293031323334353637import osimport torchfrom PIL import Imagefrom transformers import CLIPProcessor, CLIPModel
from src.utils.singleton import Singletonfrom src.modules.config import Config, config as ConfigObjfrom src.modules.logger import logger as Logger
class TransformersModelLoader: __metaclass__ = Singleton
def __init__(self, conf: Config): #self.model = None #return # TODO remove this line
self.model = CLIPModel.from_pretrained(conf.transformers_model_name) self.processor = CLIPProcessor.from_pretrained(conf.transformers_model_name) device = torch.device("cuda" if conf.gpu_mode else "cpu") self.model.to(device)
def image_analyse(self, image_path): image = Image.open(image_path) inputs = self.processor(text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True) outputs = self.model(**inputs) logits_per_image = outputs.logits_per_image probs = logits_per_image.softmax(dim=1)
return probs
def image_to_prompt(self, image_path): return none
transformers_model_loader = TransformersModelLoader(ConfigObj)2 unmodified lines3456678914 unmodified lines2425262728293031323334353637382728293031324546333435363738394041524243444546474849505152535455565758596061626315 unmodified lines798081748283777879808182848586878889909192938485949596879798991002 unmodified linesfrom src.storage.state import state as Statefrom src.modules.logger import logger as Logger
from src.scenarios.interrogation import image_analysis, image_to_promptfrom src.scenarios.interrogation import image_describe, image_testfrom src.repositories.images import images as ImagesRepo
14 unmodified lines </div>"""
CSS = """ #col-container {margin-left: auto; margin-right: auto;} a {text-decoration-line: underline; font-weight: 600;} .animate-spin { animation: spin 1s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"""
def select_image(selection: gr.SelectData): Logger.info("Image selected") State.set_current_image(selection.value['image']['path'])
def selected_image_process(): Logger.info("Selected image process")def selected_image_describe(): Logger.info("Selected image describe") image_path = State.get_current_image() if not image_path: Logger.tmp_debug(image_path) print(image_path) gr.Warning("No image selected!") return None
return image_to_prompt(image_path) return image_describe(image_path)
def selected_image_test(): Logger.info("Selected image test") image_path = State.get_current_image() if not image_path: gr.Warning("No image selected!") return None
result = image_test(image_path, [ "Is it a photo? Answer only \"Yes\" or \"No\".", "Is it a human? Answer only \"Yes\" or \"No\".", "Is it alone? Answer only \"Yes\" or \"No\".", "Is it a woman? Answer only \"Yes\" or \"No\".", "Is it happy? Answer only \"Yes\" or \"No\"." ])
return result
def build():15 unmodified lines )
gallery.select(select_image, inputs=None, outputs=None) button = gr.Button("Analyze")
with gr.Column(): output_text = gr.Textbox(label="Output", elem_id="output-txt") medium = gr.Label(label="Medium", num_top_classes=5) artist = gr.Label(label="Artist", num_top_classes=5) movement = gr.Label(label="Movement", num_top_classes=5) trending = gr.Label(label="Trending", num_top_classes=5) flavor = gr.Label(label="Flavor", num_top_classes=5) output_text = gr.Textbox(label="Description", elem_id="output-txt") describe_button = gr.Button("Describe")
is_photo = gr.Checkbox(label="Is a photo?") is_human = gr.Checkbox(label="Is a human?") is_alone = gr.Checkbox(label="Alone?") is_woman = gr.Checkbox(label="Is it a woman?") is_happy = gr.Checkbox(label="Is it happy?") test_button = gr.Button("Test")
#button.click(selected_image_process, inputs=[], outputs=[output_text, medium, artist, movement, trending, flavor]) button.click(selected_image_process, inputs=[], outputs=[output_text]) describe_button.click(selected_image_describe, inputs=[], outputs=[output_text]) test_button.click(selected_image_test(), inputs=[], outputs=[is_photo, is_human, is_alone, is_woman, is_happy])
with gr.Blocks(css=CSS) as block: with gr.Blocks() as block: with gr.Column(elem_id="col-container"): gr.HTML(TITLE)
5 unmodified lines6789101112139101112131415165 unmodified lines
def __init__(self): self.images = [ "/app/images/cat.jpg", "/app/images/cat.jpg", "/app/images/cat.jpg", "/app/images/cat.jpg", "/app/images/cat.jpg" "images/cat.jpg", "images/dog.jpg", "images/turtle.jpg", "images/human.jpg", "images/woman.jpg" ]
def get_images(self):1233456778991011121314151416171618192021222324import os
from src.modules.models.clip_model_loader import clip_model_loader as ClipModelLoader#from src.modules.models.clip_model_loader import clip_model_loader as ClipModelLoaderfrom src.modules.models.model_loader import model_loader as ModelLoaderfrom src.storage.state import state as State
def image_to_prompt(image_path):def image_describe(image_path): State.begin() result = ClipModelLoader.image_to_prompt(image_path) #result = ClipModelLoader.image_describe(image_path) result = ModelLoader.image_describe(image_path) State.end() return result
def image_analysis(image_path):def image_test(image_path, questions): State.begin() result = ClipModelLoader.image_analyse(image_path) #result = ClipModelLoader.image_ask(image_path) result = [] for question in questions: out = ModelLoader.image_ask(image_path, question) result.append(out == 'Yes') State.end() return resultapp_interogation.py+6-6
docker-compose.yml+2
images/dog.jpgAdded

images/human.jpgAdded

images/turtle.jpgAdded

images/woman.jpgAdded

my.dist.env+3-1
requirements.txt+4-2
src/modules/config.py+7-4
src/modules/models/clip_model_loader.py+5-2
src/modules/models/model_loader.pyAdded+53
src/modules/models/transformers_model_loader.pyDeleted-37
src/pages/interrogation.py+36-26
src/repositories/images.py+5-5
src/scenarios/interrogation.py+11-5