This repository has been archived by the owner on Dec 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_cli.py
107 lines (84 loc) · 3.02 KB
/
simple_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import json
import logging
from utils import MongoDBDAO
import pika
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)-8s - %(name)s:%(lineno)d |> %(message)s",
datefmt="%d.%m.%Y %H:%M:%S"
)
STORAGE = []
mongo_dao = MongoDBDAO("localhost", 27017, "text_matcher", "admin", "securePasswd!")
conn = pika.BlockingConnection(parameters=pika.ConnectionParameters("localhost", 49153))
ch = conn.channel()
temp_queue = ch.queue_declare(queue='', exclusive=True)
temp_queue_name = temp_queue.method.queue
def on_reply(ch, method, properties, body):
logging.info(f"Got an message in {method.routing_key} queue!")
logging.info(body)
global STORAGE
STORAGE.append((method, properties, body))
ch.basic_ack(delivery_tag=method.delivery_tag)
ch.basic_consume(temp_queue_name, on_message_callback=on_reply)
def send_text():
with open("text.txt") as f:
texts = f.readlines()
logging.info("Available texts:")
for i, t in enumerate(texts):
logging.info(f"{i}: {t}")
comm = input("Insert a valid number, or own text to send it.")
try:
tts = texts[int(comm)]
except (ValueError, IndexError) as e:
tts = comm
ch.basic_publish(
exchange="",
routing_key="front_to_back_text",
body=json.dumps({"text": tts, "title": f"{tts[:10]}..."}),
properties=pika.BasicProperties(
content_type="application/json",
reply_to=temp_queue_name
)
)
logging.info(f"Text '{tts[:10]} ... {tts[-10:]}' sent!")
def get():
what = input("what you want to get (Sentence or Text): ")
_id = input("_id (leave empty for all):")
if not _id:
logging.info(mongo_dao.get_records(what, None, None))
else:
logging.info(mongo_dao.get_records(what, {"_id": _id}, None))
def get_similarity():
_id = input("_id:")
ch.basic_publish(
exchange="",
routing_key="front_to_back_sentences",
body=json.dumps({"sentenceUUID": _id}),
properties=pika.BasicProperties(
content_type="application/json",
reply_to=temp_queue_name
)
)
def exit_():
logging.info("Closing the connection.")
ch.close()
conn.close()
while not conn.is_closed or not ch.is_closed():
conn.process_data_events(0.5)
def check_new_messages():
conn.process_data_events(0.5)
menu = {
"1": {"description": "Fetching data from MongoDB.", "func": get},
"2": {"description": "Search for similar sentence.", "func": get_similarity},
"3": {"description": "Process and add new text to MongoDB.", "func": send_text},
"4": {"description": "Check if new messages appeared.", "func": check_new_messages},
"5": {"description": "Exit from CLI.", "func": exit}
}
while True:
try:
print("\n---- Menu ----")
[print(f"{k} => {v['description']}") for k, v in menu.items()]
menu[input("Enter function number:")]['func']()
except Exception as e:
logging.error(f"exception happened: {e}", exc_info=e)
continue