SF001-123456 commited on
Commit
e43be0f
·
verified ·
1 Parent(s): bee375d

Upload 10 files

Browse files
README.md CHANGED
@@ -1,13 +1,122 @@
1
- ---
2
- title: Chatbotv2
3
- emoji: 👁
4
- colorFrom: gray
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 5.20.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HRMS Email Automation & Legal Assistant Chatbot
2
+
3
+ ## Overview
4
+ This repository contains three separate applications:
5
+ 1. **HRMS Email Automation** - A Streamlit-based application for automating HR interview invitation emails.
6
+ 2. **Legal Assistant Chatbot** - A Streamlit-based chatbot leveraging Retrieval-Augmented Generation (RAG) for legal assistance.
7
+ 3. **Employee Performance & Retention Analytics Dashboard** - A Streamlit-based analytics dashboard providing insights into employee attrition, performance, and retention risk.
8
+
9
+ ---
10
+
11
+ ## 1️⃣ HRMS Email Automation
12
+
13
+ ### Description
14
+ The **HRMS Email Automation** tool simplifies the process of sending interview invitations via email. It provides a user-friendly form to collect candidate details and automatically sends emails for both **Online** and **Face-to-Face** interviews.
15
+
16
+ ### Features
17
+ - Select interview type: **Online** or **Face-to-Face**.
18
+ - Input relevant details like candidate name, interview time, PIC (Person in Charge), and contact details.
19
+ - Validate form fields to ensure required details are entered.
20
+ - Send email automatically using the `EmailAuto` class.
21
+ - User-friendly interface built with **Streamlit**.
22
+
23
+ ### Installation & Usage
24
+ ```sh
25
+ # Clone the repository
26
+ git clone https://github.com/your-repo.git
27
+ cd your-repo
28
+
29
+ # Install dependencies
30
+ pip install -r requirements.txt
31
+
32
+ # Run the Streamlit app
33
+ streamlit run email_ui.py
34
+ ```
35
+
36
+ ### File Structure
37
+ ```
38
+ ├── automation/
39
+ │ ├── emailAuto.py # Handles email automation
40
+ ├── email_ui.py # Streamlit UI for HRMS Email Automation
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 2️⃣ Legal Assistant Chatbot
46
+
47
+ ### Description
48
+ The **Legal Assistant Chatbot** is a chatbot designed to provide legal assistance by retrieving relevant legal context from **Pinecone** and responding based on a fine-tuned **TinyLlama** model.
49
+
50
+ ### Features
51
+ - Uses **Retrieval-Augmented Generation (RAG)** for context-aware legal responses.
52
+ - Retrieves legal documents from **Pinecone** to enhance responses.
53
+ - Fine-tuned **TinyLlama-1.1B-Chat** model for legal domain understanding.
54
+ - Interactive chat interface built with **Gradio**.
55
+ - Supports file uploads (optional).
56
+
57
+ ### Installation & Usage
58
+ ```sh
59
+ # Install dependencies
60
+ pip install -r requirements.txt
61
+
62
+ # Run the chatbot
63
+ python app.py
64
+ ```
65
+
66
+ ### File Structure
67
+ ```
68
+ ├── backend/
69
+ │ ├── train.py # Handles model training
70
+ │ ├── rag.py # Handles Pinecone-based retrieval
71
+ ├── app.py # Gradio UI for the Legal Assistant Chatbot
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 3️⃣ Employee Performance & Retention Analytics Dashboard
77
+
78
+ ### Description
79
+ The **Employee Performance & Retention Analytics Dashboard** provides insights into employee attrition, performance, and retention risk. It includes interactive visualizations, ML-based attrition predictions, and employee-specific evaluations.
80
+
81
+ ### Features
82
+ - **Attrition Prediction:** Uses a RandomForest model to predict employee attrition likelihood.
83
+ - **Performance Analysis:** Visualizations of performance rating, salary, and tenure.
84
+ - **Retention Analysis:** Highlights risks based on job satisfaction, work-life balance, and promotion history.
85
+ - **Employee Evaluation:** Individual employee performance and retention insights.
86
+ - **AI-Powered Insights:** Generates department-specific insights based on filtered employee data.
87
+
88
+ ### Installation & Usage
89
+ ```sh
90
+ # Install dependencies
91
+ pip install -r requirements.txt
92
+
93
+ # Run the Streamlit dashboard
94
+ streamlit run dashboard.py
95
+ ```
96
+
97
+ ### File Structure
98
+ ```
99
+ ├── dashboard.py # Streamlit UI for HR analytics
100
+ ├── HR-Employee-Attrition.csv # Employee dataset
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Environment Variables
106
+ Both applications require environment variables to function correctly. Create a `.env` file and add the following:
107
+ ```
108
+ PINECONE_API_KEY=your_pinecone_api_key
109
+ PINECONE_INDEX=your_pinecone_index
110
+ PINECONE_NAMESPACE=your_pinecone_namespace
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Contribution
116
+ Feel free to contribute to this project by submitting issues, pull requests, or feature suggestions!
117
+
118
+ ---
119
+
120
+ ## License
121
+ This project is licensed under the MIT License.
122
+
app.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import logging
3
+ from backend.train import ModelTrainer
4
+ from backend.rag import PineconeRetriever
5
+ from dotenv import load_dotenv
6
+ import os
7
+
8
+
9
+
10
+ load_dotenv()
11
+
12
+ # Configure logging
13
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
14
+
15
+ class ChatbotUI:
16
+ """Class for the Gradio-based chatbot UI with RAG."""
17
+ def __init__(self, model_name, pinecone_api, pinecone_index, pinecone_namespace):
18
+ logging.info("Initializing ChatbotUI...")
19
+ self.trainer = ModelTrainer(model_name)
20
+ self.retriever = PineconeRetriever(pinecone_api, pinecone_index, pinecone_namespace)
21
+ logging.info("ChatbotUI initialized successfully.")
22
+
23
+ def chatbot_response(self, input_text, history=None):
24
+ """Generate response using retrieved context and the trained model."""
25
+ if history is None:
26
+ history = []
27
+ logging.info(f"Received user input: {input_text}")
28
+
29
+ # Retrieve relevant context from Pinecone
30
+ retrieved_docs = self.retriever.retrieve_context(input_text, top_k=1)
31
+ logging.info(f"Retrieved context: {retrieved_docs}")
32
+
33
+ # Preset instruction for the legal assistant
34
+ preset = "You are a helpful assistant. You do not respond as 'User' or pretend to be 'User'. You only respond once as 'Assistant'."
35
+
36
+ # Combine retrieved context with the user query to form the prompt
37
+ prompt = f"{preset}\nContext: {retrieved_docs}\nUser: {input_text}\nResponse:"
38
+ logging.info(f"Generated prompt for TinyLlama: {prompt}")
39
+
40
+ # Generate response using the model
41
+ inputs = self.trainer.tokenizer(prompt, return_tensors="pt").input_ids
42
+ output = self.trainer.model.generate(inputs, max_length=1000)
43
+ response = self.trainer.tokenizer.decode(output[0], skip_special_tokens=True)
44
+ logging.info("Response generated successfully.")
45
+
46
+ # Ensure response does not repeat the prompt
47
+ if response.startswith(prompt):
48
+ response = response[len(prompt):].strip()
49
+
50
+ # Append the new turn to the conversation history
51
+ history.append((input_text, response))
52
+ logging.info(f"Updated conversation history: {history}")
53
+
54
+ return history, ""
55
+
56
+ def clear_conversation(self):
57
+ """Clears the entire conversation history and resets the input box."""
58
+ logging.info("Clearing conversation history.")
59
+ return [], "", []
60
+
61
+ # Optional function if you want to process uploaded files:
62
+ def process_file(self, file):
63
+ """
64
+ A placeholder function that can be used to handle file uploads.
65
+ For instance, you could read the file contents and update the conversation
66
+ or retrieve additional context from the file.
67
+ """
68
+ if file is not None:
69
+ logging.info(f"File uploaded: {file.name}")
70
+ # Example: read the file (if it's text) and do something with it.
71
+ # with open(file.name, 'r') as f:
72
+ # text_data = f.read()
73
+ # # Do something with text_data...
74
+ return "File uploaded successfully!"
75
+ return "No file uploaded."
76
+
77
+ def launch(self):
78
+ logging.info("Launching chatbot UI...")
79
+ with gr.Blocks() as demo:
80
+ # Title / Header
81
+ gr.Markdown("<h2 style='text-align: center;'>Legal Assistant Chatbot</h2>")
82
+
83
+ # Main Chatbot component
84
+ chatbot = gr.Chatbot(label="Chat")
85
+
86
+ # Textbox for user messages
87
+ msg = gr.Textbox(label="Your Message", placeholder="Enter your message here...")
88
+
89
+ # State to store conversation history
90
+ state = gr.State([])
91
+
92
+ # Define the function to update the conversation history
93
+ def user_message(message, chat_history):
94
+ return self.chatbot_response(message, chat_history)
95
+
96
+ # Submit the user's message
97
+ msg.submit(user_message, [msg, state], [chatbot, msg])
98
+
99
+ # Clear Chat button
100
+ clear_btn = gr.Button("Clear Chat")
101
+ clear_btn.click(fn=self.clear_conversation,
102
+ inputs=[],
103
+ outputs=[chatbot, msg, state],
104
+ queue=False)
105
+
106
+ # Optional File Upload (uncomment if you want to enable it)
107
+ # file_uploader = gr.File(label="Upload a Document")
108
+ # file_upload_btn = gr.Button("Process File")
109
+ # file_upload_output = gr.Textbox(label="File Processing Result")
110
+ # file_upload_btn.click(fn=self.process_file,
111
+ # inputs=[file_uploader],
112
+ # outputs=[file_upload_output])
113
+
114
+ demo.launch()
115
+
116
+ if __name__ == "__main__":
117
+ chatbot = ChatbotUI(
118
+ # model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
119
+ model_name="sainoforce/modelv3",
120
+ pinecone_api=os.getenv("PINECONE_API_KEY"),
121
+ pinecone_index=os.getenv("PINECONE_INDEX"),
122
+ pinecone_namespace=os.getenv("PINECONE_NAMESPACE")
123
+ )
124
+ chatbot.launch()
backend/__init__.py ADDED
File without changes
backend/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (173 Bytes). View file
 
backend/__pycache__/rag.cpython-312.pyc ADDED
Binary file (2.58 kB). View file
 
backend/__pycache__/train.cpython-312.pyc ADDED
Binary file (1.62 kB). View file
 
backend/data.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from datasets import Dataset
3
+
4
+ class DataLoader:
5
+ """Class for loading and merging CSV data."""
6
+ def __init__(self, csv_paths):
7
+ self.csv_paths = csv_paths
8
+
9
+ def load_data(self):
10
+ """Load multiple CSV files and merge them into a single dataset."""
11
+ dataframes = [pd.read_csv(path).dropna() for path in self.csv_paths]
12
+ combined_df = pd.concat(dataframes, ignore_index=True)
13
+ return Dataset.from_pandas(combined_df)
14
+
15
+ if __name__ == "__main__":
16
+ csv_files = ["data1.csv", "data2.csv"] # Update with actual file paths
17
+ data_loader = DataLoader(csv_files)
18
+ dataset = data_loader.load_data()
19
+ print(dataset)
backend/rag.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pinecone import Pinecone
2
+ from dotenv import load_dotenv
3
+ import os
4
+
5
+ load_dotenv()
6
+ class PineconeRetriever:
7
+ """Class for initializing and querying Pinecone."""
8
+ def __init__(self, api_key, index_name, namespace):
9
+ self.api_key = api_key
10
+ self.index_name = index_name
11
+ self.namespace = namespace
12
+ self.pc = Pinecone(api_key=self.api_key)
13
+ self.index = self.pc.Index(self.index_name)
14
+
15
+ def retrieve_data(self, query, top_k=1):
16
+ """Retrieve relevant data from Pinecone."""
17
+ # Convert the query into a numerical vector that Pinecone can search with
18
+ query_embedding = self.pc.inference.embed(
19
+ model="multilingual-e5-large",
20
+ inputs=[query],
21
+ parameters={
22
+ "input_type": "query",
23
+ "truncate": "END"
24
+ }
25
+ )
26
+
27
+ results = self.index.query(namespace=self.namespace,
28
+ vector=query_embedding[0].values,
29
+ top_k=top_k,
30
+ include_values=False,
31
+ include_metadata=True
32
+ )
33
+
34
+ return results
35
+
36
+ def retrieve_context(self, query, top_k=1):
37
+ results = self.retrieve_data(query, top_k)
38
+ context = ""
39
+ for match in results['matches']:
40
+ context += match['metadata']['source_text']
41
+ return context
42
+
43
+ if __name__ == "__main__":
44
+ pinecone_api=os.getenv("PINECONE_API_KEY"),
45
+ pinecone_index=os.getenv("PINECONE_INDEX"),
46
+ pinecone_namespace=os.getenv("PINECONE_NAMESPACE")
47
+
48
+ retriever = PineconeRetriever(API_KEY, INDEX_NAME, NAMESPACE)
49
+ query_result = retriever.retrieve_context("hi")
50
+ print(query_result)
backend/train.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ import torch
3
+
4
+ class ModelTrainer:
5
+ """Class for loading and training a TinyLlama model."""
6
+ def __init__(self, model_name):
7
+ self.model_name = model_name
8
+ self.model, self.tokenizer = self.load_model()
9
+
10
+ def load_model(self):
11
+ """Load a pre-trained model and tokenizer."""
12
+ print(f"Loading model: {self.model_name}")
13
+
14
+ device = "cuda" if torch.cuda.is_available() else "cpu"
15
+ model = AutoModelForCausalLM.from_pretrained(self.model_name).to(device)
16
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name)
17
+ return model, tokenizer
18
+
19
+ if __name__ == "__main__":
20
+ # Load model directly
21
+
22
+ model_name = "sainoforce/modelv2"
23
+ trainer = ModelTrainer(model_name)
24
+ print("Model and tokenizer loaded successfully.")
requirements.txt ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ datasets
3
+ accelerate
4
+ bitsandbytes
5
+ peft
6
+ gradio
7
+ matplotlib
8
+ numpy
9
+ pinecone[grpc]
10
+ nltk
11
+ altair==5.5.0
12
+ attrs==25.1.0
13
+ blinker==1.9.0
14
+ cachetools==5.5.2
15
+ certifi==2025.1.31
16
+ charset-normalizer==3.4.1
17
+ click==8.1.8
18
+ colorama==0.4.6
19
+ dotenv==0.9.9
20
+ gitdb==4.0.12
21
+ GitPython==3.1.44
22
+ idna==3.10
23
+ Jinja2==3.1.6
24
+ jsonschema==4.23.0
25
+ jsonschema-specifications==2024.10.1
26
+ MarkupSafe==3.0.2
27
+ narwhals==1.29.1
28
+ numpy==2.2.3
29
+ packaging==24.2
30
+ pandas==2.2.3
31
+ pillow==11.1.0
32
+ protobuf==5.29.3
33
+ pyarrow==19.0.1
34
+ pydeck==0.9.1
35
+ python-dateutil==2.9.0.post0
36
+ python-dotenv==1.0.1
37
+ pytz==2025.1
38
+ referencing==0.36.2
39
+ requests==2.32.3
40
+ rpds-py==0.23.1
41
+ six==1.17.0
42
+ smmap==5.0.2
43
+ streamlit==1.43.1
44
+ tenacity==9.0.0
45
+ toml==0.10.2
46
+ tornado==6.4.2
47
+ typing_extensions==4.12.2
48
+ tzdata==2025.1
49
+ urllib3==2.3.0
50
+ watchdog==6.0.0
51
+ streamlit
52
+ pandas
53
+ plotly
54
+ scikit-learn
55
+
56
+
57
+
58
+