zumat commited on
Commit
d606f94
·
verified ·
1 Parent(s): 1f21f35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -206
app.py CHANGED
@@ -1,8 +1,4 @@
1
- from pathlib import Path
2
  import gradio as gr
3
- import re
4
- import pandas as pd
5
- import email
6
  from email import policy
7
  from email.parser import BytesParser
8
  import base64
@@ -15,11 +11,6 @@ import gpxpy
15
  import gpxpy.gpx
16
  from icalendar import Calendar
17
  import zipfile
18
- import tempfile
19
-
20
- # Ensure the Gradio cache directory exists
21
- gradio_cache_dir = '/tmp/gradio'
22
- Path(gradio_cache_dir).mkdir(parents=True, exist_ok=True)
23
 
24
  def decode_email_content(content, content_transfer_encoding):
25
  if content_transfer_encoding == 'base64':
@@ -29,8 +20,10 @@ def decode_email_content(content, content_transfer_encoding):
29
  return content
30
 
31
  def parse_email(raw_email):
 
32
  msg = BytesParser(policy=policy.default).parsebytes(raw_email)
33
 
 
34
  email_details = {
35
  "From": msg["From"],
36
  "To": msg["To"],
@@ -39,6 +32,7 @@ def parse_email(raw_email):
39
  "Body": ""
40
  }
41
 
 
42
  if msg.is_multipart():
43
  for part in msg.iter_parts():
44
  content_type = part.get_content_type()
@@ -65,207 +59,194 @@ def parse_email(raw_email):
65
 
66
  return email_details
67
 
68
- def parse_whatsapp_chat(input_file_path, output_file_path):
69
- with open(input_file_path, 'r', encoding='utf-8') as input_file:
70
- lines = input_file.readlines()
71
-
72
- messages = []
73
- for line in lines:
74
- try:
75
- if line.startswith('['):
76
- date_time, sender_message = line[1:].split('] ', 1)
77
- date, time = date_time.split(', ')
78
- sender, message = sender_message.split(': ', 1)
79
- messages.append([date, time, sender, message])
80
- except ValueError:
81
- print(f"Skipping line due to error: {line.strip()} - not enough values to unpack (expected 2, got 1)")
82
-
83
- with open(output_file_path, 'w', newline='', encoding='utf-8') as output_file:
84
- writer = csv.writer(output_file)
85
- writer.writerow(['Date', 'Time', 'Sender', 'Message'])
86
- writer.writerows(messages)
87
-
88
- print(f"File {output_file_path} written with {len(messages)} records")
89
-
90
  def dataManipulator(converter, filepath):
91
  global output_file
92
  output_file = filepath
93
 
94
- try:
95
- if converter == "Email Converter":
96
- records = []
97
-
98
- with open(filepath, 'rb') as file:
99
- raw_email_data = file.read()
100
-
101
- email_entries = raw_email_data.split(b'\nFrom ')
102
-
103
- for raw_email in email_entries:
104
- if not raw_email.startswith(b'From '):
105
- raw_email = b'From ' + raw_email
106
-
107
- parsed_email = parse_email(raw_email)
108
-
109
- record_data = {
110
- "date and time": parsed_email["Date"],
111
- "from": parsed_email["From"],
112
- "to": parsed_email["To"],
113
- "Cc": "", # Add Cc if needed, parse_email function does not extract it by default
114
- "Subject": parsed_email["Subject"],
115
- "Content": parsed_email["Body"]
116
- }
117
-
118
- records.append(record_data)
119
-
120
- print("Email records parsed:", records)
121
-
122
- output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
123
-
124
- columns = ["date and time", "from", "to", "Cc", "Subject", "Content"]
125
-
126
- with open(output_file, 'w', newline='') as csvfile:
127
- writer = csv.DictWriter(csvfile, fieldnames=columns)
128
-
129
- writer.writeheader()
130
- for record in records:
131
- writer.writerow(record)
132
-
133
- return output_file
134
-
135
- if converter == "Calendar Converter":
136
- with open(filepath, 'rb') as file:
137
- calendar = Calendar.from_ical(file.read())
138
-
139
- records = []
140
- for component in calendar.walk():
141
- if component.name == "VEVENT":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  records.append({
143
- "summary": component.get('summary'),
144
- "dtstart": component.get('dtstart').dt,
145
- "dtend": component.get('dtend').dt,
146
- "description": component.get('description'),
147
- "location": component.get('location')
148
  })
149
 
150
- print("Calendar records parsed:", records)
151
-
152
- output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
153
-
154
- with open(output_file, 'w', newline='') as csvfile:
155
- fieldnames = ["summary", "dtstart", "dtend", "description", "location"]
156
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
157
-
158
- writer.writeheader()
159
- for record in records:
160
- writer.writerow(record)
161
-
162
- return output_file
163
-
164
- if converter == "AppleHealth Converter":
165
- tree = ET.parse(filepath)
166
- root = tree.getroot()
167
- records = []
168
-
169
- columns = ["startDate", "endDate", "device", "sourceName", "type", "unit", "value"]
170
-
171
- for record in root.findall('Record'):
172
- record_data = {key: record.attrib.get(key, '') for key in columns}
173
- records.append(record_data)
174
-
175
- print("AppleHealth records parsed:", records)
176
-
177
- output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
178
-
179
- with open(output_file, 'w', newline='') as csvfile:
180
- writer = csv.DictWriter(csvfile, fieldnames=columns)
181
-
182
- writer.writeheader()
183
- for record in records:
184
- writer.writerow(record)
185
-
186
- return output_file
187
-
188
- if converter == "AppleHealth GPS Converter":
189
- with open(filepath, 'r') as file:
190
- gpx = gpxpy.parse(file)
191
-
192
- records = []
193
- for track in gpx.tracks:
194
- for segment in track.segments:
195
- for point in segment.points:
196
- records.append({
197
- "latitude": point.latitude,
198
- "longitude": point.longitude,
199
- "elevation": point.elevation,
200
- "time": point.time
201
- })
202
-
203
- print("AppleHealth GPS records parsed:", records)
204
-
205
- output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
206
-
207
- with open(output_file, 'w', newline='') as csvfile:
208
- fieldnames = records[0].keys() if records else []
209
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
210
-
211
- writer.writeheader()
212
- for record in records:
213
- writer.writerow(record)
214
-
215
- return output_file
216
-
217
- if converter == "WhatsApp Converter":
218
- parse_whatsapp_chat(input_file_path, output_file)
219
- return output_file
220
-
221
- if converter == "Google Foto Converter":
222
- records = []
223
- with zipfile.ZipFile(filepath, 'r') as zip_ref:
224
- zip_ref.extractall('json_folder')
225
-
226
- for filename in os.listdir('json_folder'):
227
- if filename.endswith('.json'):
228
- with open(os.path.join('json_folder', filename), 'r') as json_file:
229
- data = json.load(json_file)
230
- records.append(data)
231
-
232
- print("Google Foto records parsed:", records)
233
-
234
- output_file = 'googleFotoConverted.csv'
235
-
236
- with open(output_file, 'w', newline='') as csvfile:
237
- fieldnames = set()
238
- for record in records:
239
- fieldnames.update(record.keys())
240
- writer = csv.DictWriter(csvfile, fieldnames=list(fieldnames))
241
-
242
- writer.writeheader()
243
- for record in records:
244
- writer.writerow(record)
245
-
246
- return output_file
247
- except Exception as e:
248
- return f"Error: {str(e)}"
249
-
250
- return "Converter type not recognized."
251
-
252
- def process_input(input_file, state):
253
- try:
254
- if input_file is not None:
255
- output_file = dataManipulator(None, input_file.name)
256
- return gr.File.update(value=output_file, label="Download converted file"), state
257
- else:
258
- return gr.Textbox.update(value="No file uploaded."), state
259
- except Exception as e:
260
- return gr.Textbox.update(value=f"Error processing WhatsApp file: {str(e)}"), state
261
-
262
- with gr.Blocks() as demo:
263
- converter = gr.Dropdown(["Email Converter", "Calendar Converter", "AppleHealth Converter", "AppleHealth GPS Converter", "WhatsApp Converter", "Google Foto Converter"], label="Select Converter")
264
- input_file = gr.File(label="Upload File")
265
- output_file = gr.File(label="Download converted file")
266
- error_message = gr.Textbox(label="Error Message", interactive=False)
267
-
268
- process_button = gr.Button("Process")
269
- process_button.click(fn=process_input, inputs=[converter, input_file], outputs=[output_file, error_message])
270
-
271
- demo.launch()
 
 
1
  import gradio as gr
 
 
 
2
  from email import policy
3
  from email.parser import BytesParser
4
  import base64
 
11
  import gpxpy.gpx
12
  from icalendar import Calendar
13
  import zipfile
 
 
 
 
 
14
 
15
  def decode_email_content(content, content_transfer_encoding):
16
  if content_transfer_encoding == 'base64':
 
20
  return content
21
 
22
  def parse_email(raw_email):
23
+ # Parsing the raw email content
24
  msg = BytesParser(policy=policy.default).parsebytes(raw_email)
25
 
26
+ # Extracting email details
27
  email_details = {
28
  "From": msg["From"],
29
  "To": msg["To"],
 
32
  "Body": ""
33
  }
34
 
35
+ # Extracting the email body content
36
  if msg.is_multipart():
37
  for part in msg.iter_parts():
38
  content_type = part.get_content_type()
 
59
 
60
  return email_details
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def dataManipulator(converter, filepath):
63
  global output_file
64
  output_file = filepath
65
 
66
+ if converter == "Email Converter":
67
+ records = []
68
+
69
+ with open(filepath, 'rb') as file:
70
+ raw_email_data = file.read()
71
+
72
+ email_entries = raw_email_data.split(b'\nFrom ')
73
+
74
+ for raw_email in email_entries:
75
+ if not raw_email.startswith(b'From '):
76
+ raw_email = b'From ' + raw_email
77
+
78
+ parsed_email = parse_email(raw_email)
79
+
80
+ record_data = {
81
+ "date and time": parsed_email["Date"],
82
+ "from": parsed_email["From"],
83
+ "to": parsed_email["To"],
84
+ "Cc": "", # Add Cc if needed, parse_email function does not extract it by default
85
+ "Subject": parsed_email["Subject"],
86
+ "Content": parsed_email["Body"]
87
+ }
88
+
89
+ records.append(record_data)
90
+
91
+ output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
92
+
93
+ columns = ["date and time", "from", "to", "Cc", "Subject", "Content"]
94
+
95
+ with open(output_file, 'w', newline='') as csvfile:
96
+ writer = csv.DictWriter(csvfile, fieldnames=columns)
97
+
98
+ writer.writeheader()
99
+ for record in records:
100
+ writer.writerow(record)
101
+
102
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
103
+ if converter == "Calendar Converter":
104
+ with open(filepath, 'rb') as file:
105
+ calendar = Calendar.from_ical(file.read())
106
+
107
+ records = []
108
+ for component in calendar.walk():
109
+ if component.name == "VEVENT":
110
+ records.append({
111
+ "summary": component.get('summary'),
112
+ "dtstart": component.get('dtstart').dt,
113
+ "dtend": component.get('dtend').dt,
114
+ "description": component.get('description'),
115
+ "location": component.get('location')
116
+ })
117
+
118
+ output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
119
+
120
+ with open(output_file, 'w', newline='') as csvfile:
121
+ fieldnames = ["summary", "dtstart", "dtend", "description", "location"]
122
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
123
+
124
+ writer.writeheader()
125
+ for record in records:
126
+ writer.writerow(record)
127
+
128
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
129
+ if converter == "AppleHealth Converter":
130
+ tree = ET.parse(filepath)
131
+ root = tree.getroot()
132
+ records = []
133
+
134
+ columns = ["startDate", "endDate", "device", "sourceName", "type", "unit", "value"]
135
+
136
+ for record in root.findall('Record'):
137
+ record_data = {key: record.attrib.get(key, '') for key in columns}
138
+ records.append(record_data)
139
+
140
+ output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
141
+
142
+ with open(output_file, 'w', newline='') as csvfile:
143
+ writer = csv.DictWriter(csvfile, fieldnames=columns)
144
+
145
+ writer.writeheader()
146
+ for record in records:
147
+ writer.writerow(record)
148
+
149
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
150
+ if converter == "AppleHealth GPS Converter":
151
+ with open(filepath, 'r') as filepath:
152
+ gpx = gpxpy.parse(filepath)
153
+
154
+ records = []
155
+ for track in gpx.tracks:
156
+ for segment in track.segments:
157
+ for point in segment.points:
158
  records.append({
159
+ "latitude": point.latitude,
160
+ "longitude": point.longitude,
161
+ "elevation": point.elevation,
162
+ "time": point.time
 
163
  })
164
 
165
+ output_file = os.path.basename(os.path.splitext(filepath.name)[0]) + '_converted.csv'
166
+
167
+ with open(output_file, 'w', newline='') as csvfile:
168
+ fieldnames = records[0].keys()
169
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
170
+
171
+ writer.writeheader()
172
+ for record in records:
173
+ writer.writerow(record)
174
+
175
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
176
+ if converter == "WhatsApp Converter":
177
+ with open(filepath, 'r', errors='ignore') as file:
178
+ lines = file.readlines()
179
+
180
+ records = []
181
+ for line in lines:
182
+ if ', ' in line and ': ' in line:
183
+ date_time, message = line.split(' - ', 1)
184
+ date, time = date_time.split(', ')
185
+ sender, message = message.split(': ', 1)
186
+ records.append({
187
+ "date": date,
188
+ "time": time,
189
+ "sender": sender,
190
+ "message": message
191
+ })
192
+
193
+ output_file = os.path.basename(os.path.splitext(filepath)[0]) + '_converted.csv'
194
+
195
+ with open(output_file, 'w', newline='') as csvfile:
196
+ fieldnames = ["date", "time", "sender", "message"]
197
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
198
+
199
+ writer.writeheader()
200
+ for record in records:
201
+ writer.writerow(record)
202
+
203
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
204
+ if converter == "Google Foto Converter":
205
+ records = []
206
+ # Unzip the file
207
+ with zipfile.ZipFile(filepath, 'r') as zip_ref:
208
+ zip_ref.extractall('json_folder')
209
+
210
+ # Process the extracted files
211
+ records = []
212
+ for filename in os.listdir('json_folder'):
213
+ if filename.endswith('.json'):
214
+ with open(os.path.join('json_folder', filename), 'r') as json_file:
215
+ data = json.load(json_file)
216
+ records.append(data)
217
+
218
+ for filename in os.listdir('json_folder'):
219
+ if filename.endswith('.json'):
220
+ with open(os.path.join('json_folder', filename), 'r') as json_file:
221
+ data = json.load(json_file)
222
+ records.append(data)
223
+
224
+ output_file = 'googleFotoConverted.csv'
225
+
226
+ with open(output_file, 'w', newline='') as csvfile:
227
+ fieldnames = set()
228
+ for record in records:
229
+ fieldnames.update(record.keys())
230
+ writer = csv.DictWriter(csvfile, fieldnames=list(fieldnames))
231
+
232
+ writer.writeheader()
233
+ for record in records:
234
+ writer.writerow(record)
235
+
236
+ return gr.DownloadButton(label=f"Download {output_file}", value=output_file, interactive=True)
237
+ else:
238
+ return gr.DownloadButton(label="Download not ready", value="output_file", interactive=False)
239
+
240
+
241
+ demo = gr.Interface(
242
+ dataManipulator,
243
+ [
244
+ gr.Radio(["Email Converter", "Calendar Converter", "AppleHealth Converter", "AppleHealth GPS Converter", "WhatsApp Converter", "Google Foto Converter"], label="Select a converter:"),
245
+ gr.File(label="Upload a file"),
246
+ ],
247
+ outputs=gr.DownloadButton(label="Download not ready", value="output_file", interactive=False),
248
+ allow_flagging="never",
249
+ )
250
+
251
+ if __name__ == "__main__":
252
+ demo.launch()