Viclim commited on
Commit
399af00
·
verified ·
1 Parent(s): d94c436

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
+
5
+ # --- 1. Model Initialization (Loads once when the app starts) ---
6
+ print("🔄 Loading the AI model... This will take a moment on the first run.")
7
+ # Model name from Hugging Face Hub
8
+ model_name = "Qwen/Qwen2.5-1.5B-Instruct"
9
+
10
+ # Load the tokenizer and model
11
+ # We explicitly set `device_map="cpu"` to ensure it runs on the free CPU hardware.
12
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
13
+ model = AutoModelForCausalLM.from_pretrained(
14
+ model_name,
15
+ torch_dtype=torch.float32, # Use float32 for CPU stability
16
+ device_map="cpu",
17
+ trust_remote_code=True
18
+ )
19
+ print("✅ AI Model loaded and ready!")
20
+
21
+ # --- 2. The Core AI Function ---
22
+ def chat_with_ai(message, history):
23
+ """
24
+ Takes the user's message and chat history, generates a response from the AI model.
25
+ """
26
+ # Construct the conversation prompt. The model expects a specific chat format.
27
+ # Here we build a simple prompt with the conversation history.
28
+ prompt = ""
29
+ for user_msg, bot_msg in history:
30
+ prompt += f"<|im_start|>user\n{user_msg}<|im_end|>\n"
31
+ prompt += f"<|im_start|>assistant\n{bot_msg}<|im_end|>\n"
32
+ # Add the current user message
33
+ prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
34
+
35
+ # Tokenize the input and generate a response
36
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
37
+ with torch.no_grad(): # Disable gradient calculation for faster inference
38
+ outputs = model.generate(
39
+ **inputs,
40
+ max_new_tokens=512, # Maximum length of the new response
41
+ temperature=0.7, # Controls randomness (lower = more deterministic)
42
+ do_sample=True, # Enable sampling for more creative responses
43
+ pad_token_id=tokenizer.eos_token_id
44
+ )
45
+
46
+ # Decode only the newly generated tokens (skip the input prompt)
47
+ generated_tokens = outputs[0][inputs['input_ids'].shape[1]:]
48
+ response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
49
+
50
+ return response.strip() # Return the clean response
51
+
52
+ # --- 3. Gradio Interface Setup ---
53
+ # gr.ChatInterface provides a perfect, ready-made UI for chatbots.
54
+ demo = gr.ChatInterface(
55
+ fn=chat_with_ai,
56
+ title="🤖 Free AI Assistant on Hugging Face Spaces",
57
+ description="Ask me anything! I'm running entirely on a free CPU instance. Be patient, I'm thinking as fast as I can.",
58
+ theme="soft",
59
+ examples=["What is the capital of France?", "Explain quantum computing in simple terms.", "Write a short poem about coding."]
60
+ )
61
+
62
+ # --- 4. Launch the App ---
63
+ if __name__ == "__main__":
64
+ demo.launch()