Raiff1982 commited on
Commit
7a01de3
·
verified ·
1 Parent(s): f880280

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -1
app.py CHANGED
@@ -1,3 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
 
3
- gr.load("models/black-forest-labs/FLUX.1-dev").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ import copy
4
+ import inspect
5
+ import warnings
6
+ import json
7
+ import logging
8
+ from pathlib import Path
9
+ from typing import Any, Literal, Optional, Union, List
10
+ from cryptography.fernet import Fernet
11
+ from pydantic import BaseModel, Field
12
+ from gradio import Interface, Blocks
13
+ from gradio.components import Component
14
+ from gradio.data_classes import FileData, GradioModel, GradioRootModel
15
+ from gradio.events import Events
16
+ from gradio.exceptions import Error
17
+ from gradio_client import utils as client_utils
18
+ from transformers import pipeline
19
+ from diffusers import DiffusionPipeline, FluxPipeline
20
+ import torch
21
  import gradio as gr
22
 
23
+ # Corrected code with closed parenthesis
24
+ image_model = FluxPipeline.from_pretrained(
25
+ "black-forest-labs/FLUX.1-dev",
26
+ torch_dtype=torch.bfloat16,
27
+ use_auth_token=os.getenv("HUGGINGFACE_TOKEN")
28
+ )
29
+ image_model.enable_model_cpu_offload()
30
+
31
+ # Define data models for Hugging Face
32
+ class FileDataDict(BaseModel):
33
+ path: str
34
+ url: Optional[str] = None
35
+ size: Optional[int] = None
36
+ orig_name: Optional[str] = None
37
+ mime_type: Optional[str] = None
38
+ is_stream: Optional[bool] = False
39
+
40
+ class Config:
41
+ arbitrary_types_allowed = True
42
+
43
+ class MessageDict(BaseModel):
44
+ content: Union[str, FileDataDict, tuple, Component]
45
+ role: Literal["user", "assistant", "system"]
46
+ metadata: Optional[dict] = None
47
+ options: Optional[List[dict]] = None
48
+
49
+ class Config:
50
+ arbitrary_types_allowed = True
51
+
52
+ class ChatMessage(GradioModel):
53
+ role: Literal["user", "assistant", "system"]
54
+ content: Union[str, FileData, Component]
55
+ metadata: dict = Field(default_factory=dict)
56
+ options: Optional[List[dict]] = None
57
+
58
+ class Config:
59
+ arbitrary_types_allowed = True
60
+
61
+ class ChatbotDataMessages(GradioRootModel):
62
+ root: List[ChatMessage]
63
+
64
+ # Universal Reasoning Aggregator
65
+ class UniversalReasoning:
66
+ def __init__(self, config):
67
+ self.config = config
68
+ self.sentiment_analyzer = pipeline("sentiment-analysis") # Hugging Face sentiment analysis
69
+ self.context_history = [] # Maintain context history
70
+
71
+ # Load models with explicit truncation
72
+ self.deepseek_model = pipeline(
73
+ "text-classification",
74
+ model="distilbert-base-uncased-finetuned-sst-2-english",
75
+ truncation=True
76
+ ) # Updated model
77
+
78
+ self.davinci_model = pipeline(
79
+ "text2text-generation",
80
+ model="t5-small",
81
+ truncation=True
82
+ ) # Replacing text-davinci with T5
83
+
84
+ self.additional_model = pipeline(
85
+ "text-generation",
86
+ model="EleutherAI/gpt-neo-125M",
87
+ truncation=True
88
+ ) # Example GPT-Neo model
89
+
90
+ # Use earlier-defined image model
91
+ self.image_model = image_model
92
+
93
+ async def generate_response(self, question: str) -> str:
94
+ self.context_history.append(question) # Add question to context history
95
+ sentiment_score = self.analyze_sentiment(question)
96
+
97
+ deepseek_response = self.deepseek_model(question)
98
+ davinci_response = self.davinci_model(question, max_length=50, truncation=True)
99
+ additional_response = self.additional_model(question, max_length=100, truncation=True)
100
+
101
+ responses = [
102
+ f"Sentiment score: {sentiment_score}",
103
+ f"DeepSeek Response: {deepseek_response}",
104
+ f"T5 Response: {davinci_response}",
105
+ f"Additional Model Response: {additional_response}"
106
+ ]
107
+
108
+ return "\n\n".join(responses)
109
+
110
+ def generate_image(self, prompt: str):
111
+ image = self.image_model(
112
+ prompt,
113
+ height=1024,
114
+ width=1024,
115
+ guidance_scale=3.5,
116
+ num_inference_steps=50,
117
+ max_sequence_length=512,
118
+ generator=torch.Generator("cpu").manual_seed(0)
119
+ ).images[0]
120
+ image.save("flux-dev.png")
121
+ return image
122
+
123
+ def analyze_sentiment(self, text: str) -> list:
124
+ sentiment_score = self.sentiment_analyzer(text) # Returns a list of dictionaries
125
+ logging.info(f"Sentiment analysis result: {sentiment_score}")
126
+ return sentiment_score
127
+
128
+ # Main Multimodal Chatbot Component
129
+ class MultimodalChatbot(Component):
130
+ def __init__(
131
+ self,
132
+ value: Optional[List[MessageDict]] = None,
133
+ label: Optional[str] = None,
134
+ render: bool = True,
135
+ log_file: Optional[Path] = None,
136
+ ):
137
+ # Ensure value is initialized as an empty list if None
138
+ value = value or []
139
+ super().__init__(label=label, value=value)
140
+ self.log_file = log_file
141
+ self.render = render
142
+ self.data_model = ChatbotDataMessages
143
+ self.universal_reasoning = UniversalReasoning({})
144
+
145
+ def preprocess(self, payload: Optional[ChatbotDataMessages]) -> List[MessageDict]:
146
+ # Handle None payload gracefully
147
+ if payload is None:
148
+ return []
149
+ return payload.root
150
+
151
+ def postprocess(self, messages: Optional[List[MessageDict]]) -> ChatbotDataMessages:
152
+ # Ensure messages is a valid list
153
+ messages = messages or []
154
+ return ChatbotDataMessages(root=messages)
155
+
156
+ # Hugging Face Integration Class
157
+ class HuggingFaceChatbot:
158
+ def __init__(self):
159
+ # Initialize MultimodalChatbot with a default empty list
160
+ self.chatbot = MultimodalChatbot(value=[])
161
+
162
+ def setup_interface(self):
163
+ async def chatbot_logic(input_text: str) -> str:
164
+ return await self.chatbot.universal_reasoning.generate_response(input_text)
165
+
166
+ def image_logic(prompt: str):
167
+ return self.chatbot.universal_reasoning.generate_image(prompt)
168
+
169
+ interface = Interface(
170
+ fn=chatbot_logic,
171
+ inputs="text",
172
+ outputs="text",
173
+ title="Hugging Face Multimodal Chatbot",
174
+ )
175
+
176
+ image_interface = Interface(
177
+ fn=image_logic,
178
+ inputs="text",
179
+ outputs="image",
180
+ title="Image Generator",
181
+ )
182
+
183
+ return Blocks([interface, image_interface])
184
+
185
+ def launch(self):
186
+ interface = self.setup_interface()
187
+ interface.launch()
188
+
189
+ # If running as standalone
190
+ if __name__ == "__main__":
191
+ logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
192
+ chatbot = HuggingFaceChatbot()
193
+ chatbot.launch()