nbloom 0.0.1__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ Metadata-Version: 2.4
2
+ Name: nbloom
3
+ Version: 0.0.1
@@ -0,0 +1,5 @@
1
+ nbloom.py,sha256=h6oa_nFChatLe1qLHjO0q1eLjwfAc0AvwndrumT4qQ4,17087
2
+ nbloom-0.0.1.dist-info/METADATA,sha256=obOhFSGc0VaelNht1oLzSMrCW8GLHOVpSPHLcnjh42w,50
3
+ nbloom-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ nbloom-0.0.1.dist-info/top_level.txt,sha256=o27CuAbWI1_LUs0Ac3r1KtneewDaxWFgm9D_xdJ2Z1Y,7
5
+ nbloom-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ nbloom
nbloom.py ADDED
@@ -0,0 +1,599 @@
1
+ """Create Jupyter notebooks for the NLP Laboratory programs.
2
+
3
+ Usage:
4
+ import nlp_lab
5
+ nlp_lab.x(1) # writes program_1.ipynb (comments removed)
6
+ nlp_lab.x(9, "q9.ipynb")
7
+ """
8
+
9
+ import io
10
+ import json
11
+ import os
12
+ import tokenize
13
+
14
+
15
+ PROGRAMS = {}
16
+
17
+ PROGRAMS[1] = r'''# Import required libraries
18
+ import nltk
19
+ from nltk.tokenize import word_tokenize
20
+ from nltk.corpus import stopwords
21
+ from nltk import pos_tag
22
+
23
+ # Download required NLTK resources
24
+ nltk.download('punkt')
25
+ nltk.download('punkt_tab')
26
+ nltk.download('stopwords')
27
+ nltk.download('averaged_perceptron_tagger_eng')
28
+
29
+ # Sample customer reviews
30
+ reviews = [
31
+ "The product is amazing and works really well!",
32
+ "I am not happy with the service. It was too slow.",
33
+ "Excellent quality and fast delivery. Highly recommended!",
34
+ "The packaging was terrible and the product was damaged."
35
+ ]
36
+
37
+ # Load English stop words
38
+ stop_words = set(stopwords.words('english'))
39
+
40
+ # Process each customer review
41
+ for i, review in enumerate(reviews, 1):
42
+
43
+ print(f"\n=== Review {i} ===")
44
+ print("Original Review:", review)
45
+
46
+ # Step 1: Tokenization
47
+ # Split the review into individual words and punctuation
48
+ tokens = word_tokenize(review)
49
+ print("Tokens:", tokens)
50
+
51
+ # Step 2: Stop-word removal
52
+ # Remove common words and punctuation
53
+ filtered_words = [
54
+ word.lower()
55
+ for word in tokens
56
+ if word.isalpha() and word.lower() not in stop_words
57
+ ]
58
+ print("After Stop-word Removal:", filtered_words)
59
+
60
+ # Step 3: POS Tagging for word identification
61
+ # Identify the grammatical category of each word
62
+ identified_words = pos_tag(filtered_words)
63
+ print("Word Identification:", identified_words)
64
+ '''
65
+
66
+ PROGRAMS[2] = r'''# Import NLTK library
67
+ import nltk
68
+ # Import Porter Stemmer and WordNet Lemmatizer
69
+ from nltk.stem import PorterStemmer, WordNetLemmatizer
70
+ # Download WordNet database required for lemmatization
71
+ nltk.download('wordnet')
72
+
73
+ # Create Stemmer and Lemmatizer objects
74
+ stemmer = PorterStemmer()
75
+ lemmatizer = WordNetLemmatizer()
76
+
77
+ # Read a word from the user and convert it to lowercase
78
+ word = input("Enter a word: ").lower()
79
+ # Find the stem of the word using Porter Stemmer
80
+ stem = stemmer.stem(word)
81
+
82
+ # Find the dictionary/root form using WordNet Lemmatizer
83
+ # pos='v' specifies that the word is treated as a verb
84
+ lemma = lemmatizer.lemmatize(word, pos='v')
85
+
86
+ # Display morphological analysis results
87
+ print("\nMorphological Analysis")
88
+ print("Word :", word)
89
+ print("Stem :", stem)
90
+ print("Lemma :", lemma)
91
+
92
+ # Read the root word
93
+ root = input("\nEnter root word: ").lower()
94
+
95
+ # Read the required morphological form
96
+ form = input("Enter form (past/ing): ").lower()
97
+
98
+ # Generate past tense form
99
+ if form == "past":
100
+
101
+ # If root ends with 'e', add only 'd'
102
+ # Example: like -> liked
103
+ if root.endswith("e"):
104
+ generated = root + "d"
105
+ else:
106
+ generated = root + "ed"
107
+
108
+ elif form == "ing":
109
+ if root.endswith("e"):
110
+ generated = root[:-1] + "ing"
111
+
112
+ else:
113
+ generated = root + "ing"
114
+
115
+ # Handle incorrect form entered by the user
116
+ else:
117
+ generated = "Invalid form"
118
+
119
+ # Display the generated word
120
+ print("Generated word:", generated)
121
+ '''
122
+
123
+ PROGRAMS[3] = r'''import nltk
124
+ from nltk.corpus import stopwords
125
+ from nltk.tokenize import word_tokenize
126
+ import matplotlib.pyplot as plt
127
+ from collections import Counter
128
+
129
+ # Download resources (first run only)
130
+ nltk.download('punkt_tab')
131
+ nltk.download('stopwords')
132
+
133
+ # Input Text
134
+ text = """
135
+ Natural Language Processing is a part of Artificial Intelligence.
136
+ It deals with the interaction between computers and humans
137
+ using natural language.
138
+ """
139
+
140
+ # Step 1: Tokenize text
141
+
142
+ tokens = word_tokenize(text.lower())
143
+
144
+ # Step 2: Remove stopwords
145
+ stop_words = set(stopwords.words('english'))
146
+ filtered_tokens = [w for w in tokens if w.isalpha() and w not in stop_words]
147
+ # Step 3: Count word frequencies
148
+
149
+ word_freq = Counter(filtered_tokens)
150
+ # Get the most common words (top 5)
151
+ most_common_words = word_freq.most_common(5)
152
+ #unpacks those two tuples from the zip result into two variables:
153
+ words, freqs = zip(*most_common_words)
154
+ print(words)
155
+ print(freqs)
156
+
157
+ # Step 4: Plot bar graph
158
+ plt.bar(words, freqs, color="skyblue")
159
+ plt.title("Most Frequent Words in Text")
160
+ plt.xlabel("Words")
161
+ plt.ylabel("Frequency")
162
+ plt.show()
163
+ '''
164
+
165
+ PROGRAMS[4] = r'''# Function to calculate minimum edit distance
166
+ def edit_distance(s, t):
167
+ m, n = len(s), len(t)
168
+
169
+ # Create matrix and initialize first row and column
170
+ d = [[i + j if i == 0 or j == 0 else 0
171
+ for j in range(n + 1)] for i in range(m + 1)]
172
+
173
+ # Fill the edit distance matrix
174
+ for i in range(1, m + 1):
175
+ for j in range(1, n + 1):
176
+
177
+ # Cost is 0 for same characters, otherwise 1
178
+ cost = 0 if s[i-1] == t[j-1] else 1
179
+
180
+ # Find minimum of deletion, insertion and substitution
181
+ d[i][j] = min(
182
+ d[i-1][j] + 1, # Deletion
183
+ d[i][j-1] + 1, # Insertion
184
+ d[i-1][j-1] + cost # Match/Substitution
185
+ )
186
+
187
+ # Display the edit distance matrix
188
+ print("\nEdit Distance Matrix:")
189
+ print(" ", *t)
190
+
191
+ for i, row in enumerate(d):
192
+ print(" " if i == 0 else s[i-1], *row)
193
+
194
+ # Start backtracking from bottom-right cell
195
+ i, j = m, n
196
+ print("\nOperations Required:")
197
+
198
+ while i > 0 or j > 0:
199
+ # Characters are same - no operation required
200
+ if i > 0 and j > 0 and s[i-1] == t[j-1]:
201
+ i, j = i-1, j-1
202
+
203
+ # Diagonal movement indicates substitution
204
+ elif i > 0 and j > 0 and d[i][j] == d[i-1][j-1] + 1:
205
+ print("Substitute", s[i-1], "with", t[j-1])
206
+ i, j = i-1, j-1
207
+
208
+ # Left movement indicates insertion
209
+ elif j > 0 and d[i][j] == d[i][j-1] + 1:
210
+ print("Insert", t[j-1])
211
+ j -= 1
212
+
213
+ # Upward movement indicates deletion
214
+ else:
215
+ print("Delete", s[i-1])
216
+ i -= 1
217
+
218
+ # Display final edit distance
219
+ print("\nMinimum Edit Distance =", d[m][n])
220
+
221
+ # Read input words
222
+ s = input("Enter wrong word: ")
223
+ t = input("Enter correct word: ")
224
+
225
+ # Call the function
226
+ edit_distance(s, t)
227
+ '''
228
+
229
+ PROGRAMS[5] = r'''# Install svgling for drawing parse trees in Colab
230
+ !pip install svgling
231
+
232
+ # Program to perform POS tagging and draw a parse tree using NLTK
233
+
234
+ import nltk
235
+ from nltk import word_tokenize, pos_tag
236
+ from nltk import RegexpParser
237
+ import svgling
238
+
239
+ # Download required NLTK data files (only the first time)
240
+ nltk.download('punkt')
241
+ nltk.download('punkt_tab')
242
+ nltk.download('averaged_perceptron_tagger')
243
+ nltk.download('averaged_perceptron_tagger_eng') # Download the specific English tagger
244
+
245
+ # Step 1: Input sentence#
246
+ sentence = "The quick brown fox jumps over the lazy dog"
247
+
248
+ # Step 2: Tokenize the sentence
249
+ tokens = word_tokenize(sentence)
250
+
251
+ # Step 3: Perform POS tagging
252
+ pos_tags = pos_tag(tokens)
253
+ print("Part-of-Speech Tags:")
254
+ print(pos_tags)
255
+
256
+ # Step 4: Define a simple grammar for noun phrases
257
+ grammar = "NP: {<DT>?<JJ>*<NN>}"
258
+
259
+ # Step 5: Create a parser and parse the POS-tagged sentence
260
+ parser = RegexpParser(grammar)
261
+ tree = parser.parse(pos_tags)
262
+
263
+ # Step 6: Display the parsed tree
264
+ print("\nParsed Tree:")
265
+ print(tree)
266
+ #tree.draw()
267
+ display(svgling.draw_tree(tree))
268
+ '''
269
+
270
+ PROGRAMS[6] = r'''# Bilingual lexicon
271
+ dictionary = {
272
+ "i": "ನಾನು", "he": "ಅವನು",
273
+ "she": "ಅವಳು", "we": "ನಾವು",
274
+ "they": "ಅವರು",
275
+ "rice": "ಅನ್ನ", "water": "ನೀರು",
276
+ "milk": "ಹಾಲು", "book": "ಪುಸ್ತಕ",
277
+ "apple": "ಸೇಬು", "food": "ಆಹಾರ",
278
+ "red": "ಕೆಂಪು", "good": "ಒಳ್ಳೆಯ",
279
+ "small": "ಚಿಕ್ಕ", "fresh": "ತಾಜಾ"
280
+ }
281
+
282
+ # Verb forms based on subject
283
+ verbs = {
284
+ "eat": ["ತಿನ್ನುತ್ತೇನೆ", "ತಿನ್ನುತ್ತಾನೆ", "ತಿನ್ನುತ್ತಾಳೆ",
285
+ "ತಿನ್ನುತ್ತೇವೆ", "ತಿನ್ನುತ್ತಾರೆ"],
286
+ "drink": ["ಕುಡಿಯುತ್ತೇನೆ", "ಕುಡಿಯುತ್ತಾನೆ", "ಕುಡಿಯುತ್ತಾಳೆ",
287
+ "ಕುಡಿಯುತ್ತೇವೆ", "ಕುಡಿಯುತ್ತಾರೆ"],
288
+ "read": ["ಓದುತ್ತೇನೆ", "ಓದುತ್ತಾನೆ", "ಓದುತ್ತಾಳೆ",
289
+ "ಓದುತ್ತೇವೆ", "ಓದುತ್ತಾರೆ"]
290
+ }
291
+
292
+ subjects = ["i", "he", "she", "we", "they"]
293
+ verb_forms = {"eats": "eat", "drinks": "drink",
294
+ "reads": "read"}
295
+
296
+ # Translation function
297
+ def translate(sentence):
298
+ words = sentence.lower().strip(".,!?").split()
299
+
300
+ # Remove articles
301
+ words = [w for w in words if w not in ["a", "an", "the"]]
302
+
303
+ if len(words) < 3 or words[0] not in subjects:
304
+ return "Unsupported sentence"
305
+
306
+ subject = words[0]
307
+ verb = verb_forms.get(words[1], words[1])
308
+
309
+ if verb not in verbs:
310
+ return "Unknown verb"
311
+
312
+ # Translate object phrase
313
+ obj = " ".join(dictionary.get(w, w) for w in words[2:])
314
+
315
+ # Select verb based on subject
316
+ index = subjects.index(subject)
317
+ kannada_verb = verbs[verb][index]
318
+
319
+ # SVO -> SOV
320
+ return f"{dictionary[subject]} {obj} {kannada_verb}"
321
+
322
+ # Input and output
323
+ sentence = input("Enter English sentence: ")
324
+ print("Kannada Translation:", translate(sentence))
325
+ '''
326
+
327
+ PROGRAMS[7] = r'''from collections import Counter
328
+
329
+ # Word frequency dataset
330
+ counts = {
331
+ "apple": 5, "banana": 4, "orange": 3,
332
+ "grape": 2, "mango": 2, "pear": 1,
333
+ "kiwi": 1, "guava": 1, "peach": 1,
334
+ "plum": 1, "cherry": 0, "papaya": 0
335
+ }
336
+
337
+ N = sum(counts.values())
338
+ V = len(counts)
339
+ k = 0.5
340
+ Nc = Counter(counts.values())
341
+
342
+ # Good-Turing adjusted counts
343
+ gt = {}
344
+ for word, c in counts.items():
345
+ gt[word] = ((c + 1) * Nc[c + 1] / Nc[c]
346
+ if Nc[c + 1] > 0 else c)
347
+
348
+ total_gt = sum(gt.values())
349
+
350
+ print("Total Words:", N, "Vocabulary:", V)
351
+ print("Count of Counts:", dict(sorted(Nc.items())))
352
+ print(f"\n{'Word':10} {'MLE':8} {'Laplace':9} {'Add-k':8} {'Good-Turing'}")
353
+
354
+ for word, c in counts.items():
355
+ mle = c / N
356
+ lap = (c + 1) / (N + V)
357
+ add = (c + k) / (N + k * V)
358
+ good = gt[word] / total_gt
359
+
360
+ print(f"{word:10} {mle:<8.3f} {lap:<9.3f} "
361
+ f"{add:<8.3f} {good:.3f}")
362
+ '''
363
+
364
+ PROGRAMS[8] = r'''#import the libraries
365
+ from collections import Counter
366
+ from nltk import word_tokenize
367
+ from nltk.util import ngrams
368
+ from nltk.corpus import stopwords
369
+ import nltk
370
+
371
+ # download required NLTK resources
372
+ nltk.download('punkt')
373
+ nltk.download('stopwords')
374
+
375
+ # stop words list
376
+ stop_words = set(stopwords.words('english'))
377
+
378
+ # create the collection of 3 documents
379
+ doc_1 = 'Convolutional Neural Networks are very similar to ordinary Neural Networks from the previous chapter.'
380
+ doc_2 = 'Convolutional Neural Networks take advantage of the fact that the input consists of images and they constrain the architecture in a more sensible way.'
381
+ doc_3 = 'In particular, unlike a regular Neural Network, the layers of a ConvNet have neurons arranged in 3 dimensions: width, height, depth.'
382
+
383
+ # combine all documents
384
+ documents = doc_1 + " " + doc_2 + " " + doc_3
385
+
386
+ # tokenize the text
387
+ tokens = word_tokenize(documents.lower())
388
+
389
+ # remove stop words
390
+ filtered_tokens = [word for word in tokens if word.isalpha() and word not in stop_words]
391
+
392
+ # generate bi-grams
393
+ bigrams = list(ngrams(filtered_tokens, 2))
394
+
395
+ # count frequency of bi-grams
396
+ bigram_freq = Counter(bigrams)
397
+
398
+ # print the number of unique bi-grams
399
+ print("Number of unique bi-grams:", len(bigram_freq))
400
+
401
+ # print the top 5 most common bi-grams
402
+ print("\nTop 5 most common bi-grams:")
403
+ for bigram, freq in bigram_freq.most_common(5):
404
+ print(bigram, "->", freq)
405
+ '''
406
+
407
+ PROGRAMS[9] = r'''from collections import Counter
408
+
409
+ # Sample corpus
410
+ corpus = [
411
+ "The sun rises in the east",
412
+ "The sun shines in the morning",
413
+ "The sun shines brightly",
414
+ "The moon shines at night",
415
+ "The stars shine at night",
416
+ "The birds fly in the sky",
417
+ "The birds sing in the morning",
418
+ "The birds build their nests",
419
+ "The children play in the park",
420
+ "The children play in the garden",
421
+ "The children read books",
422
+ "The students read books",
423
+ "The students play in the park",
424
+ "The students study in the library",
425
+ "The teacher teaches in the classroom",
426
+ "The teacher reads a book",
427
+ "The dog runs in the park",
428
+ "The dog plays in the garden",
429
+ "The cat sleeps on the sofa",
430
+ "The cat plays in the garden"
431
+ ]
432
+
433
+ # Generate bigrams
434
+ bigrams = []
435
+ for sentence in corpus:
436
+ words = sentence.lower().split()
437
+ for i in range(len(words) - 1):
438
+ bigrams.append((words[i], words[i + 1]))
439
+
440
+ # Count bigram frequencies
441
+ counts = Counter(bigrams)
442
+
443
+ # Enter a new sentence
444
+ sentence = input("Enter a sentence: ").lower().split()
445
+
446
+ if sentence:
447
+ word = sentence[-1]
448
+ next_words = {}
449
+
450
+ for (w1, w2), count in counts.items():
451
+ if w1 == word:
452
+ next_words[w2] = count
453
+
454
+ if next_words:
455
+ predictions = Counter(next_words).most_common(5)
456
+ print("Predicted next word:", predictions[0][0])
457
+ print("Completed sentence:", " ".join(sentence + [predictions[0][0]]))
458
+ print("Top predictions:", predictions)
459
+ else:
460
+ print("No prediction available")
461
+ else:
462
+ print("Please enter a sentence")
463
+ '''
464
+
465
+ PROGRAMS[10] = r'''from nltk import CFG
466
+ from nltk.parse import RecursiveDescentParser, ShiftReduceParser
467
+
468
+ # Define Context-Free Grammar
469
+ grammar = CFG.fromstring("""
470
+ S -> NP VP
471
+ NP -> Det N
472
+ VP -> V NP
473
+ Det -> 'the' | 'a' | 'an'
474
+ N -> 'boy' | 'girl' | 'apple'
475
+ V -> 'eats' | 'likes'
476
+ """)
477
+
478
+ # Accept input sentence
479
+ sentence = input("Enter sentence: ").lower().split()
480
+
481
+ # Top-Down Parsing
482
+ print("\nTOP-DOWN PARSING")
483
+ top = RecursiveDescentParser(grammar)
484
+
485
+ # Bottom-Up Parsing
486
+ print("\nBOTTOM-UP PARSING")
487
+ bottom = ShiftReduceParser(grammar)
488
+ # Generate parse trees
489
+ for name, parser in [("Top-Down", top), ("Bottom-Up", bottom)]:
490
+ try:
491
+ trees = list(parser.parse(sentence))
492
+ if trees:
493
+ print("\n", name, "Parse Tree:")
494
+ trees[0].pretty_print()
495
+ else:
496
+ print(name, ": Sentence not accepted")
497
+ except ValueError:
498
+ print(name, ": Word not found in grammar")
499
+ '''
500
+
501
+
502
+ def strip_comments(source):
503
+ """Remove Python comments from source without touching string literals."""
504
+ lines = source.splitlines(keepends=True)
505
+ protected = set()
506
+ try:
507
+ tokens = list(tokenize.generate_tokens(io.StringIO(source).readline))
508
+ except (tokenize.TokenError, IndentationError):
509
+ tokens = []
510
+
511
+ for tok in tokens:
512
+ if tok.type == tokenize.STRING and tok.start[0] != tok.end[0]:
513
+ protected.update(range(tok.start[0], tok.end[0] + 1))
514
+ if tok.type == tokenize.COMMENT:
515
+ row, col = tok.start
516
+ original = lines[row - 1]
517
+ ending = "\n" if original.endswith("\n") else ""
518
+ kept = original[:col].rstrip()
519
+ lines[row - 1] = kept + ending if kept else ending
520
+
521
+ cleaned = []
522
+ for row, line in enumerate(lines, 1):
523
+ if line.strip() == "" and row not in protected:
524
+ if not cleaned or cleaned[-1].strip() == "":
525
+ continue
526
+ line = "\n" if line.endswith("\n") else ""
527
+ cleaned.append(line)
528
+ return "".join(cleaned)
529
+
530
+
531
+ def get_code(i):
532
+ """Return the comment-free source for program number i (1-10)."""
533
+ try:
534
+ number = int(i)
535
+ except (TypeError, ValueError):
536
+ raise ValueError("Program number must be an integer from 1 to 10")
537
+ if number not in PROGRAMS:
538
+ raise ValueError("Program number must be an integer from 1 to 10")
539
+ return strip_comments(PROGRAMS[number]).strip() + "\n"
540
+
541
+
542
+ def x(i, filename=None):
543
+ """Write program i to an .ipynb notebook and return its path.
544
+
545
+ Example:
546
+ import nlp_lab
547
+ nlp_lab.x(1) # program_1.ipynb
548
+ nlp_lab.x(3, "frequency.ipynb")
549
+ """
550
+ code = get_code(i)
551
+ if filename is None:
552
+ filename = f"program_{int(i)}.ipynb"
553
+ if not str(filename).endswith(".ipynb"):
554
+ filename = f"{filename}.ipynb"
555
+
556
+ parent = os.path.dirname(os.path.abspath(filename))
557
+ os.makedirs(parent, exist_ok=True)
558
+
559
+ notebook = {
560
+ "cells": [
561
+ {
562
+ "cell_type": "code",
563
+ "execution_count": None,
564
+ "metadata": {},
565
+ "outputs": [],
566
+ "source": code.splitlines(keepends=True),
567
+ }
568
+ ],
569
+ "metadata": {
570
+ "kernelspec": {
571
+ "display_name": "Python 3",
572
+ "language": "python",
573
+ "name": "python3",
574
+ },
575
+ "language_info": {
576
+ "name": "python",
577
+ "version": "3",
578
+ },
579
+ },
580
+ "nbformat": 4,
581
+ "nbformat_minor": 5,
582
+ }
583
+
584
+ with open(filename, "w", encoding="utf-8") as fh:
585
+ json.dump(notebook, fh, indent=1, ensure_ascii=False)
586
+ fh.write("\n")
587
+
588
+ print(f"Created {filename}")
589
+ return filename
590
+
591
+
592
+ __all__ = ["x", "get_code", "strip_comments", "PROGRAMS"]
593
+
594
+
595
+ if __name__ == "__main__":
596
+ import sys
597
+
598
+ for arg in sys.argv[1:] or ["1"]:
599
+ x(arg)