krisha06 commited on
Commit
21b2f6b
Β·
verified Β·
1 Parent(s): 49a2334

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -39
app.py CHANGED
@@ -6,30 +6,35 @@ import streamlit as st
6
  # Use CPU
7
  device = torch.device("cpu")
8
 
 
 
 
 
 
9
  # Load tokenizer and base model
10
- tokenizer = AutoTokenizer.from_pretrained("TinyLLaMA/TinyLLaMA-1.1B-Chat-v1.0")
11
- base_model = AutoModelForCausalLM.from_pretrained(
12
- "TinyLLaMA/TinyLLaMA-1.1B-Chat-v1.0",
13
- torch_dtype=torch.float32,
14
- device_map=None
15
- ).to(device)
16
 
17
- # Load LoRA adapter
18
- model = PeftModel.from_pretrained(base_model, "lora_adapter").to(device)
19
- model.eval()
 
20
 
21
- # Load zero-shot classifier for topic filtering
22
- classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", device=-1)
23
 
24
- # Streamlit UI
25
- st.set_page_config(page_title="Python Tutor", page_icon="🐍")
26
- st.title("🧠 TinyLLaMA Python Tutor (LoRA)")
27
- st.markdown("Ask me any *Python programming* question below:")
28
 
29
- # Input box
 
 
30
  user_question = st.text_input("Your question:")
31
 
32
- # Function to filter Python-related questions
33
  def is_python_related(question):
34
  candidate_labels = [
35
  "Python programming", "Java programming", "General knowledge",
@@ -38,7 +43,7 @@ def is_python_related(question):
38
  result = classifier(question, candidate_labels)
39
  return result['labels'][0] == "Python programming"
40
 
41
- # Format code blocks
42
  def format_code_blocks(text):
43
  if "```" in text:
44
  return text
@@ -58,7 +63,7 @@ def format_code_blocks(text):
58
  formatted.append("```")
59
  return "\n".join(formatted)
60
 
61
- # Handle input
62
  if user_question:
63
  if len(user_question.strip()) < 10:
64
  st.warning("Please ask a more specific Python question.")
@@ -68,35 +73,29 @@ if user_question:
68
  st.error("Sorry, I am a Python tutor. I cannot answer this.")
69
  else:
70
  with st.spinner("Thinking..."):
71
- # Prompt to keep model focused
72
- prompt = f"""
73
- You are a helpful assistant that only answers questions about Python programming.
74
 
75
- Instructions:
76
- - If a question is not related to Python, do not answer it.
77
- - Focus strictly on Python concepts, syntax, libraries, and best practices.
78
- - Answer clearly and include code examples if helpful.
79
 
80
  Question: {user_question}
81
  Answer:"""
82
 
83
- # Tokenize input
84
  inputs = tokenizer(prompt, return_tensors="pt").to(device)
85
 
86
- # Generate output
87
  with torch.inference_mode():
88
  output = model.generate(
89
- **inputs,
90
- max_new_tokens=512, # increase if needed
91
- do_sample=False,
92
- repetition_penalty=1.1,
93
- eos_token_id=tokenizer.eos_token_id,
94
- pad_token_id=tokenizer.pad_token_id
95
- )
96
- # Decode and clean output
97
  decoded = tokenizer.decode(output[0], skip_special_tokens=True)
98
- answer = decoded.split("Answer:")[-1].strip()
 
99
 
100
- # Display response
101
  st.markdown("### πŸ’‘ Answer:")
102
- st.markdown(format_code_blocks(answer))
 
 
6
  # Use CPU
7
  device = torch.device("cpu")
8
 
9
+ # Set page config
10
+ st.set_page_config(page_title="Python Tutor", page_icon="🐍")
11
+ st.title("🧠 TinyLLaMA Python Tutor (LoRA)")
12
+ st.markdown("Ask me any *Python programming* question below:")
13
+
14
  # Load tokenizer and base model
15
+ @st.cache_resource
16
+ def load_model():
17
+ tokenizer = AutoTokenizer.from_pretrained("TinyLLaMA/TinyLLaMA-1.1B-Chat-v1.0")
18
+ tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token
 
 
19
 
20
+ base_model = AutoModelForCausalLM.from_pretrained(
21
+ "TinyLLaMA/TinyLLaMA-1.1B-Chat-v1.0",
22
+ torch_dtype=torch.float32,
23
+ ).to(device)
24
 
25
+ model = PeftModel.from_pretrained(base_model, "lora_adapter").to(device)
26
+ model.eval()
27
 
28
+ classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", device=-1)
29
+
30
+ return tokenizer, model, classifier
 
31
 
32
+ tokenizer, model, classifier = load_model()
33
+
34
+ # User input
35
  user_question = st.text_input("Your question:")
36
 
37
+ # Helper to check topic relevance
38
  def is_python_related(question):
39
  candidate_labels = [
40
  "Python programming", "Java programming", "General knowledge",
 
43
  result = classifier(question, candidate_labels)
44
  return result['labels'][0] == "Python programming"
45
 
46
+ # Code block formatter
47
  def format_code_blocks(text):
48
  if "```" in text:
49
  return text
 
63
  formatted.append("```")
64
  return "\n".join(formatted)
65
 
66
+ # Process the question
67
  if user_question:
68
  if len(user_question.strip()) < 10:
69
  st.warning("Please ask a more specific Python question.")
 
73
  st.error("Sorry, I am a Python tutor. I cannot answer this.")
74
  else:
75
  with st.spinner("Thinking..."):
 
 
 
76
 
77
+ prompt = f"""You are a helpful and knowledgeable Python programming tutor.
78
+ Always provide short, clear, beginner-friendly explanations with examples.
 
 
79
 
80
  Question: {user_question}
81
  Answer:"""
82
 
 
83
  inputs = tokenizer(prompt, return_tensors="pt").to(device)
84
 
 
85
  with torch.inference_mode():
86
  output = model.generate(
87
+ **inputs,
88
+ max_new_tokens=512,
89
+ do_sample=False,
90
+ repetition_penalty=1.1,
91
+ eos_token_id=tokenizer.eos_token_id,
92
+ pad_token_id=tokenizer.pad_token_id
93
+ )
94
+
95
  decoded = tokenizer.decode(output[0], skip_special_tokens=True)
96
+ answer = decoded.split("Answer:")[-1].split("Question:")[0].strip() # clean hallucinated extra question
97
+ formatted = format_code_blocks(answer)
98
 
 
99
  st.markdown("### πŸ’‘ Answer:")
100
+ with st.expander("πŸ” Click to view full response"):
101
+ st.markdown(formatted)