tannic 0.1.0__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.
tannic/__init__.py ADDED
File without changes
tannic/p10_a.py ADDED
@@ -0,0 +1,35 @@
1
+ from confluent_kafka import Consumer, Producer
2
+ import json
3
+
4
+ THRESHOLD = 40.0
5
+ consumer = Consumer({
6
+ 'bootstrap.servers': 'localhost:9092',
7
+ 'group.id': 'temp-alert-app',
8
+ 'auto.offset.reset': 'earliest'
9
+ })
10
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
11
+ consumer.subscribe(['sensor-stream'])
12
+ print("High-temperature detector running... (Ctrl+C to stop)")
13
+
14
+ try:
15
+ while True:
16
+ msg = consumer.poll(1.0)
17
+ if msg is None or msg.error():
18
+ continue
19
+ reading = json.loads(msg.value().decode('utf-8'))
20
+
21
+ # Filter: only readings above the threshold become alerts
22
+ if reading['temperature'] > THRESHOLD:
23
+ alert = {'sensor_id': reading['sensor_id'],
24
+ 'temperature': reading['temperature'],
25
+ 'message': f"High temperature! Above {THRESHOLD} C"}
26
+ producer.produce('high-temp-alerts', key=reading['sensor_id'],
27
+ value=json.dumps(alert))
28
+ producer.flush()
29
+ print("ALERT published:", alert)
30
+ else:
31
+ print("Normal:", reading)
32
+ except KeyboardInterrupt:
33
+ pass
34
+ finally:
35
+ consumer.close()
tannic/p10_b.py ADDED
@@ -0,0 +1,14 @@
1
+ from confluent_kafka import Producer
2
+ import json, random, time
3
+
4
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
5
+
6
+ for i in range(15):
7
+ reading = {'sensor_id': f"sensor-{random.randint(1, 3)}",
8
+ 'temperature': round(random.uniform(25, 50), 1)}
9
+ producer.produce('sensor-stream', key=reading['sensor_id'],
10
+ value=json.dumps(reading))
11
+ print("Sent:", reading)
12
+ time.sleep(1)
13
+
14
+ producer.flush()
tannic/p1_a.py ADDED
@@ -0,0 +1,12 @@
1
+ from confluent_kafka import Producer
2
+
3
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
4
+
5
+ for i in range(1, 6):
6
+ message = f"Hello World {i}"
7
+ # No key is given -> keyless message (Kafka spreads them across partitions)
8
+ producer.produce('demo.topic', value=message)
9
+ print("Sent:", message)
10
+
11
+ producer.flush() # wait until all messages are delivered
12
+ print("All messages sent to demo.topic")
tannic/p1_b.py ADDED
@@ -0,0 +1,23 @@
1
+ from confluent_kafka import Consumer
2
+
3
+ consumer = Consumer({
4
+ 'bootstrap.servers': 'localhost:9092',
5
+ 'group.id': 'demo-group',
6
+ 'auto.offset.reset': 'earliest' # read from the beginning
7
+ })
8
+ consumer.subscribe(['demo.topic'])
9
+ print("Waiting for messages... (Ctrl+C to stop)")
10
+
11
+ try:
12
+ while True:
13
+ msg = consumer.poll(1.0) # wait up to 1 second
14
+ if msg is None:
15
+ continue
16
+ if msg.error():
17
+ print("Error:", msg.error())
18
+ continue
19
+ print("Received:", msg.value().decode('utf-8'))
20
+ except KeyboardInterrupt:
21
+ pass
22
+ finally:
23
+ consumer.close()
tannic/p2.py ADDED
@@ -0,0 +1,19 @@
1
+ from confluent_kafka import Producer
2
+
3
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
4
+
5
+ def delivery_report(err, msg):
6
+ if err:
7
+ print("Delivery Failed: ", err)
8
+ else:
9
+ print(f"Delivered: '{msg.value().decode()}' -> topic = {msg.topic()} Partition = {msg.partition()} offset = {msg.offset()}")
10
+
11
+ for i in range(1, 10):
12
+ message = f"Async message {i}"
13
+
14
+ producer.produce('demo.topic', value = message, callback = delivery_report)
15
+ print("Queued: ", message)
16
+ producer.poll(0)
17
+
18
+ producer.flush()
19
+ print('done')
tannic/p3.py ADDED
@@ -0,0 +1,24 @@
1
+ from confluent_kafka import Producer
2
+ import json, random, time
3
+
4
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
5
+ THRESHOLD = 40.0
6
+
7
+ for i in range(1, 11):
8
+ reading = {
9
+ 'sensor_id': f"sensor-{random.randint(1, 3)}",
10
+ 'temperature': round(random.uniform(25, 50), 1),
11
+ 'humidity': round(random.uniform(30, 80), 1),
12
+ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
13
+ }
14
+
15
+ data = json.dumps(reading)
16
+ producer.produce('iot-sensor-data', key = reading['sensor_id'], value = data)
17
+ print("Sent: ", data)
18
+
19
+ if reading['temperature'] > THRESHOLD:
20
+ print(f" ALERT! {reading['sensor_id']} temperature "
21
+ f"{reading['temperature']} C exceeds {THRESHOLD} C")
22
+ time.sleep(1)
23
+
24
+ producer.flush()
tannic/p4.py ADDED
@@ -0,0 +1,29 @@
1
+ from confluent_kafka import Consumer
2
+ import json
3
+
4
+ THRESHOLD = 40.0
5
+ consumer = Consumer({
6
+ 'bootstrap.servers': 'localhost:9092',
7
+ 'group.id': 'iot-group',
8
+ 'auto.offset.reset': 'earliest'
9
+ })
10
+ consumer.subscribe(['iot-sensor-data'])
11
+ print("Reading sensor data... (Ctrl+C to stop)")
12
+
13
+ try:
14
+ while True:
15
+ msg = consumer.poll(1.0)
16
+ if msg is None:
17
+ continue
18
+ if msg.error():
19
+ print("Error:", msg.error())
20
+ continue
21
+ reading = json.loads(msg.value().decode('utf-8')) # JSON -> dict
22
+ sid, temp = reading['sensor_id'], reading['temperature']
23
+ print(f"{sid}: temp={temp} C, humidity={reading['humidity']} %")
24
+ if temp > THRESHOLD:
25
+ print(f" ALERT! High temperature {temp} C at {sid}")
26
+ except KeyboardInterrupt:
27
+ pass
28
+ finally:
29
+ consumer.close()
tannic/p5.py ADDED
@@ -0,0 +1,29 @@
1
+ from confluent_kafka import Producer
2
+ import json
3
+
4
+ producer = Producer({
5
+ 'bootstrap.servers': 'localhost:9092',
6
+ 'acks': 'all', # wait for all in-sync replicas to confirm
7
+ 'retries': 5, # retry failed sends up to 5 times
8
+ 'retry.backoff.ms': 500, # wait 500 ms between retries
9
+ 'enable.idempotence': True, # retries will not create duplicates
10
+ 'linger.ms': 100, # wait up to 100 ms to fill a batch
11
+ 'batch.size': 16384 # max batch size in bytes (16 KB)
12
+ })
13
+
14
+ def delivery_report(err, msg):
15
+ if err:
16
+ print("FAILED:", err)
17
+ else:
18
+ print(f"ACK received: {msg.value().decode()} "
19
+ f"(partition {msg.partition()}, offset {msg.offset()})")
20
+
21
+ for i in range(1, 11):
22
+ payment = {'payment_id': f"PAY{1000 + i}", 'amount': 100 * i,
23
+ 'status': 'SUCCESS'}
24
+ producer.produce('payments', key=payment['payment_id'],
25
+ value=json.dumps(payment), callback=delivery_report)
26
+ producer.poll(0)
27
+
28
+ producer.flush() # all 10 messages go out in batches, then ACKs arrive
29
+ print("All payments sent reliably")
tannic/p6_a.py ADDED
@@ -0,0 +1,32 @@
1
+ from confluent_kafka import Producer
2
+ import json
3
+
4
+ producer = Producer({
5
+ 'bootstrap.servers': 'localhost:9092',
6
+ 'transactional.id': 'bank-transfer-1' # required for transactions
7
+ })
8
+ producer.init_transactions()
9
+
10
+ def transfer(txn_id, from_acc, to_acc, amount, fail=False):
11
+ producer.begin_transaction()
12
+ try:
13
+ debit = {'txn_id': txn_id, 'type': 'DEBIT', 'account': from_acc, 'amount': amount}
14
+ credit = {'txn_id': txn_id, 'type': 'CREDIT', 'account': to_acc, 'amount': amount}
15
+
16
+ producer.produce('transactions', key=txn_id, value=json.dumps(debit))
17
+ print(txn_id, "debit event sent")
18
+
19
+ if fail:
20
+ raise Exception("Simulated failure before credit")
21
+
22
+ producer.produce('transactions', key=txn_id, value=json.dumps(credit))
23
+ print(txn_id, "credit event sent")
24
+
25
+ producer.commit_transaction() # both events become visible together
26
+ print(txn_id, "COMMITTED - both events saved\n")
27
+ except Exception as e:
28
+ producer.abort_transaction() # both events are discarded
29
+ print(txn_id, "ABORTED -", e, "- no event saved\n")
30
+
31
+ transfer('TXN1001', 'ACC-A', 'ACC-B', 500) # succeeds
32
+ transfer('TXN1002', 'ACC-A', 'ACC-B', 700, fail=True)
tannic/p6_b.py ADDED
@@ -0,0 +1,21 @@
1
+ from confluent_kafka import Consumer
2
+
3
+ consumer = Consumer({
4
+ 'bootstrap.servers': 'localhost:9092',
5
+ 'group.id': 'txn-check-group',
6
+ 'auto.offset.reset': 'earliest',
7
+ 'isolation.level': 'read_committed' # aborted messages are hidden
8
+ })
9
+ consumer.subscribe(['transactions'])
10
+ print("Committed events (Ctrl+C to stop):")
11
+
12
+ try:
13
+ while True:
14
+ msg = consumer.poll(1.0)
15
+ if msg is None or msg.error():
16
+ continue
17
+ print(msg.value().decode('utf-8'))
18
+ except KeyboardInterrupt:
19
+ pass
20
+ finally:
21
+ consumer.close()
tannic/p7.py ADDED
@@ -0,0 +1,32 @@
1
+ from confluent_kafka import Consumer
2
+
3
+ consumer = Consumer({
4
+ 'bootstrap.servers': 'localhost:9092',
5
+ 'group.id': 'payment-processor',
6
+ 'auto.offset.reset': 'earliest',
7
+ 'enable.auto.commit': False # we commit offsets ourselves
8
+ })
9
+ consumer.subscribe(['payments'])
10
+ print("Processing payments... (Ctrl+C to stop)")
11
+
12
+ try:
13
+ while True:
14
+ msg = consumer.poll(1.0)
15
+ if msg is None:
16
+ continue
17
+ if msg.error():
18
+ print("Error:", msg.error())
19
+ continue
20
+
21
+ # 1. Process the message first
22
+ print(f"Processing offset {msg.offset()}: {msg.value().decode('utf-8')}")
23
+
24
+ # 2. Commit the offset only AFTER processing succeeded.
25
+ # If the program crashes before this line, the message is read
26
+ # again on restart -> at-least-once delivery.
27
+ consumer.commit(message=msg, asynchronous=False)
28
+ print(f" Committed offset {msg.offset()}")
29
+ except KeyboardInterrupt:
30
+ pass
31
+ finally:
32
+ consumer.close()
tannic/p8_a.py ADDED
@@ -0,0 +1,38 @@
1
+ from confluent_kafka import Consumer, Producer
2
+
3
+ consumer = Consumer({
4
+ 'bootstrap.servers': 'localhost:9092',
5
+ 'group.id': 'word-count-app',
6
+ 'auto.offset.reset': 'earliest'
7
+ })
8
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
9
+ consumer.subscribe(['text-input'])
10
+
11
+ word_counts = {} # state store: remembers counts across messages
12
+ print("Word Count app running... (Ctrl+C to stop)")
13
+
14
+ try:
15
+ while True:
16
+ msg = consumer.poll(1.0)
17
+ if msg is None or msg.error():
18
+ continue
19
+ line = msg.value().decode('utf-8')
20
+
21
+ # Stateless transformation: lowercase, split into words, strip punctuation
22
+ words = [w.strip('.,!?;:') for w in line.lower().split()]
23
+
24
+ # Stateful aggregation: update the running count of each word
25
+ for word in words:
26
+ if word == '':
27
+ continue
28
+ word_counts[word] = word_counts.get(word, 0) + 1
29
+ producer.produce('word-count-output', key=word,
30
+ value=str(word_counts[word]))
31
+ producer.flush()
32
+
33
+ print("Input:", line)
34
+ print("Counts:", word_counts)
35
+ except KeyboardInterrupt:
36
+ pass
37
+ finally:
38
+ consumer.close()
tannic/p8_b.py ADDED
@@ -0,0 +1,13 @@
1
+ from confluent_kafka import Producer
2
+
3
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
4
+ print("Type a sentence and press Enter (type 'exit' to quit)")
5
+
6
+ while True:
7
+ line = input("> ")
8
+ if line.strip().lower() == 'exit':
9
+ break
10
+ producer.produce('text-input', value=line)
11
+ producer.flush()
12
+
13
+ print("Producer closed")
tannic/p9_a.py ADDED
@@ -0,0 +1,40 @@
1
+ from confluent_kafka import Consumer, Producer
2
+ import json
3
+
4
+ consumer = Consumer({
5
+ 'bootstrap.servers': 'localhost:9092',
6
+ 'group.id': 'stock-stats-app',
7
+ 'auto.offset.reset': 'earliest'
8
+ })
9
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
10
+ consumer.subscribe(['stock-prices'])
11
+
12
+ stats = {} # state: symbol -> {min, max, total, count}
13
+ print("Stock statistics app running... (Ctrl+C to stop)")
14
+
15
+ try:
16
+ while True:
17
+ msg = consumer.poll(1.0)
18
+ if msg is None or msg.error():
19
+ continue
20
+ tick = json.loads(msg.value().decode('utf-8'))
21
+ symbol, price = tick['symbol'], tick['price']
22
+
23
+ if symbol not in stats:
24
+ stats[symbol] = {'min': price, 'max': price, 'total': 0, 'count': 0}
25
+ s = stats[symbol]
26
+ s['min'] = min(s['min'], price)
27
+ s['max'] = max(s['max'], price)
28
+ s['total'] += price
29
+ s['count'] += 1
30
+ avg = round(s['total'] / s['count'], 2)
31
+
32
+ result = {'symbol': symbol, 'min': s['min'], 'max': s['max'],
33
+ 'avg': avg, 'count': s['count']}
34
+ producer.produce('stock-stats', key=symbol, value=json.dumps(result))
35
+ producer.flush()
36
+ print(f"{symbol}: price={price} min={s['min']} max={s['max']} avg={avg}")
37
+ except KeyboardInterrupt:
38
+ pass
39
+ finally:
40
+ consumer.close()
tannic/p9_b.py ADDED
@@ -0,0 +1,15 @@
1
+ from confluent_kafka import Producer
2
+ import json, random, time
3
+
4
+ producer = Producer({'bootstrap.servers': 'localhost:9092'})
5
+ stocks = {'TCS': 3500, 'INFY': 1500, 'RELIANCE': 2800} # base prices
6
+
7
+ for i in range(20):
8
+ symbol = random.choice(list(stocks))
9
+ price = round(stocks[symbol] + random.uniform(-50, 50), 2)
10
+ tick = {'symbol': symbol, 'price': price}
11
+ producer.produce('stock-prices', key=symbol, value=json.dumps(tick))
12
+ print("Sent:", tick)
13
+ time.sleep(1)
14
+
15
+ producer.flush()
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: tannic
3
+ Version: 0.1.0
4
+ Summary: Kafka producer/consumer example scripts
5
+ Requires-Python: >=3.8
6
+ Requires-Dist: confluent-kafka
@@ -0,0 +1,20 @@
1
+ tannic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ tannic/p10_a.py,sha256=043JaLlGt9AEYJ3lO1mZ3nssVvrWZYKcX5WOwUGFmF4,1174
3
+ tannic/p10_b.py,sha256=sKjiiGeAuQzWQXfo-rZ8BhOc_UYdcrHqCax99ZxiLAg,448
4
+ tannic/p1_a.py,sha256=7jFmX0mp-7ftmCphqvQilrc1W6dIxUuGzpeCyZmM2z0,420
5
+ tannic/p1_b.py,sha256=pXZfevbhHkc-OwFUn4RdeSP0-L-g-N2telBVroI9lnU,622
6
+ tannic/p2.py,sha256=4iQ8bi0nXQcPL9AxuRCfFXmL9TCcCnz-7JdiglF8MwI,572
7
+ tannic/p3.py,sha256=nB1J_pFR4lZ0TWdpFtOQAzRgkRKqWol9dZcsoMuUJxc,781
8
+ tannic/p4.py,sha256=yB1GBR_8spc2rYCP6xAJGmHXfDCHNxzfr6bjfemSpSQ,859
9
+ tannic/p5.py,sha256=yWgYFSENfLDUUpbqw22oXsVvBUKkPMHL7-UjJRHa1L8,1145
10
+ tannic/p6_a.py,sha256=lSMcg6jja_FRDyG5P-0l73kNCU7Pyb8cHgGsA39eGBU,1261
11
+ tannic/p6_b.py,sha256=68003NCS15WFmHb6f9X0F6aeldkyMOS3-m_c-8fSvqk,562
12
+ tannic/p7.py,sha256=QYJiGZCcE1ofB92OjA5bq-1tXzhB-8I_ZdYNS1Hzz-I,1017
13
+ tannic/p8_a.py,sha256=nHIi3WfbXTt99BievVSqUMNEy67Xx__avYYm5duy2oU,1215
14
+ tannic/p8_b.py,sha256=BeqrxJXqP8twJMCulADP4tEIny5ZF5lkEes56zffXCY,355
15
+ tannic/p9_a.py,sha256=QxP3dztOY9559pB3ks5cxOUwXMw9iZWNk0DYnqeHGTM,1346
16
+ tannic/p9_b.py,sha256=nkLqz9n1AgFWwgdxrShYajc6SOhQbF0GHVH4nfbH5ck,501
17
+ tannic-0.1.0.dist-info/METADATA,sha256=s6x7L6lRnC9LlPCdkWwNrZGeVOO6xjWjgU-VOwXlJtQ,159
18
+ tannic-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
+ tannic-0.1.0.dist-info/top_level.txt,sha256=NuEE9tnJOAotNxfFL-XU_H7VidtA5dZ7Fjh0papZj9Q,7
20
+ tannic-0.1.0.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
+ tannic