Update app.py
Browse files
app.py
CHANGED
@@ -1,154 +1,163 @@
|
|
1 |
-
|
2 |
-
import
|
3 |
-
|
4 |
-
from
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
def
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
try:
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
except Exception as e:
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
border-radius: 25px;
|
53 |
-
padding: 8px 20px;
|
54 |
-
font-size: 14px;
|
55 |
-
font-weight: bold;
|
56 |
-
cursor: pointer;
|
57 |
-
}
|
58 |
-
.stButton button:hover {
|
59 |
-
background-color: #0a1b35;
|
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 |
-
|
130 |
-
|
131 |
-
|
132 |
-
)
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
from accelerate import Accelerator
|
5 |
+
|
6 |
+
# Check if GPU is available for better performance
|
7 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
8 |
+
print(f"Using device: {device}")
|
9 |
+
|
10 |
+
# Initialize the Accelerator for optimized inference
|
11 |
+
accelerator = Accelerator()
|
12 |
+
|
13 |
+
# Load models and tokenizers with FP16 for speed optimization if GPU is available
|
14 |
+
model_dirs = [
|
15 |
+
"Poonawala/gpt2",
|
16 |
+
"Poonawala/MiriFur",
|
17 |
+
"Poonawala/Llama-3.2-1B"
|
18 |
+
]
|
19 |
+
|
20 |
+
models = {}
|
21 |
+
tokenizers = {}
|
22 |
+
|
23 |
+
def load_model(model_dir):
|
24 |
+
model = AutoModelForCausalLM.from_pretrained(model_dir, torch_dtype=torch.float16 if device.type == "cuda" else torch.float32)
|
25 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
26 |
+
|
27 |
+
if tokenizer.pad_token is None:
|
28 |
+
tokenizer.pad_token = tokenizer.eos_token
|
29 |
+
|
30 |
+
# Move model to GPU/CPU as per availability
|
31 |
+
model = model.to(device)
|
32 |
+
return model, tokenizer
|
33 |
+
|
34 |
+
# Load all models
|
35 |
+
for model_dir in model_dirs:
|
36 |
+
model_name = model_dir.split("/")[-1]
|
37 |
try:
|
38 |
+
model, tokenizer = load_model(model_dir)
|
39 |
+
models[model_name] = model
|
40 |
+
tokenizers[model_name] = tokenizer
|
41 |
+
|
42 |
+
# Batch warm-up inference to reduce initial response time
|
43 |
+
dummy_inputs = ["Hello", "What is a recipe?", "Explain cooking basics"]
|
44 |
+
for dummy_input in dummy_inputs:
|
45 |
+
input_ids = tokenizer.encode(dummy_input, return_tensors='pt').to(device)
|
46 |
+
with torch.no_grad():
|
47 |
+
model.generate(input_ids, max_new_tokens=1)
|
48 |
+
|
49 |
+
print(f"Loaded model and tokenizer from {model_dir}.")
|
50 |
except Exception as e:
|
51 |
+
print(f"Failed to load model from {model_dir}: {e}")
|
52 |
+
continue
|
53 |
+
|
54 |
+
def get_response(prompt, model_name, user_type):
|
55 |
+
if model_name not in models:
|
56 |
+
return "Model not loaded correctly."
|
57 |
+
|
58 |
+
model = models[model_name]
|
59 |
+
tokenizer = tokenizers[model_name]
|
60 |
+
|
61 |
+
# Define different prompt templates based on user type
|
62 |
+
user_type_templates = {
|
63 |
+
"Expert": f"As an Expert, {prompt}\nAnswer:",
|
64 |
+
"Intermediate": f"As an Intermediate, {prompt}\nAnswer:",
|
65 |
+
"Beginner": f"Explain in simple terms: {prompt}\nAnswer:",
|
66 |
+
"Professional": f"As a Professional, {prompt}\nAnswer:"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
}
|
68 |
+
|
69 |
+
# Get the appropriate prompt based on user type
|
70 |
+
prompt_template = user_type_templates.get(user_type, f"{prompt}\nAnswer:")
|
71 |
+
|
72 |
+
encoding = tokenizer(
|
73 |
+
prompt_template,
|
74 |
+
return_tensors='pt',
|
75 |
+
padding=True,
|
76 |
+
truncation=True,
|
77 |
+
max_length=500 # Increased length for larger inputs
|
78 |
+
).to(device)
|
79 |
+
|
80 |
+
max_new_tokens = 200 # Increased to allow full-length answers
|
81 |
+
|
82 |
+
with torch.no_grad():
|
83 |
+
output = model.generate(
|
84 |
+
input_ids=encoding['input_ids'],
|
85 |
+
attention_mask=encoding['attention_mask'],
|
86 |
+
max_new_tokens=max_new_tokens, # Higher value for longer answers
|
87 |
+
num_beams=3, # Using beam search for better quality answers
|
88 |
+
repetition_penalty=1.2, # Increased to reduce repetitive text
|
89 |
+
temperature=0.9, # Slightly higher for creative outputs
|
90 |
+
top_p=0.9, # Including more tokens for diverse generation
|
91 |
+
early_stopping=True,
|
92 |
+
pad_token_id=tokenizer.pad_token_id
|
93 |
+
)
|
94 |
+
|
95 |
+
response = tokenizer.decode(output[0], skip_special_tokens=True)
|
96 |
+
return response.strip()
|
97 |
+
|
98 |
+
def process_input(prompt, model_name, user_type):
|
99 |
+
if prompt and prompt.strip():
|
100 |
+
return get_response(prompt, model_name, user_type)
|
101 |
+
else:
|
102 |
+
return "Please provide a prompt."
|
103 |
+
|
104 |
+
# Gradio Interface with Modern Design
|
105 |
+
with gr.Blocks(css="""
|
106 |
+
body {
|
107 |
+
background-color: #faf3e0; /* Beige for a warm food-related theme */
|
108 |
+
font-family: 'Arial, sans-serif';
|
109 |
+
}
|
110 |
+
.title {
|
111 |
+
font-size: 2.5rem;
|
112 |
+
font-weight: bold;
|
113 |
+
color: #ff7f50; /* Coral color for a food-inspired look */
|
114 |
+
text-align: center;
|
115 |
+
margin-bottom: 1rem;
|
116 |
+
}
|
117 |
+
.container {
|
118 |
+
max-width: 900px;
|
119 |
+
margin: auto;
|
120 |
+
padding: 2rem;
|
121 |
+
background-color: #ffffff;
|
122 |
+
border-radius: 10px;
|
123 |
+
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
124 |
+
}
|
125 |
+
.button {
|
126 |
+
background-color: #ff7f50; /* Coral color for buttons */
|
127 |
+
color: white;
|
128 |
+
padding: 0.8rem 1.5rem;
|
129 |
+
font-size: 1rem;
|
130 |
+
border: none;
|
131 |
+
border-radius: 5px;
|
132 |
+
cursor: pointer;
|
133 |
+
}
|
134 |
+
.button:hover {
|
135 |
+
background-color: #ffa07a; /* Light salmon for hover effect */
|
136 |
+
}
|
137 |
+
""") as demo:
|
138 |
+
|
139 |
+
gr.Markdown("<div class='title'>Cookspert: Your Cooking Assistant</div>")
|
140 |
+
|
141 |
+
user_types = ["Expert", "Intermediate", "Beginner", "Professional"]
|
142 |
+
|
143 |
+
with gr.Tabs():
|
144 |
+
with gr.TabItem("Ask a Cooking Question"):
|
145 |
+
with gr.Row():
|
146 |
+
with gr.Column(scale=2):
|
147 |
+
prompt = gr.Textbox(label="Ask about any recipe", placeholder="Ask question related to cooking here...", lines=2)
|
148 |
+
model_name = gr.Radio(label="Choose Model", choices=list(models.keys()), interactive=True)
|
149 |
+
user_type = gr.Dropdown(label="User Type", choices=user_types, value="Beginner")
|
150 |
+
submit_button = gr.Button("ChefGPT", elem_classes="button")
|
151 |
+
|
152 |
+
response = gr.Textbox(
|
153 |
+
label="🍽️ Response",
|
154 |
+
placeholder="Your answer will appear here...",
|
155 |
+
lines=10,
|
156 |
+
interactive=False,
|
157 |
+
show_copy_button=True
|
158 |
+
)
|
159 |
+
|
160 |
+
submit_button.click(fn=process_input, inputs=[prompt, model_name, user_type], outputs=response)
|
161 |
+
|
162 |
+
if __name__ == "__main__":
|
163 |
+
demo.launch(server_name="0.0.0.0", share=True, debug=True)
|