ChijoTheDatascientist commited on
Commit
cd8911f
1 Parent(s): bebb6bb

chatbot code to summarize and give insight

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from huggingface_hub import InferenceClient
4
+ import streamlit as st
5
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
6
+ from langchain_core.prompts import PromptTemplate
7
+ from langchain_core.output_parsers import StrOutputParser
8
+
9
+ # Load HF_TOKEN securely
10
+ hf_token = os.getenv("HF_TOKEN")
11
+
12
+ # Set up the Hugging Face Inference Client with the Bearer token
13
+ client = InferenceClient(api_key=f"Bearer {hf_token}")
14
+
15
+ # Model paths and IDs
16
+ model_id = "mistralai/Mistral-7B-Instruct-v0.3"
17
+ bart_model_path = "ChijoTheDatascientist/summarization-model"
18
+
19
+ # Load BART model for summarization
20
+ device = torch.device('cpu')
21
+ bart_tokenizer = AutoTokenizer.from_pretrained(bart_model_path)
22
+ bart_model = AutoModelForSeq2SeqLM.from_pretrained(bart_model_path).to(device)
23
+
24
+ @st.cache_data
25
+ def summarize_review(review_text):
26
+ inputs = bart_tokenizer(review_text, max_length=1024, truncation=True, return_tensors="pt")
27
+ summary_ids = bart_model.generate(inputs["input_ids"], max_length=40, min_length=10, length_penalty=2.0, num_beams=8, early_stopping=True)
28
+ summary = bart_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
29
+ return summary
30
+
31
+ def generate_response(system_message, user_input, chat_history, max_new_tokens=128):
32
+ try:
33
+ # Prepare the messages for the Hugging Face Inference API
34
+ messages = [{"role": "user", "content": user_input}]
35
+
36
+ # Call the Inference API
37
+ completion = client.chat.completions.create(
38
+ model=model_id,
39
+ messages=messages,
40
+ max_tokens=max_new_tokens,
41
+ )
42
+
43
+ # Get the response from the API
44
+ response = completion.choices[0].message["content"]
45
+ return response
46
+
47
+ except Exception as e:
48
+ return f"Error generating response: {e}"
49
+
50
+ # Streamlit app configuration
51
+ st.set_page_config(page_title="Insight Snap & Summarizer")
52
+ st.title("Insight Snap & Summarizer")
53
+
54
+ st.markdown("""
55
+ - Use specific keywords in your queries to get targeted responses:
56
+ - **"summarize"**: To summarize customer reviews.
57
+ - **"Feedback or insights"**: Get actionable business insights based on feedback.
58
+ """)
59
+
60
+ # Initialize session state for chat history
61
+ if "chat_history" not in st.session_state:
62
+ st.session_state.chat_history = []
63
+
64
+ # Chat interface
65
+ user_input = st.text_area("Enter customer reviews or a question:")
66
+
67
+ if st.button("Submit"):
68
+ if user_input:
69
+ # Summarize if the query is feedback-related
70
+ if "summarize" in user_input.lower():
71
+ summary = summarize_review(user_input)
72
+ st.markdown(f"**Summary:** \n{summary}")
73
+ elif "insight" in user_input.lower() or "feedback" in user_input.lower():
74
+ system_message = (
75
+ "You are a helpful assistant providing actionable insights "
76
+ "from customer feedback to help businesses improve their services."
77
+ )
78
+ # Use the last summarized text if available
79
+ last_summary = st.session_state.get("last_summary", "")
80
+ query_input = last_summary if last_summary else user_input
81
+ response = generate_response(system_message, query_input, st.session_state.chat_history)
82
+
83
+ if response:
84
+ # Update chat history
85
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
86
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
87
+ st.markdown(f"**Insight:** \n{response}")
88
+ else:
89
+ st.warning("No response generated. Please try again later.")
90
+ else:
91
+ st.warning("Please specify if you want to 'summarize' or get 'insights'.")
92
+
93
+ # Store the last summary for insights
94
+ if "summarize" in user_input.lower():
95
+ st.session_state["last_summary"] = summary
96
+ else:
97
+ st.warning("Please enter customer reviews or ask for insights.")
98
+
99
+