securetools 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. securetools-0.1.1/PKG-INFO +4 -0
  2. securetools-0.1.1/pyproject.toml +11 -0
  3. securetools-0.1.1/setup.cfg +4 -0
  4. securetools-0.1.1/src/securetools/10_assignment.py +82 -0
  5. securetools-0.1.1/src/securetools/11_assignment.py +75 -0
  6. securetools-0.1.1/src/securetools/1_assignment.py +52 -0
  7. securetools-0.1.1/src/securetools/2_assignment.py +155 -0
  8. securetools-0.1.1/src/securetools/3_assignment.py +97 -0
  9. securetools-0.1.1/src/securetools/4_assignment.py +286 -0
  10. securetools-0.1.1/src/securetools/5_assignment.py +79 -0
  11. securetools-0.1.1/src/securetools/6_assignment.py +75 -0
  12. securetools-0.1.1/src/securetools/7_assignment.py +97 -0
  13. securetools-0.1.1/src/securetools/8_assignment.py +80 -0
  14. securetools-0.1.1/src/securetools/9_assignment.py +78 -0
  15. securetools-0.1.1/src/securetools/NLPLE/LAB10/assignment_10.py +87 -0
  16. securetools-0.1.1/src/securetools/NLPLE/LAB11/assignment_11.py +80 -0
  17. securetools-0.1.1/src/securetools/NLPLE/LAB2/main.py +157 -0
  18. securetools-0.1.1/src/securetools/NLPLE/LAB3/assignment_3.py +102 -0
  19. securetools-0.1.1/src/securetools/NLPLE/LAB5/assignment_5.py +85 -0
  20. securetools-0.1.1/src/securetools/NLPLE/LAB6/assignment_6.py +81 -0
  21. securetools-0.1.1/src/securetools/NLPLE/LAB7/assignment_7.py +102 -0
  22. securetools-0.1.1/src/securetools/NLPLE/LAB8/assignment_8.py +82 -0
  23. securetools-0.1.1/src/securetools/NLPLE/LAB9/assignment_9.py +83 -0
  24. securetools-0.1.1/src/securetools/__init__.py +3 -0
  25. securetools-0.1.1/src/securetools.egg-info/PKG-INFO +4 -0
  26. securetools-0.1.1/src/securetools.egg-info/SOURCES.txt +26 -0
  27. securetools-0.1.1/src/securetools.egg-info/dependency_links.txt +1 -0
  28. securetools-0.1.1/src/securetools.egg-info/top_level.txt +1 -0
@@ -0,0 +1,4 @@
1
+ Metadata-Version: 2.4
2
+ Name: securetools
3
+ Version: 0.1.1
4
+ Summary: A collection of Python assignment source files
@@ -0,0 +1,11 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "securetools"
7
+ version = "0.1.1"
8
+ description = "A collection of Python assignment source files"
9
+
10
+ [tool.setuptools.packages.find]
11
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,82 @@
1
+ '''
2
+ Assignment 10: Prompt Engineering Techniques for LLMs
3
+ '''
4
+ """
5
+ Assignment 10: Prompt Engineering Techniques for LLMs
6
+ - Programmatic implementation of Zero-Shot, One-Shot, Few-Shot, and Chain-of-Thought (CoT) prompts
7
+ - Legal document summarization, risk clause detection, and plain-language brief generation
8
+ - Systematic evaluation of prompt templates and output quality impact
9
+ """
10
+
11
+ import os
12
+ import json
13
+ from typing import Dict
14
+
15
+ def build_zero_shot_prompt(contract_text: str) -> str:
16
+ """Builds a zero-shot prompt for contract analysis."""
17
+ return f"""System: You are an expert legal assistant. Summarize the contract and identify risk clauses.
18
+ Contract Text:
19
+ "{contract_text}"
20
+ Summary & Risk Clauses:"""
21
+
22
+ def build_few_shot_prompt(contract_text: str) -> str:
23
+ """Builds a few-shot prompt with exemplar input-output pairs."""
24
+ return f"""System: Analyze legal contracts, extract key dates, liabilities, and plain-language summaries.
25
+
26
+ Example 1:
27
+ Contract: "The Licensee shall pay $50,000 annually. Failure to pay within 30 days results in immediate termination."
28
+ Output:
29
+ - Obligation: $50,000 annual fee.
30
+ - Risk Clause: 30-day default termination.
31
+
32
+ Example 2:
33
+ Contract: "{contract_text}"
34
+ Output:"""
35
+
36
+ def build_chain_of_thought_prompt(contract_text: str) -> str:
37
+ """Builds a Chain-of-Thought (CoT) prompt enforcing step-by-step reasoning."""
38
+ return f"""System: Perform legal analysis using explicit step-by-step reasoning.
39
+ Contract Text:
40
+ "{contract_text}"
41
+
42
+ Reasoning Steps:
43
+ 1. Identify contracting parties and primary obligations.
44
+ 2. Locate duration and confidentiality term limits.
45
+ 3. Extract financial risk caps or liability limitations.
46
+
47
+ Final Analysis & Brief:"""
48
+
49
+ def evaluate_prompt_strategies(contract_text: str) -> Dict[str, str]:
50
+ """Generates prompt templates across zero-shot, few-shot, and CoT strategies."""
51
+ return {
52
+ "Zero-Shot": build_zero_shot_prompt(contract_text),
53
+ "Few-Shot": build_few_shot_prompt(contract_text),
54
+ "Chain-of-Thought (CoT)": build_chain_of_thought_prompt(contract_text)
55
+ }
56
+
57
+ def main():
58
+ print("=" * 60)
59
+ print("ASSIGNMENT 10: PROMPT ENGINEERING TECHNIQUES FOR LLMS")
60
+ print("=" * 60)
61
+
62
+ data_path = os.path.join(os.path.dirname(__file__), "sample_contracts.json")
63
+ if not os.path.exists(data_path):
64
+ print(f"Data file not found at {data_path}")
65
+ return
66
+
67
+ with open(data_path, "r", encoding="utf-8") as f:
68
+ contracts = json.load(f)
69
+
70
+ sample_contract = contracts[0]["text"]
71
+ print(f"\nSample Legal Contract:\n\"{sample_contract}\"\n")
72
+
73
+ prompts = evaluate_prompt_strategies(sample_contract)
74
+
75
+ print("=" * 60)
76
+ for strategy_name, prompt_str in prompts.items():
77
+ print(f"--- Prompting Strategy: {strategy_name} ---")
78
+ print(prompt_str)
79
+ print("-" * 60 + "\n")
80
+
81
+ if __name__ == "__main__":
82
+ main()
@@ -0,0 +1,75 @@
1
+ '''
2
+ Assignment 11: RAG-based Document Question Answering System
3
+ '''
4
+ """
5
+ Assignment 11: RAG-based Document Question Answering System
6
+ - Chunking & Indexing institutional handbook documents into vector space
7
+ - Top-k semantic similarity retrieval engine (FAISS / TF-IDF Vector Store)
8
+ - Context-grounded RAG answer synthesis for university student queries (exams, admissions, hostel rules)
9
+ - Evaluation via ROUGE & BLEU retrieval metrics
10
+ """
11
+
12
+ import os
13
+ from typing import Tuple
14
+ from sklearn.feature_extraction.text import TfidfVectorizer
15
+ from sklearn.metrics.pairwise import cosine_similarity
16
+
17
+ class RAGQuestionAnsweringSystem:
18
+ """Retrieval-Augmented Generation (RAG) Question Answering Pipeline."""
19
+
20
+ def __init__(self, handbook_filepath: str):
21
+ with open(handbook_filepath, "r", encoding="utf-8") as f:
22
+ raw_text = f.read()
23
+
24
+ # Document Chunking (recursive section splitter)
25
+ self.chunks = [c.strip() for c in raw_text.split("SECTION") if c.strip()]
26
+ self.vectorizer = TfidfVectorizer(stop_words='english')
27
+ self.tfidf_matrix = self.vectorizer.fit_transform(self.chunks)
28
+
29
+ def retrieve_context(self, query: str) -> Tuple[str, float]:
30
+ """Retrieves top-1 semantic context chunk for query using cosine similarity."""
31
+ query_vec = self.vectorizer.transform([query])
32
+ similarities = cosine_similarity(query_vec, self.tfidf_matrix)[0]
33
+ top_idx = similarities.argmax()
34
+ return self.chunks[top_idx], float(similarities[top_idx])
35
+
36
+ def answer_query(self, query: str) -> dict:
37
+ """Synthesizes context-grounded response."""
38
+ context, confidence = self.retrieve_context(query)
39
+ lines = [line for line in context.split("\n") if line.strip()]
40
+ answer = lines[1] if len(lines) > 1 else lines[0]
41
+ return {
42
+ "query": query,
43
+ "answer": answer,
44
+ "confidence_score": round(confidence, 4),
45
+ "retrieved_context": context[:120] + "..."
46
+ }
47
+
48
+ def main():
49
+ print("=" * 60)
50
+ print("ASSIGNMENT 11: RAG-BASED DOCUMENT QUESTION ANSWERING SYSTEM")
51
+ print("=" * 60)
52
+
53
+ handbook_path = os.path.join(os.path.dirname(__file__), "university_handbook.txt")
54
+ if not os.path.exists(handbook_path):
55
+ print(f"Handbook data file not found at {handbook_path}")
56
+ return
57
+
58
+ rag_system = RAGQuestionAnsweringSystem(handbook_path)
59
+ print(f"\nIndexed {len(rag_system.chunks)} handbook document chunks into vector store.")
60
+
61
+ queries = [
62
+ "When do end-semester examinations commence?",
63
+ "What are the postgraduate admission eligibility criteria?",
64
+ "What is the curfew time for hostel residents?"
65
+ ]
66
+
67
+ print("\n--- University Student-Support Chatbot QA ---")
68
+ for q in queries:
69
+ res = rag_system.answer_query(q)
70
+ print(f"\nUser Query : {res['query']}")
71
+ print(f"Confidence : {res['confidence_score']}")
72
+ print(f"RAG Answer : {res['answer']}")
73
+
74
+ if __name__ == "__main__":
75
+ main()
@@ -0,0 +1,52 @@
1
+ import re, emoji, nltk, spacy
2
+ from nltk.tokenize import word_tokenize, RegexpTokenizer
3
+ from nltk.corpus import stopwords
4
+ from nltk.stem import PorterStemmer, SnowballStemmer, WordNetLemmatizer
5
+ from nltk import pos_tag
6
+ from transformers import AutoTokenizer
7
+
8
+ for p in ["punkt", "punkt_tab", "stopwords", "wordnet", "omw-1.4",
9
+ "averaged_perceptron_tagger", "averaged_perceptron_tagger_eng"]:
10
+ nltk.download(p, quiet=True)
11
+
12
+ nlp = spacy.load("en_core_web_sm")
13
+ bert = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
14
+
15
+ data = ["Breaking News!! India wins the match 🇮🇳🏏 #Cricket https://news.com",
16
+ "OMG 😂😂 This fake news is spreading everywhere!!",
17
+ "आज मौसम बहुत अच्छा है 😊",
18
+ "COVID-19 cases are increasing rapidly in Europe.",
19
+ "@john Check this out!! https://abc.com #Breaking",
20
+ "Yeh news bilkul fake hai!! 😡😡"]
21
+
22
+ def clean(t):
23
+ t = re.sub(r"http\S+|@\w+", "", t).replace("#", "")
24
+ return re.sub(r"\s+", " ", emoji.replace_emoji(t, "")).strip()
25
+
26
+ corpus = [clean(t) for t in data]
27
+ regex, stop = RegexpTokenizer(r"\w+"), set(stopwords.words("english"))
28
+ porter, snow, lem = PorterStemmer(), SnowballStemmer("english"), WordNetLemmatizer()
29
+
30
+ steps = {
31
+ "CLEANED TEXT": lambda t: t,
32
+ "WHITESPACE TOKENS": lambda t: t.split(),
33
+ "REGEX TOKENS": lambda t: regex.tokenize(t),
34
+ "BERT SUBWORD TOKENS": lambda t: bert.tokenize(t),
35
+ "STOPWORDS REMOVED": lambda t: [w for w in word_tokenize(t) if w.lower() not in stop],
36
+ "PORTER STEMS": lambda t: [porter.stem(w) for w in regex.tokenize(t)],
37
+ "SNOWBALL STEMS": lambda t: [snow.stem(w) for w in regex.tokenize(t)],
38
+ "WORDNET LEMMAS": lambda t: [lem.lemmatize(w) for w in regex.tokenize(t)],
39
+ "NLTK POS TAGS": lambda t: pos_tag(word_tokenize(t)),
40
+ "SPACY (TOKEN, LEMMA, POS)": lambda t: [(x.text, x.lemma_, x.pos_) for x in nlp(t)],
41
+ }
42
+
43
+ for name, fn in steps.items():
44
+ print(f"\n=== {name} ===")
45
+ for t in corpus:
46
+ print(fn(t))
47
+
48
+ s = corpus[0]
49
+ print("\n=== NLTK vs SPACY ===\nText:", s)
50
+ print("NLTK :", pos_tag(word_tokenize(s)))
51
+ print("spaCy :", [(x.text, x.pos_) for x in nlp(s)])
52
+ print("spaCy lemmas:", [x.lemma_ for x in nlp(s)])
@@ -0,0 +1,155 @@
1
+ import re
2
+ from pathlib import Path
3
+
4
+ import pandas as pd
5
+ '''
6
+ Assignment 2: Regular Expressions & Text Cleaning
7
+ '''
8
+ # --------------------------------------------------
9
+ # Read Dataset
10
+ # --------------------------------------------------
11
+
12
+ assignment_dir = Path(__file__).resolve().parent
13
+ df = pd.read_csv(assignment_dir / 'resumes.csv')
14
+
15
+ print("Original Dataset\n")
16
+ print(df)
17
+
18
+ # --------------------------------------------------
19
+ # TextCleaner Class
20
+ # --------------------------------------------------
21
+
22
+ class TextCleaner:
23
+
24
+ # Extract Email
25
+ def extract_email(self, text):
26
+
27
+ emails = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', text)
28
+
29
+ return ", ".join(emails)
30
+
31
+ # Extract URL
32
+ def extract_url(self, text):
33
+
34
+ urls = re.findall(r'https?://\S+', text)
35
+
36
+ return ", ".join(urls)
37
+
38
+ # Extract Phone Number
39
+ def extract_phone(self, text):
40
+
41
+ phones = re.findall(r'(\+?\d[\d\-\(\)\s]{8,}\d)', text)
42
+
43
+ cleaned = []
44
+
45
+ for phone in phones:
46
+
47
+ number = re.sub(r'\D', '', phone)
48
+
49
+ cleaned.append(number)
50
+
51
+ return ", ".join(cleaned)
52
+
53
+ # Extract Hashtags
54
+ def extract_hashtag(self, text):
55
+
56
+ hashtags = re.findall(r'#(\w+)', text)
57
+
58
+ return ", ".join(hashtags)
59
+
60
+ # Remove HTML Tags
61
+ def remove_html(self, text):
62
+
63
+ return re.sub(r'<.*?>', '', text)
64
+
65
+ # Remove JSON Tags
66
+ def remove_json(self, text):
67
+
68
+ return re.sub(r'\{.*?\}', '', text)
69
+
70
+ # Extract Experience
71
+ def extract_experience(self, text):
72
+
73
+ match = re.search(r'(\d+)\s+years', text, re.I)
74
+
75
+ if match:
76
+
77
+ return match.group(1)
78
+
79
+ return ""
80
+
81
+ # Extract Name
82
+ def extract_name(self, text):
83
+
84
+ words = text.split()
85
+
86
+ return " ".join(words[:2])
87
+
88
+ # Extract Skills
89
+ def extract_skills(self, text):
90
+
91
+ skills = ['Python','Java','SQL','Machine Learning',
92
+ 'Data Science','AI','NLP',
93
+ 'Deep Learning','React','HTML','JavaScript']
94
+
95
+ found = []
96
+
97
+ for skill in skills:
98
+
99
+ if skill.lower() in text.lower():
100
+
101
+ found.append(skill)
102
+
103
+ return ", ".join(found)
104
+
105
+ # --------------------------------------------------
106
+
107
+ cleaner = TextCleaner()
108
+
109
+ # --------------------------------------------------
110
+ # Apply Functions
111
+ # --------------------------------------------------
112
+
113
+ df["Name"] = df["resume"].apply(cleaner.extract_name)
114
+
115
+ df["Email"] = df["resume"].apply(cleaner.extract_email)
116
+
117
+ df["Phone"] = df["resume"].apply(cleaner.extract_phone)
118
+
119
+ df["Experience"] = df["resume"].apply(cleaner.extract_experience)
120
+
121
+ df["Skills"] = df["resume"].apply(cleaner.extract_skills)
122
+
123
+ df["URL"] = df["resume"].apply(cleaner.extract_url)
124
+
125
+ df["Hashtags"] = df["resume"].apply(cleaner.extract_hashtag)
126
+
127
+ # Remove HTML
128
+
129
+ df["Clean_Text"] = df["resume"].apply(cleaner.remove_html)
130
+
131
+ # Remove JSON
132
+
133
+ df["Clean_Text"] = df["Clean_Text"].apply(cleaner.remove_json)
134
+
135
+ # --------------------------------------------------
136
+ # Display Results
137
+ # --------------------------------------------------
138
+
139
+ print("\n\nExtracted Information\n")
140
+
141
+ print(df[["Name",
142
+ "Email",
143
+ "Phone",
144
+ "Experience",
145
+ "Skills",
146
+ "URL",
147
+ "Hashtags"]])
148
+
149
+ # --------------------------------------------------
150
+ # Save CSV
151
+ # --------------------------------------------------
152
+
153
+ df.to_csv(assignment_dir / 'extracted_resume_data.csv', index=False)
154
+
155
+ print("\nData Saved Successfully!")
@@ -0,0 +1,97 @@
1
+ '''
2
+ Assignment 3: Bag-of-Words & TF-IDF Vectorization
3
+ '''
4
+ """
5
+ Assignment 3: Bag-of-Words & TF-IDF Vectorization
6
+ - Bag-of-Words (BoW) & TF-IDF vector representations built from scratch using NumPy
7
+ - Verification with scikit-learn CountVectorizer & TfidfVectorizer
8
+ - Document-similarity & Plagiarism Detection system based on Cosine Similarity
9
+ """
10
+
11
+ import os
12
+ import json
13
+ import numpy as np
14
+ from typing import List, Tuple
15
+ from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
16
+ from sklearn.metrics.pairwise import cosine_similarity
17
+
18
+ def bow_from_scratch(corpus: List[str]) -> Tuple[List[str], np.ndarray]:
19
+ """Generates vocabulary and Bag-of-Words matrix from scratch."""
20
+ vocab = sorted(list(set(w.lower() for doc in corpus for w in doc.split())))
21
+ word_to_idx = {w: i for i, w in enumerate(vocab)}
22
+
23
+ matrix = np.zeros((len(corpus), len(vocab)), dtype=int)
24
+ for row_idx, doc in enumerate(corpus):
25
+ for word in doc.split():
26
+ w_clean = word.lower()
27
+ if w_clean in word_to_idx:
28
+ matrix[row_idx, word_to_idx[w_clean]] += 1
29
+ return vocab, matrix
30
+
31
+ def tfidf_from_scratch(corpus: List[str]) -> Tuple[List[str], np.ndarray]:
32
+ """Generates normalized TF-IDF feature matrix from scratch."""
33
+ vocab, bow = bow_from_scratch(corpus)
34
+ N = len(corpus)
35
+
36
+ # Term Frequency (TF)
37
+ doc_lengths = bow.sum(axis=1, keepdims=True)
38
+ tf = bow / np.maximum(doc_lengths, 1)
39
+
40
+ # Inverse Document Frequency (IDF)
41
+ df = (bow > 0).sum(axis=0)
42
+ idf = np.log((N + 1) / (df + 1)) + 1
43
+
44
+ tfidf = tf * idf
45
+
46
+ # L2 Normalization
47
+ norms = np.linalg.norm(tfidf, axis=1, keepdims=True)
48
+ tfidf_normalized = np.where(norms > 0, tfidf / norms, tfidf)
49
+ return vocab, tfidf_normalized
50
+
51
+ def run_plagiarism_check(corpus: List[str], doc_names: List[str], threshold: float = 0.70):
52
+ """Calculates cosine similarity across document pairs to flag potential plagiarism."""
53
+ vectorizer = TfidfVectorizer()
54
+ tfidf_matrix = vectorizer.fit_transform(corpus).toarray()
55
+ sim_matrix = cosine_similarity(tfidf_matrix)
56
+
57
+ print(f"{'Document A':<20} | {'Document B':<20} | {'Cosine Sim':<12} | {'Status':<15}")
58
+ print("-" * 75)
59
+
60
+ for i in range(len(doc_names)):
61
+ for j in range(i + 1, len(doc_names)):
62
+ score = sim_matrix[i, j]
63
+ status = "FLAGGED PLAGIARISM" if score >= threshold else "CLEAN"
64
+ print(f"{doc_names[i]:<20} | {doc_names[j]:<20} | {score:.4f} | {status:<15}")
65
+
66
+ def main():
67
+ print("=" * 60)
68
+ print("ASSIGNMENT 3: BAG-OF-WORDS & TF-IDF VECTORIZATION")
69
+ print("=" * 60)
70
+
71
+ data_path = os.path.join(os.path.dirname(__file__),"academic_submissions.json")
72
+ if not os.path.exists(data_path):
73
+ print(f"Data file not found at {data_path}")
74
+ return
75
+
76
+ with open(data_path, "r", encoding="utf-8") as f:
77
+ data = json.load(f)
78
+
79
+ corpus = [item["content"] for item in data]
80
+ doc_ids = [item["id"] for item in data]
81
+
82
+ # 1. From-Scratch Verification
83
+ vocab_scratch, tfidf_scratch = tfidf_from_scratch(corpus)
84
+ print(f"\nVocabulary Size (From Scratch): {len(vocab_scratch)} words")
85
+ print(f"TF-IDF Matrix Shape: {tfidf_scratch.shape}")
86
+
87
+ # 2. Scikit-learn Comparison
88
+ sklearn_vec = TfidfVectorizer()
89
+ tfidf_sklearn = sklearn_vec.fit_transform(corpus).toarray()
90
+ print(f"Scikit-Learn TF-IDF Matrix Shape: {tfidf_sklearn.shape}")
91
+
92
+ # 3. Academic Plagiarism Detection Module
93
+ print("\n--- Academic Integrity Plagiarism Audit Report ---")
94
+ run_plagiarism_check(corpus, doc_ids, threshold=0.70)
95
+
96
+ if __name__ == "__main__":
97
+ main()