Rsnarsna commited on
Commit
4cdc302
·
verified ·
1 Parent(s): 4653184

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +375 -1
app.py CHANGED
@@ -1,7 +1,381 @@
1
  import streamlit as st # type: ignore
2
  import sys
3
  from io import StringIO
4
- from main import start, stop
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  # Function to capture print statements into the log box
7
  class StreamToText:
 
1
  import streamlit as st # type: ignore
2
  import sys
3
  from io import StringIO
4
+ import email, imaplib, json
5
+ import torch, time # type: ignore
6
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM # type: ignore
7
+ import mysql.connector # type: ignore
8
+ # from main import start, stop
9
+
10
+ # constants.py
11
+
12
+ IMAP_SERVER = 'imap.gmail.com'
13
+ EMAIL_ADDRESS = 'narayanansubramani14@gmail.com'
14
+ PASSWORD = 'gclc wsnx kywt uvqy '
15
+
16
+ OPENAI_API_KEY = ''#'sk-proj-AnXUB4dJmJliZETCm67WT3BlbkFJ7dp4DAXRFQ6pXAyK7gWE'
17
+ # IMAP_SERVER = 'imap.gmail.com'
18
+ # EMAIL_ADDRESS = 'redmind.uiautomation@gmail.com'
19
+ # PASSWORD = 'jymzapycraiheubg'
20
+
21
+ # h99d6-103-25-46-162.ngrok-free.app
22
+ DB_CONFIG = {
23
+ 'host': '99d6-103-25-46-162.ngrok-free.app',
24
+ 'user': 'root',
25
+ 'password': '',
26
+ 'database': 'shipment_details'
27
+ }
28
+
29
+ def read_email():
30
+ try:
31
+ mail = imaplib.IMAP4_SSL(IMAP_SERVER)
32
+ mail.login(EMAIL_ADDRESS, PASSWORD)
33
+ mail.select('inbox')
34
+
35
+ # Search for unread emails
36
+ status, messages = mail.search(None, 'UNSEEN')
37
+ message_ids = messages[0].split()
38
+
39
+ # Process each unread email
40
+ for message_id in message_ids:
41
+ try:
42
+ # Fetch the email
43
+ status, data = mail.fetch(message_id, '(RFC822)')
44
+ raw_email = data[0][1]
45
+ email_message = email.message_from_bytes(raw_email)
46
+
47
+ # Extract email metadata
48
+ sender = email_message['From']
49
+ receiver = email_message['To']
50
+ cc = email_message['Cc']
51
+ bcc = email_message['Bcc']
52
+ subject = email_message['Subject']
53
+ date = email_message['Date']
54
+
55
+ # print('sender : >>',type(sender), sender)
56
+ # Extract the email body
57
+ email_body = ""
58
+ if email_message.is_multipart():
59
+ for part in email_message.walk():
60
+ if part.get_content_type() == 'text/plain':
61
+ email_body = part.get_payload(decode=True).decode('utf-8')
62
+ break
63
+ else:
64
+ email_body = email_message.get_payload(decode=True).decode('utf-8')
65
+
66
+ extracted_details = get_details(email_body)
67
+ # print(type(extracted_details_str))
68
+ # extracted_details = json.loads(extracted_details_str)
69
+ # print(extracted_details)
70
+ print(type(extracted_details))
71
+ # Combine metadata and extracted details
72
+ meta_data = {
73
+ 'sender': sender,
74
+ 'receiver': receiver,
75
+ 'cc': cc,
76
+ 'bcc': bcc,
77
+ 'subject': subject
78
+ }
79
+ # print(type(meta_data))
80
+ extracted_details.update(meta_data)
81
+
82
+ print('full data about email ! ...::',extracted_details)
83
+ insert_data(extracted_details)
84
+ print('email analysed succesfully !\n')
85
+
86
+ except Exception as e:
87
+ print(f"Error processing email ID {message_id}: {e}")
88
+
89
+ # Close the connection
90
+ mail.close()
91
+ mail.logout()
92
+
93
+ except Exception as e:
94
+ print(f"Error reading emails: {e}")
95
+
96
+ def load_llm_model():
97
+ try:
98
+ # Check if GPU is available and set the device accordingly
99
+ device = "cuda" if torch.cuda.is_available() else "cpu"
100
+ print(f"Using device: {device}")
101
+
102
+ # Load the tokenizer
103
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct", trust_remote_code=True, cache_dir='./phi3_mini')
104
+
105
+ # Load the model in 8-bit precision directly
106
+ model = AutoModelForCausalLM.from_pretrained(
107
+ "microsoft/Phi-3-mini-128k-instruct",
108
+ load_in_8bit=True, # Directly use load_in_8bit
109
+ device_map="auto", # Automatically map layers to available device (GPU/CPU)
110
+ trust_remote_code=True,
111
+ cache_dir='./phi3_mini'
112
+ )
113
+ global pipe
114
+ # Create a pipeline for text generation
115
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
116
+
117
+ output = pipe("we are start to analyse email!", max_new_tokens=200)
118
+ print(output[0])
119
+ except Exception as e:
120
+ print(f"Error initializing LLM: {e}")
121
+
122
+ def extract_info(output):
123
+ text = output[0]['generated_text']
124
+ txt = text[len(prompt_):]
125
+
126
+
127
+ # Find the position of the first '{' character
128
+ start_index = txt.find('{')
129
+
130
+ # Find the position of the corresponding '}' character
131
+ end_index = txt.find('}', start_index)
132
+ ex_data = ''
133
+ # Extract the text between '{' and '}'
134
+ if start_index != -1 and end_index != -1:
135
+ extracted_data = txt[start_index:end_index + 1].strip()
136
+ cleaned_string = extracted_data.strip("{}")
137
+ print(extracted_data)
138
+ else:
139
+ print("Curly braces '{ }' not found in the text.")
140
+ start_index = txt.find('\n\nEx')
141
+ end_index = txt.find('\n\n', start_index)
142
+ if start_index != -1:
143
+ ex_data = txt[start_index:].strip()
144
+ print(ex_data)
145
+ else:
146
+ print("Curly braces '{ }' not found in the text.")
147
+
148
+ # data = ex_data
149
+ d = ex_data[23:]
150
+ info = d.replace('\n', '')
151
+ info.strip()
152
+ cleaned_string = ', '.join(part.strip() for part in info.split(',') if part.strip())
153
+
154
+ # Split the string into key-value pairs using a comma followed by a space
155
+ key_value_pairs = cleaned_string.split(", ")
156
+
157
+ # Create a dictionary to hold the extracted data
158
+ data_dict = {}
159
+
160
+ # Iterate through the key-value pairs and populate the dictionary
161
+ for pair in key_value_pairs:
162
+ # Split the pair into key and value at the first colon
163
+ if ": " in pair:
164
+ key, value = pair.split(": ", 2) # Use maxsplit=1 to handle values with colons
165
+ data_dict[key.strip()] = value.strip() # Strip any extra whitespace
166
+ # Display the resulting dictionary
167
+ # print(data_dict)
168
+ # print(type(data_dict))
169
+
170
+
171
+ # Extract the part starting from "description:" and ending with "quantities:"
172
+ start_key = "description:"
173
+ end_key = "quantities:"
174
+
175
+ # Find the start and end positions
176
+ start_index = cleaned_string.find(start_key) + len(start_key)
177
+ end_index = cleaned_string.find(end_key)
178
+
179
+ # Extract the description by slicing the string
180
+ description = cleaned_string[start_index:end_index].strip()
181
+ data_dict['description'] = description
182
+ # Print the extracted description
183
+
184
+
185
+ # print(data_dict['origin'],'\n',
186
+ # data_dict['destination'],'\n',
187
+ # data_dict['expected_shipment_datetime'],'\n',
188
+ # data_dict['types_of_service'],'\n',
189
+ # data_dict['warehouse'],'\n',
190
+ # data_dict['description'],'\n',
191
+ # data_dict['quantities'],'\n',
192
+ # data_dict['carrier_details'])
193
+ # print(description)
194
+ return data_dict
195
+
196
+ output_format = {
197
+ "origin": "",
198
+ "destination": "",
199
+ "Expected_shipment_datetime": "",
200
+ "Types of service": "",
201
+ "Warehouse": "",
202
+ "Description": "",
203
+ "Quantities": "",
204
+ "Carrier_details": ""
205
+ }
206
+
207
+ prompt = f"""
208
+ System prompt: You will be provided with an email containing shipment details. Your task is to extract specific information based on the given instructions.
209
+
210
+ Instructions:
211
+ 1. The input email may contain irrelevant information. Focus only on extracting details about future shipments.
212
+ 2. The output should be in JSON format. If a type of information is not found, it should be marked as null.
213
+ 3. Extract the following information:
214
+ - origin: The origin location of the consignment.
215
+ - destination: The destination location of the consignment.
216
+ - expected_shipment_datetime: The expected date and time of delivery to the warehouse (format: yyyy-mm-dd hh:mm:ss).
217
+ - types_of_service: The type of service (AIR, LCL, FCL). AIR can be mentioned as flight, aeroplane, or any mode of air transport. LCL is a Less-Container Load, and FCL is a Full-Container Load.
218
+ - warehouse: The name of the warehouse.
219
+ - description: A brief description of the email (ASN).
220
+ - quantities: The number of items in the shipment.
221
+ - carrier_details: The details of the carrier.
222
+ 4. the output extracted information contains must be in this format:
223
+ {{
224
+ "origin": "",
225
+ "destination": "",
226
+ "expected_shipment_datetime": "",
227
+ "types_of_service": "",
228
+ "warehouse": "",
229
+ "description": "",
230
+ "quantities": "",
231
+ "carrier_details": ""
232
+ }}
233
+ Examples:
234
+
235
+ 1. Email: We are pleased to inform you of an upcoming shipment originating from Hamburg and destined for New York. The shipment is expected to arrive on August 15, 2024. This consignment includes various electronics, with an estimated quantity of 200 units. The service type for this shipment is AIR, provided by our reliable carrier, Sky Logistics.
236
+ Extracted Information:
237
+ origin: Hamburg,
238
+ destination: New York,
239
+ expected_shipment_datetime: 2024-08-15 00:00:000,
240
+ types_of_service: AIR,
241
+ warehouse: Sky Logistics,
242
+ description: We are pleased to inform you of an upcoming shipment originating from Hamburg and destined for New York. The shipment is expected to arrive on August 15, 2024.,
243
+ quantities: 200 units,
244
+ carrier_details: Sky Logistics
245
+
246
+ 2. Email: Please be advised of a shipment from our supplier in Shanghai heading to Los Angeles. The expected date of arrival is July 30, 2024. The shipment consists of mixed goods, mainly textiles, with a total of 500 pieces. This delivery will be handled through LCL service by Ocean Freight Co.
247
+ Extracted Information:
248
+ origin: Shanghai,
249
+ destination: Los Angeles,
250
+ expected_shipment_datetime: 2024-07-30 00:00:0000,
251
+ types_of_service: LCL,
252
+ warehouse: Ocean Freight Co.,
253
+ description: Please be advised of a shipment from our supplier in Shanghai heading to Los Angeles. The expected date of arrival is July 30, 2024.,
254
+ quantities: 500 pieces,
255
+ carrier_details: Ocean Freight Co.
256
+
257
+ 3. Email: A new shipment is on its way from Mumbai to London, scheduled to reach by August 22, 2024. This batch contains furniture items, totaling 150 pieces. It is managed by Global Carriers.
258
+ Extracted Information:
259
+ origin: Mumbai,
260
+ destination: London,
261
+ expected_shipment_datetime: 2024-08-22 00:00:00000,
262
+ types_of_service: null,
263
+ warehouse: Global Carriers,
264
+ description: A new shipment is on its way from Mumbai to London, scheduled to reach by August 22, 2024.,
265
+ quantities: 150 pieces,
266
+ carrier_details: Global Carriers
267
+
268
+ 4. Email: We are notifying you about a shipment dispatched from Tokyo, heading towards Sydney, with an estimated arrival date of September 10, 2024. The cargo includes automotive parts, summing up to 350 units. This shipment will be transported via AIR service, operated by Jet Logistics.
269
+ Extracted Information:
270
+ origin: Tokyo,
271
+ destination: Sydney,
272
+ expected_shipment_datetime: 2024-09-10 00:00:0000,
273
+ types_of_service: AIR,
274
+ warehouse: Jet Logistics,
275
+ description: We are notifying you about a shipment dispatched from Tokyo, heading towards Sydney, with an estimated arrival date of September 10, 2024.,
276
+ quantities: 350 units,
277
+ carrier_details: Jet Logistics
278
+
279
+ 5. Email: Kindly note the details of a forthcoming shipment from Berlin to Toronto. The shipment encompasses various household goods, with a total quantity of 400 items. We have arranged for this to be shipped using LCL service, provided by Sea Wave Transport.
280
+ Extracted Information:
281
+ origin: Berlin,
282
+ destination: Toronto,
283
+ expected_shipment_datetime: null,
284
+ types_of_service: LCL,
285
+ warehouse: Sea Wave Transport,
286
+ description: Kindly note the details of a forthcoming shipment from Berlin to Toronto. The expected arrival is on August 5, 2024.,
287
+ quantities: 400 items,
288
+ carrier_details: Sea Wave Transport
289
+
290
+ Output: {output_format}
291
+ """
292
+
293
+ def insert_data(extracted_details):
294
+ try:
295
+ print('started !!')
296
+ # Initialize MySQL database connection
297
+ mydb = mysql.connector.connect(**DB_CONFIG)
298
+ cursor = mydb.cursor()
299
+ print('db connecyed ! ''')
300
+ # Check if any of the required fields are empty
301
+ required_fields = [
302
+ 'origin', 'destination', 'expected_shipment_datetime',
303
+ 'types_of_service', 'warehouse', 'description',
304
+ 'quantities', 'carrier_details'
305
+ ]
306
+ if all(extracted_details.get(field) in ["", None] for field in required_fields):
307
+ print("Skipping insertion: All specified extracted values are empty.")
308
+ return
309
+ sql = """
310
+ INSERT INTO shipment_details (origin, destination, expected_shipment_datetime, types_of_service, warehouse, description, quantities, carrier_details, sender, receiver, cc, bcc, subject)
311
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
312
+ """
313
+ # print(data_dict['origin'],'\n',
314
+ # data_dict['destination'],'\n',
315
+ # data_dict['expected_shipment_datetime'],'\n',
316
+ # data_dict['types_of_service'],'\n',
317
+ # data_dict['warehouse'],'\n',
318
+ # data_dict['description'],'\n',
319
+ # data_dict['quantities'],'\n',
320
+ # data_dict['carrier_details'])
321
+ # print(description)
322
+ print('ready to update ! ///')
323
+ val = (
324
+ extracted_details.get('origin'),
325
+ extracted_details.get('destination'),
326
+ extracted_details.get('expected_shipment_datetime'),
327
+ extracted_details.get('types_of_service'),
328
+ extracted_details.get('warehouse'),
329
+ extracted_details.get('description'),
330
+ extracted_details.get('quantities'),
331
+ extracted_details.get('carrier_details'),
332
+ extracted_details.get('sender'),
333
+ extracted_details.get('receiver'),
334
+ extracted_details.get('cc'),
335
+ extracted_details.get('bcc'),
336
+ extracted_details.get('subject')
337
+ )
338
+ cursor.execute(sql, val)
339
+ print('data inserted successfully ! ...')
340
+ mydb.commit()
341
+
342
+ except mysql.connector.Error as e:
343
+ print(f"Database error: {e}")
344
+ except Exception as e:
345
+ print(f"Error inserting data: {e}")
346
+
347
+ def get_details(mail):
348
+ # Example usage
349
+ # prompt = "Once upon a time"
350
+ global prompt_
351
+ prompt_ = prompt + mail
352
+ output = pipe(prompt_, max_new_tokens=400)
353
+ print(output[0])
354
+ extracted_info = extract_info(output)
355
+ print(extracted_info)
356
+
357
+ return extracted_info
358
+
359
+
360
+ running = False
361
+
362
+ def start():
363
+ global running
364
+ running = True
365
+ while running:
366
+ try:
367
+ print('Started running...')
368
+ read_email()
369
+ except Exception as e:
370
+ print(f"Error in main loop: {e}")
371
+ print('%' * 100)
372
+ time.sleep(10) # Sleep for 10 seconds before the next iteration
373
+
374
+ def stop():
375
+ global running
376
+ running = False
377
+ print("Stopped running.")
378
+
379
 
380
  # Function to capture print statements into the log box
381
  class StreamToText: