krisha06 commited on
Commit
dd686dc
·
verified ·
1 Parent(s): 9b175a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -41
app.py CHANGED
@@ -1,58 +1,64 @@
 
1
  import torch
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  from peft import PeftModel
4
- import streamlit as st
5
 
6
- # Load tokenizer and model
7
- base_model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
8
- tokenizer = AutoTokenizer.from_pretrained(base_model)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- model = AutoModelForCausalLM.from_pretrained(base_model, device_map="cpu")
11
- model = PeftModel.from_pretrained(model, "lora_adapter") # Change if needed
12
- model.eval()
 
 
13
 
14
- # Format prompt (no USER/ASSISTANT lines to confuse model)
15
- def format_prompt(instruction):
16
- return f"""You are a helpful and expert Python programming tutor.
17
- You only answer questions related to Python programming.
18
- If the question is unrelated to Python, say:
19
  "Sorry, I can only answer Python-related questions."
20
 
21
- Question: {instruction}
22
- Answer:"""
23
 
24
- # Generate answer
25
- def chat(instruction):
26
- prompt = format_prompt(instruction)
27
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
28
 
 
 
 
 
29
  with torch.no_grad():
30
- outputs = model.generate(
31
  **inputs,
32
- max_new_tokens=512,
33
- do_sample=False,
34
  temperature=0.7,
35
  top_p=0.9,
36
- repetition_penalty=1.1
37
  )
38
-
39
- full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
40
-
41
- # Only return the model's answer
42
- return full_output.split("Answer:")[-1].strip()
43
 
44
  # Streamlit UI
45
- st.set_page_config(page_title="🐍 Python Tutor Chatbot (LoRA)")
46
- st.title("🐍 Python Tutor Chatbot (LoRA)")
47
- st.write("Ask me Python programming questions!")
48
-
49
- user_input = st.text_area("Your question:")
50
-
51
- if st.button("Get Answer") and user_input.strip():
52
- with st.spinner("Thinking..."):
53
- response = chat(user_input)
54
- st.markdown("**Answer:**")
55
- if "```" in response:
56
- st.markdown(response)
57
- else:
58
- st.write(response)
 
1
+ import streamlit as st
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
  from peft import PeftModel
 
5
 
6
+ # Load base model & tokenizer
7
+ base_model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
8
+ adapter_path = "lora_adapter" # path to your LoRA adapter directory
9
+
10
+ @st.cache_resource
11
+ def load_model():
12
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
13
+ base_model = AutoModelForCausalLM.from_pretrained(base_model_name, device_map="auto")
14
+ model = PeftModel.from_pretrained(base_model, adapter_path)
15
+ model.eval()
16
+ return tokenizer, model
17
+
18
+ tokenizer, model = load_model()
19
+
20
+ # Prompt formatting
21
+ def format_prompt(user_input):
22
+ return f"""You are a helpful and knowledgeable Python tutor chatbot.
23
 
24
+ You only answer questions related to Python programming, including:
25
+ - Python syntax, functions, loops, and conditionals
26
+ - Standard libraries and popular packages (e.g., NumPy, pandas)
27
+ - Debugging and code explanation
28
+ - Python tools, environments, and tips
29
 
30
+ If a question is not related to Python, reply with:
 
 
 
 
31
  "Sorry, I can only answer Python-related questions."
32
 
33
+ ### Instruction:
34
+ {user_input}
35
 
36
+ ### Response:"""
 
 
 
37
 
38
+ # Chat handler
39
+ def chat(user_input):
40
+ prompt = format_prompt(user_input)
41
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
42
  with torch.no_grad():
43
+ output = model.generate(
44
  **inputs,
45
+ max_new_tokens=200,
46
+ do_sample=True,
47
  temperature=0.7,
48
  top_p=0.9,
49
+ pad_token_id=tokenizer.eos_token_id
50
  )
51
+ decoded = tokenizer.decode(output[0], skip_special_tokens=True)
52
+ return decoded.split("### Response:")[-1].strip()
 
 
 
53
 
54
  # Streamlit UI
55
+ st.title("🧑‍🏫 Python Tutor Chatbot")
56
+ st.write("Ask me anything about Python programming!")
57
+
58
+ user_input = st.text_area("Your Question", height=150)
59
+ if st.button("Ask"):
60
+ if user_input.strip():
61
+ with st.spinner("Thinking..."):
62
+ answer = chat(user_input)
63
+ st.markdown("### 💡 Answer:")
64
+ st.write(answer)