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 lines2021222324252625 unmodified lines5253545556575888 unmodified lines14714814915015115215315415515615715818 unmodified lines1771781791801811821837 unmodified lines19119219319419519619719 unmodified lines# ci_vith.clip_model = ci_vith.clip_model.to("cpu")def image_analysis(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 linesreturn medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranksdef image_to_prompt(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 linesflavor = 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])examples = [['example01.jpg', MODELS[0]], ['example02.jpg', MODELS[0]]]ex = gr.Examples(examples=examples,fn=image_analysis,inputs=[input_image, input_model],outputs=[medium, artist, movement, trending, flavor],cache_examples=True,18 unmodified linesexamples = [['example01.jpg', MODELS[0], 'best'], ['example02.jpg', MODELS[0], 'best']]ex = gr.Examples(examples=examples,fn=image_to_prompt,inputs=[input_image, input_model, input_mode],outputs=[output_text, share_button, community_icon, loading_icon],cache_examples=True,7 unmodified linesgr.HTML(ARTICLE)submit_btn.click(fn=image_to_prompt,inputs=[input_image, input_model, input_mode],outputs=[output_text, share_button, community_icon, loading_icon])19 unmodified lines2021222324252625 unmodified lines5253545556575888 unmodified lines14714814915015115215315415515615715818 unmodified lines1771781791801811821837 unmodified lines19119219319419519619719 unmodified lines# ci_vith.clip_model = ci_vith.clip_model.to("cpu")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 linesreturn medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranksdef 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 linesflavor = gr.Label(label="Flavor", num_top_classes=5)button = gr.Button("Analyze")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_analyse,inputs=[input_image, input_model],outputs=[medium, artist, movement, trending, flavor],cache_examples=True,18 unmodified linesexamples = [['example01.jpg', MODELS[0], 'best'], ['example02.jpg', MODELS[0], 'best']]ex = gr.Examples(examples=examples,fn=image_describe,inputs=[input_image, input_model, input_mode],outputs=[output_text, share_button, community_icon, loading_icon],cache_examples=True,7 unmodified linesgr.HTML(ARTICLE)submit_btn.click(fn=image_describe,inputs=[input_image, input_model, input_mode],outputs=[output_text, share_button, community_icon, loading_icon])
9 unmodified lines1011121314159 unmodified linesenvironment:GRADIO_SERVER_NAME: 0.0.0.0GRADIO_SERVER_PORT: 7860env_file:- my.envports:9 unmodified lines10111213141516179 unmodified linesenvironment:GRADIO_SERVER_NAME: 0.0.0.0GRADIO_SERVER_PORT: 7860HF_HOME: "/app/volume/.cache/hf"TRANSFORMERS_CACHE: "/app/volume/.cache/transformers"env_file:- my.envports:
1234DEBUG_MODE=TrueGPU_MODE=FalseCLIP_MODEL_NAME=****123456DEBUG_MODE=TrueGPU_MODE=FalseCACHE_DIR=/app/volume/.cacheMODEL_NAME=***
2 unmodified lines3456789102 unmodified linesfairscaleftfyPillowtimmtransformers==4.37.2open_clip_torch==2.14.0requestsclip-interrogator==0.5.42 unmodified lines34567891011122 unmodified linesfairscaleftfyPillowtimm==0.9.12transformers==4.44.0open_clip_torch==2.14.0requestsclip-interrogator==0.5.4einops==0.8.0accelerate==0.32.1
14 unmodified lines151617181920212223242514 unmodified lines"GPU_MODE", False).lower() in ['true', '1']self.clip_model_name = os.environ.get("CLIP_MODEL_NAME", "")self.transformers_model_name = os.environ.get("TRANSFORMERS_MODEL_NAME", "")config = Config()14 unmodified lines151617181920212223242526272814 unmodified lines"GPU_MODE", False).lower() in ['true', '1']self.model_name = os.environ.get("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 lines1617181920212232 unmodified lines5556575859606112 unmodified lines747576777815 unmodified lines#self.model = None#return # TODO remove this linemodel_config = InterrogatorConfig(clip_model_name=conf.clip_model_name)self.model = Interrogator(model_config)if conf.gpu_mode:32 unmodified linesreturn medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranksdef image_to_prompt(self, image_path, mode=DEFAULT_MODE):self.model.config.blip_num_beams = 64self.model.config.chunk_size = 2048self.model.config.flavor_intermediate_count = 102412 unmodified linesreturn promptclip_model_loader = ClipModelLoader(ConfigObj)15 unmodified lines1617181920212232 unmodified lines5556575859606112 unmodified lines747576777879808115 unmodified lines#self.model = None#return # TODO remove this linemodel_config = InterrogatorConfig(clip_model_name="ViT-L-14/openai")self.model = Interrogator(model_config)if conf.gpu_mode:32 unmodified linesreturn medium_ranks, artist_ranks, movement_ranks, trending_ranks, flavor_ranksdef image_describe(self, image_path, mode=DEFAULT_MODE):self.model.config.blip_num_beams = 64self.model.config.chunk_size = 2048self.model.config.flavor_intermediate_count = 102412 unmodified linesreturn promptdef 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 lines345678914 unmodified lines242526272829303132333435363738394041424344454647484950515253545515 unmodified lines71727374757677787980818283848586878889902 unmodified linesfrom src.storage.state import state as Statefrom src.modules.logger import logger as Loggerfrom src.scenarios.interrogation import image_analysis, image_to_promptfrom src.repositories.images import images as ImagesRepo14 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")image_path = State.get_current_image()if not image_path:gr.Warning("No image selected!")return Nonereturn image_to_prompt(image_path)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)#button.click(selected_image_process, inputs=[], outputs=[output_text, medium, artist, movement, trending, flavor])button.click(selected_image_process, inputs=[], outputs=[output_text])with gr.Blocks(css=CSS) as block:with gr.Column(elem_id="col-container"):gr.HTML(TITLE)2 unmodified lines345678914 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596061626315 unmodified lines7980818283848586878889909192939495969798991002 unmodified linesfrom src.storage.state import state as Statefrom src.modules.logger import logger as Loggerfrom src.scenarios.interrogation import image_describe, image_testfrom src.repositories.images import images as ImagesRepo14 unmodified lines</div>"""def select_image(selection: gr.SelectData):Logger.info("Image selected")State.set_current_image(selection.value['image']['path'])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 Nonereturn 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 Noneresult = 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 resultdef build():15 unmodified lines)gallery.select(select_image, inputs=None, outputs=None)with gr.Column():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")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() as block:with gr.Column(elem_id="col-container"):gr.HTML(TITLE)
5 unmodified lines6789101112131415165 unmodified linesdef __init__(self):self.images = ["/app/images/cat.jpg","/app/images/cat.jpg","/app/images/cat.jpg","/app/images/cat.jpg","/app/images/cat.jpg"]def get_images(self):5 unmodified lines6789101112131415165 unmodified linesdef __init__(self):self.images = ["images/cat.jpg","images/dog.jpg","images/turtle.jpg","images/human.jpg","images/woman.jpg"]def get_images(self):
123456789101112131415161718import osfrom src.modules.models.clip_model_loader import clip_model_loader as ClipModelLoaderfrom src.storage.state import state as Statedef image_to_prompt(image_path):State.begin()result = ClipModelLoader.image_to_prompt(image_path)State.end()return resultdef image_analysis(image_path):State.begin()result = ClipModelLoader.image_analyse(image_path)State.end()return result123456789101112131415161718192021222324import os#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 Statedef image_describe(image_path):State.begin()#result = ClipModelLoader.image_describe(image_path)result = ModelLoader.image_describe(image_path)State.end()return resultdef image_test(image_path, questions):State.begin()#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 result
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