File size: 4,906 Bytes
7b945e6
 
 
 
 
ba0694b
7b945e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba0694b
 
 
 
 
7b945e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba0694b
 
 
 
 
 
 
 
 
 
 
 
7b945e6
 
 
 
 
ba0694b
 
7b945e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba0694b
 
 
 
 
 
7b945e6
 
 
 
 
 
 
 
 
ba0694b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import gradio as gr
from transformers import (
    AutoProcessor, 
    AutoModelForVision2Seq, 
    BlipProcessor, 
    BlipForQuestionAnswering
)
from PIL import Image
import torch
import warnings
warnings.filterwarnings("ignore")

class IridologyAnalyzer:
    def __init__(self):
        # Inicializar modelos
        print("Carregando modelos...")
        
        # GIT model
        self.git_processor = AutoProcessor.from_pretrained("microsoft/git-base-vqa")
        self.git_model = AutoModelForVision2Seq.from_pretrained("microsoft/git-base-vqa")
        
        # BLIP model
        self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
        self.blip_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
        
        # Perguntas predefinidas para análise de iridologia
        self.iridology_questions = [
            "What is the color pattern of the iris?",
            "Are there any dark spots or marks in the iris?",
            "What is the texture of the iris?",
            "Are there any rings or circles in the iris?",
            "What is the condition of the pupil?",
            "Are there any lines radiating from the pupil?",
            "Is there any discoloration in specific areas?",
            "What is the overall clarity of the iris?",
            "Describe any notable features in the iris tissue",
            "Are there any white marks or spots?",
            "Describe the structure of the iris fibers",
            "What is the condition of the iris border?"
        ]
        
        print("Modelos carregados com sucesso!")

    def analyze_with_git(self, image, question):
        inputs = self.git_processor(images=image, text=question, return_tensors="pt")
        outputs = self.git_model.generate(
            **inputs,
            max_length=50,
            num_beams=4,
            early_stopping=True
        )
        return self.git_processor.batch_decode(outputs, skip_special_tokens=True)[0]

    def analyze_with_blip(self, image, question):
        inputs = self.blip_processor(image, question, return_tensors="pt")
        outputs = self.blip_model.generate(**inputs)
        return self.blip_processor.decode(outputs[0], skip_special_tokens=True)

    def comprehensive_analysis(self, image):
        """Realiza uma análise completa usando todos os modelos e questões predefinidas."""
        results = []
        
        for question in self.iridology_questions:
            # Análise com cada modelo
            try:
                git_result = self.analyze_with_git(image, question)
                blip_result = self.analyze_with_blip(image, question)
                
                results.append({
                    "question": question,
                    "git_analysis": git_result,
                    "blip_analysis": blip_result
                })
            except Exception as e:
                print(f"Erro ao processar questão '{question}': {str(e)}")
                continue
        
        # Formatar resultados
        formatted_results = "Análise Detalhada de Iridologia:\n\n"
        for result in results:
            formatted_results += f"Pergunta: {result['question']}\n"
            formatted_results += f"Análise 1 (GIT): {result['git_analysis']}\n"
            formatted_results += f"Análise 2 (BLIP): {result['blip_analysis']}\n"
            formatted_results += "-" * 50 + "\n"
        
        return formatted_results

def create_gradio_interface():
    analyzer = IridologyAnalyzer()
    
    def process_image(image):
        if image is None:
            return "Por favor, faça o upload de uma imagem."
        
        # Converter para PIL Image se necessário
        if not isinstance(image, Image.Image):
            image = Image.fromarray(image)
        
        # Realizar análise
        try:
            return analyzer.comprehensive_analysis(image)
        except Exception as e:
            return f"Erro durante a análise: {str(e)}"
    
    # Interface Gradio
    iface = gr.Interface(
        fn=process_image,
        inputs=gr.Image(type="pil", label="Upload da Imagem do Olho"),
        outputs=gr.Textbox(label="Resultados da Análise", lines=20),
        title="Analisador de Iridologia com IA",
        description="""
        Este sistema analisa imagens de íris usando múltiplos modelos de IA para identificar padrões relevantes para iridologia.
        Faça o upload de uma imagem clara do olho para análise.
        
        Recomendações para melhores resultados:
        1. Use imagens bem iluminadas
        2. Garanta que a íris esteja em foco
        3. Evite reflexos excessivos
        4. Enquadre apenas o olho na imagem
        """,
        examples=[],
        cache_examples=True
    )
    
    return iface

if __name__ == "__main__":
    iface = create_gradio_interface()
    iface.launch()