Harika22 commited on
Commit
d1a58c4
Β·
verified Β·
1 Parent(s): 24c4109

Update pages/model.py

Browse files
Files changed (1) hide show
  1. pages/model.py +53 -33
pages/model.py CHANGED
@@ -1,60 +1,80 @@
 
1
  import streamlit as st
2
  import pickle
3
  import re
4
  import numpy as np
 
 
 
 
5
 
6
  st.set_page_config(page_title="πŸ”– TagGPT - Auto Tag Your Questions", layout="centered")
7
 
8
- def clean_text(raw_text):
9
- raw_text = re.sub(r"<.*?>", " ", raw_text) # Remove HTML tags
10
- raw_text = re.sub(r"[^a-zA-Z0-9\s]", " ", raw_text) # Remove special characters
11
- raw_text = re.sub(r"\s+", " ", raw_text.lower()).strip() # Lowercase & strip spaces
12
- return raw_text
13
 
14
  @st.cache_resource
 
15
  def load_assets():
16
- try:
17
- with open("model.pkl", "rb") as m:
18
- tag_model = pickle.load(m)
19
- with open("tfidf.pkl", "rb") as v:
20
- text_vectorizer = pickle.load(v)
21
- with open("mlb.pkl", "rb") as e:
22
- tag_encoder = pickle.load(e)
23
- return tag_model, text_vectorizer, tag_encoder
24
- except Exception as error:
25
- st.error(f"❌ Failed to load model components: {error}")
26
- st.stop()
27
 
28
  tag_model, text_vectorizer, tag_encoder = load_assets()
29
 
30
- st.title("🎯 TagGPT - Smart Stack Overflow Tag Suggester")
31
- st.markdown("πŸš€ **Automatically generate relevant tags for your coding questions.**")
32
- st.markdown("Just enter your question title and description, and let AI do the tagging!")
 
 
 
 
33
 
34
- question_title = st.text_input("🧠 Enter the **Question Title**")
35
- question_description = st.text_area("πŸ“ Provide a **Detailed Description**", height=200)
36
- confidence_threshold = st.slider("πŸ“ˆ Select Tag Confidence Threshold", 0.1, 0.9, 0.3, 0.05)
 
 
37
 
38
  if st.button("πŸ” Predict Tags"):
39
- if not question_title.strip() or not question_description.strip():
40
- st.warning("⚠️ Both title and description are required!")
41
  else:
42
- combined_input = clean_text(question_title + " " + question_description)
43
  transformed_input = text_vectorizer.transform([combined_input])
44
 
45
  try:
46
  if hasattr(tag_model, "predict_proba"):
47
- probs = tag_model.predict_proba(transformed_input)
48
- tag_preds = (probs >= confidence_threshold).astype(int)
49
  else:
50
- tag_preds = tag_model.predict(transformed_input)
 
51
 
52
- final_tags = tag_encoder.inverse_transform(tag_preds)
 
53
 
54
- if final_tags and final_tags[0]:
55
- st.success("🏷️ **Predicted Tags:**")
56
- st.markdown("πŸ”Έ " + ", ".join(final_tags[0]))
 
57
  else:
58
- st.info("πŸ€– No tags predicted. Try adjusting the threshold or refining your input.")
 
 
 
 
 
 
 
 
 
 
 
59
  except Exception as error:
60
  st.error(f"🚫 Prediction failed: {error}")
 
1
+
2
  import streamlit as st
3
  import pickle
4
  import re
5
  import numpy as np
6
+ import pandas as pd
7
+ from io import StringIO
8
+ from streamlit_lottie import st_lottie
9
+ import json
10
 
11
  st.set_page_config(page_title="πŸ”– TagGPT - Auto Tag Your Questions", layout="centered")
12
 
13
+ def load_lottie(filepath: str):
14
+ with open(filepath, "r") as f:
15
+ return json.load(f)
 
 
16
 
17
  @st.cache_resource
18
+
19
  def load_assets():
20
+ with open("model.pkl", "rb") as m:
21
+ tag_model = pickle.load(m)
22
+ with open("tfidf.pkl", "rb") as v:
23
+ text_vectorizer = pickle.load(v)
24
+ with open("mlb.pkl", "rb") as e:
25
+ tag_encoder = pickle.load(e)
26
+ return tag_model, text_vectorizer, tag_encoder
 
 
 
 
27
 
28
  tag_model, text_vectorizer, tag_encoder = load_assets()
29
 
30
+ def clean_text(raw_text):
31
+ raw_text = re.sub(r"<.*?>", " ", raw_text) # Remove HTML tags
32
+ raw_text = re.sub(r"[^a-zA-Z0-9\s]", " ", raw_text) # Remove special characters
33
+ raw_text = re.sub(r"\s+", " ", raw_text.lower()).strip()
34
+ return raw_text
35
+
36
+ st_lottie(load_lottie("tag_animation.json"), height=150, key="intro") # Lottie animation (optional)
37
 
38
+ st.title("🏷️ TagGPT - Smart Stack Overflow Tag Suggester")
39
+ st.markdown("**πŸš€ Instantly generate relevant tags for your coding questions using AI.**")
40
+
41
+ q_title = st.text_input("🧠 Enter your question title")
42
+ q_desc = st.text_area("πŸ“ Describe your problem in detail", height=200)
43
 
44
  if st.button("πŸ” Predict Tags"):
45
+ if not q_title.strip() or not q_desc.strip():
46
+ st.warning("⚠️ Please provide both title and description.")
47
  else:
48
+ combined_input = clean_text(q_title + " " + q_desc)
49
  transformed_input = text_vectorizer.transform([combined_input])
50
 
51
  try:
52
  if hasattr(tag_model, "predict_proba"):
53
+ probs = tag_model.predict_proba(transformed_input)[0]
54
+ pred_tags = (probs >= 0.3).astype(int) # Fixed threshold
55
  else:
56
+ pred_tags = tag_model.predict(transformed_input)[0]
57
+ probs = pred_tags
58
 
59
+ tag_names = tag_encoder.classes_
60
+ selected_tags = [(tag, round(probs[i]*100, 2)) for i, tag in enumerate(tag_names) if pred_tags[i] == 1]
61
 
62
+ if selected_tags:
63
+ st.success("🏷️ **Predicted Tags with Confidence:**")
64
+ for tag, score in selected_tags:
65
+ st.markdown(f"**{tag}** β€” `{score}%`")
66
  else:
67
+ st.info("πŸ€– No tags predicted. Try refining your input.")
68
+
69
+ # --- Download Option
70
+ tag_list = [tag for tag, _ in selected_tags]
71
+ df = pd.DataFrame({
72
+ "Title": [q_title],
73
+ "Description": [q_desc],
74
+ "Predicted Tags": [", ".join(tag_list)]
75
+ })
76
+ csv = df.to_csv(index=False).encode('utf-8')
77
+ st.download_button("πŸ“₯ Download Tags as CSV", data=csv, file_name="tag_predictions.csv", mime='text/csv')
78
+
79
  except Exception as error:
80
  st.error(f"🚫 Prediction failed: {error}")