AiCoderv2 commited on
Commit
d796a40
·
verified ·
1 Parent(s): af1e715

Deploy Gradio app with multiple files

Browse files
Files changed (2) hide show
  1. app.py +254 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import (
4
+ AutoTokenizer,
5
+ AutoModelForCausalLM,
6
+ pipeline
7
+ )
8
+ import spaces
9
+ import time
10
+ import os
11
+
12
+ # Model configuration
13
+ MODEL_NAME = "microsoft/DialoGPT-medium" # 1.5B parameters, close to 2B
14
+ # Alternative 2B models you could try:
15
+ # "microsoft/Phi-2" (2.7B - requires special handling)
16
+ # "EleutherAI/gpt-neo-2.7B" (2.7B parameters)
17
+
18
+ # Global variables
19
+ tokenizer = None
20
+ model = None
21
+ chat_history = []
22
+
23
+ def load_model():
24
+ """Load the model and tokenizer"""
25
+ global tokenizer, model
26
+
27
+ if tokenizer is None or model is None:
28
+ print("Loading model and tokenizer...")
29
+
30
+ # Load tokenizer
31
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, padding_side="left")
32
+ if tokenizer.pad_token is None:
33
+ tokenizer.pad_token = tokenizer.eos_token
34
+
35
+ # Load model
36
+ model = AutoModelForCausalLM.from_pretrained(
37
+ MODEL_NAME,
38
+ torch_dtype=torch.float32, # Use float32 for CPU compatibility
39
+ low_cpu_mem_usage=True
40
+ )
41
+
42
+ print(f"Model {MODEL_NAME} loaded successfully!")
43
+
44
+ return tokenizer, model
45
+
46
+ @spaces.GPU(duration=120) # Use GPU if available, with 2-minute timeout
47
+ def generate_response(user_message, history=None):
48
+ """
49
+ Generate response using the loaded model
50
+
51
+ Args:
52
+ user_message (str): User's input message
53
+ history (list): Previous chat history
54
+
55
+ Returns:
56
+ str: Generated response
57
+ """
58
+ if history is None:
59
+ history = []
60
+
61
+ try:
62
+ # Load model if not already loaded
63
+ load_model()
64
+
65
+ # Prepare input
66
+ chat_history = history.copy()
67
+ chat_history.append(user_message)
68
+
69
+ # Combine all messages for context
70
+ context = "\n".join([f"Human: {msg}" if i % 2 == 0 else f"Assistant: {msg}"
71
+ for i, msg in enumerate(chat_history)])
72
+ context += "\nAssistant:"
73
+
74
+ # Tokenize input
75
+ inputs = tokenizer.encode(context, return_tensors="pt", max_length=1024, truncation=True)
76
+
77
+ # Generate response
78
+ with torch.no_grad():
79
+ outputs = model.generate(
80
+ inputs,
81
+ max_length=inputs.shape[1] + 100,
82
+ num_return_sequences=1,
83
+ temperature=0.7,
84
+ do_sample=True,
85
+ pad_token_id=tokenizer.eos_token_id,
86
+ eos_token_id=tokenizer.encode("Human")[0]
87
+ )
88
+
89
+ # Decode response
90
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
91
+
92
+ # Extract only the assistant's response
93
+ if "Assistant:" in response:
94
+ response = response.split("Assistant:")[-1].strip()
95
+ else:
96
+ # Fallback: try to extract meaningful response
97
+ response = response[len(context):].strip()
98
+
99
+ # Clean up response
100
+ response = response.split("\n")[0].strip()
101
+
102
+ # Remove any remaining "Human:" parts
103
+ if "Human:" in response:
104
+ response = response.split("Human:")[0].strip()
105
+
106
+ # Ensure response is not empty
107
+ if not response or len(response.strip()) < 2:
108
+ response = "I'm here to chat! What would you like to talk about?"
109
+
110
+ return response
111
+
112
+ except Exception as e:
113
+ print(f"Error generating response: {e}")
114
+ return "I apologize, but I'm having trouble generating a response right now. Please try again!"
115
+
116
+ def chat_interface(message, history):
117
+ """
118
+ Chat interface function
119
+ """
120
+ if not message.strip():
121
+ return history, ""
122
+
123
+ # Generate response
124
+ response = generate_response(message, history)
125
+
126
+ # Update history
127
+ history.append(message)
128
+ history.append(response)
129
+
130
+ # Keep history manageable (last 10 exchanges)
131
+ if len(history) > 20:
132
+ history = history[-20:]
133
+
134
+ return history, ""
135
+
136
+ def clear_chat():
137
+ """Clear the chat history"""
138
+ return []
139
+
140
+ # Create the Gradio interface
141
+ def create_demo():
142
+ """Create the Gradio demo"""
143
+
144
+ # Custom CSS for better styling
145
+ css = """
146
+ .gradio-container {
147
+ max-width: 800px !important;
148
+ margin: auto !important;
149
+ }
150
+ .header {
151
+ text-align: center;
152
+ padding: 20px;
153
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
154
+ color: white;
155
+ border-radius: 10px;
156
+ margin-bottom: 20px;
157
+ }
158
+ .model-info {
159
+ text-align: center;
160
+ padding: 10px;
161
+ background-color: #f0f2f6;
162
+ border-radius: 5px;
163
+ margin-bottom: 20px;
164
+ font-size: 0.9em;
165
+ }
166
+ """
167
+
168
+ with gr.Blocks(css=css, title="Free 2B Parameter Chatbot") as demo:
169
+
170
+ # Header
171
+ gr.HTML("""
172
+ <div class="header">
173
+ <h1>🤖 Free 2B Parameter Chatbot</h1>
174
+ <p>Chat with a 2B parameter AI model for free! Fast responses, unlimited chat.</p>
175
+ <p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: white; text-decoration: underline;">Built with anycoder</a></p>
176
+ </div>
177
+ """)
178
+
179
+ # Model info
180
+ gr.HTML(f"""
181
+ <div class="model-info">
182
+ <strong>Model:</strong> {MODEL_NAME} (1.5B parameters)<br>
183
+ <strong>Type:</strong> Conversational AI<br>
184
+ <strong>Powered by:</strong> Hugging Face Transformers
185
+ </div>
186
+ """)
187
+
188
+ # Chat interface
189
+ chatbot = gr.Chatbot(
190
+ label="Chat with AI",
191
+ height=600,
192
+ bubble_full_width=False,
193
+ avatar_images=(None, None)
194
+ )
195
+
196
+ msg = gr.Textbox(
197
+ label="Your message",
198
+ placeholder="Type your message here...",
199
+ scale=4
200
+ )
201
+
202
+ with gr.Row():
203
+ send_btn = gr.Button("Send", variant="primary", scale=1)
204
+ clear_btn = gr.Button("Clear Chat", variant="secondary", scale=1)
205
+
206
+ # Example prompts
207
+ gr.Examples(
208
+ examples=[
209
+ "Hello! How are you today?",
210
+ "Tell me a joke",
211
+ "What's the weather like?",
212
+ "Can you help me with coding?",
213
+ "What's your favorite movie?",
214
+ "Explain quantum physics",
215
+ "Tell me about space exploration",
216
+ "Write a short poem about AI"
217
+ ],
218
+ inputs=msg,
219
+ label="Example prompts to get started"
220
+ )
221
+
222
+ # Event handlers
223
+ msg.submit(
224
+ chat_interface,
225
+ inputs=[msg, chatbot],
226
+ outputs=[chatbot, msg]
227
+ )
228
+
229
+ send_btn.click(
230
+ chat_interface,
231
+ inputs=[msg, chatbot],
232
+ outputs=[chatbot, msg]
233
+ )
234
+
235
+ clear_btn.click(
236
+ clear_chat,
237
+ outputs=chatbot
238
+ )
239
+
240
+ return demo
241
+
242
+ if __name__ == "__main__":
243
+ # Create and launch the demo
244
+ demo = create_demo()
245
+
246
+ # Launch with optimal settings for Hugging Face Spaces
247
+ demo.launch(
248
+ share=False, # Disable sharing since this is for Hugging Face Spaces
249
+ inbrowser=False,
250
+ server_name="0.0.0.0",
251
+ server_port=7860,
252
+ show_api=False,
253
+ quiet=True
254
+ )
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ txt
2
+ gradio
3
+ spaces
4
+ transformers
5
+ torch
6
+ accelerate
7
+ huggingface_hub