Emalawi19 commited on
Commit
c884e52
·
verified ·
1 Parent(s): 90bbefd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+
5
+ model_name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
6
+
7
+ print("Loading model...")
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ model_name,
11
+ device_map="auto",
12
+ torch_dtype=torch.float16
13
+ )
14
+ print("Model loaded!")
15
+
16
+ def chat(message, history):
17
+ if message == "":
18
+ return ""
19
+
20
+ try:
21
+ # Build conversation history safely
22
+ conversation = ""
23
+
24
+ # Handle history - each item is a list [user_msg, bot_msg]
25
+ for item in history:
26
+ if len(item) >= 2:
27
+ conversation += f"User: {item[0]}\nAssistant: {item[1]}\n"
28
+
29
+ # Add current message
30
+ conversation += f"User: {message}\nAssistant:"
31
+
32
+ # Tokenize
33
+ inputs = tokenizer(
34
+ conversation,
35
+ return_tensors="pt",
36
+ truncation=True,
37
+ max_length=1024
38
+ ).to(model.device)
39
+
40
+ # Generate response
41
+ outputs = model.generate(
42
+ **inputs,
43
+ max_new_tokens=256,
44
+ temperature=0.7,
45
+ top_p=0.9,
46
+ do_sample=True,
47
+ pad_token_id=tokenizer.eos_token_id
48
+ )
49
+
50
+ # Decode response
51
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
52
+
53
+ # Extract only the assistant's reply
54
+ if "Assistant:" in response:
55
+ response = response.split("Assistant:")[-1].strip()
56
+
57
+ # Remove any thinking tags if present
58
+ if "</think>" in response:
59
+ response = response.split("</think>")[-1].strip()
60
+
61
+ return response
62
+
63
+ except Exception as e:
64
+ return f"Error: {str(e)}"
65
+
66
+ # Create the chat interface
67
+ demo = gr.ChatInterface(
68
+ fn=chat,
69
+ title="DeepSeek Chat AI 🤖",
70
+ description="Chat with DeepSeek-R1-Distill-Qwen-1.5B",
71
+ theme="soft"
72
+ )
73
+
74
+ if __name__ == "__main__":
75
+ demo.launch()