Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,6 +7,7 @@ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
|
7 |
import email, imaplib, json, time
|
8 |
import torch, logging
|
9 |
import uvicorn
|
|
|
10 |
|
11 |
app = FastAPI()
|
12 |
|
@@ -197,13 +198,6 @@ def read_email():
|
|
197 |
running = False
|
198 |
loop_thread = None
|
199 |
|
200 |
-
def email_processing_loop():
|
201 |
-
global running
|
202 |
-
logger.info("Starting email processing loop...")
|
203 |
-
while running:
|
204 |
-
read_email()
|
205 |
-
time.sleep(10) # Check for new emails every 10 seconds
|
206 |
-
|
207 |
# HTML content for the web interface
|
208 |
html_content = """
|
209 |
<!DOCTYPE html>
|
@@ -228,124 +222,59 @@ html_content = """
|
|
228 |
</head>
|
229 |
<body>
|
230 |
<h1>Email Processing Status: {{ status }}</h1>
|
231 |
-
<button onclick="window.location.href='/start'">Start Processing</button>
|
232 |
-
<button class="stop" onclick="window.location.href='/stop'">Stop Processing</button>
|
233 |
</body>
|
234 |
</html>
|
235 |
"""
|
236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
237 |
@app.get("/", response_class=HTMLResponse)
|
238 |
async def home():
|
239 |
-
# service = authenticate_gmail()
|
240 |
-
# logger.info(service)
|
241 |
-
# print(service)
|
242 |
-
# if service:
|
243 |
-
# get_latest_email(service)
|
244 |
global running
|
245 |
status = "Running" if running else "Stopped"
|
246 |
return HTMLResponse(content=html_content.replace("{{ status }}", status), status_code=200)
|
247 |
|
248 |
-
# Endpoint to start the email processing loop
|
249 |
-
@app.
|
250 |
-
async def
|
251 |
global running, loop_thread
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
async def stop_processing():
|
262 |
-
global running
|
263 |
-
if running:
|
264 |
-
running = False
|
265 |
-
status = "Stopped"
|
266 |
-
return HTMLResponse(content=html_content.replace("{{ status }}", status), status_code=200)
|
267 |
-
|
268 |
-
|
269 |
-
import os.path
|
270 |
-
import base64
|
271 |
-
import json
|
272 |
-
import pickle
|
273 |
-
from google.auth.transport.requests import Request
|
274 |
-
from google.oauth2.credentials import Credentials
|
275 |
-
from google_auth_oauthlib.flow import InstalledAppFlow
|
276 |
-
from googleapiclient.discovery import build
|
277 |
-
from googleapiclient.errors import HttpError
|
278 |
-
|
279 |
-
# If modifying these SCOPES, delete the file token.json.
|
280 |
-
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
|
281 |
-
|
282 |
-
def authenticate_gmail():
|
283 |
-
"""Shows basic usage of the Gmail API.
|
284 |
-
Lists the user's Gmail labels.
|
285 |
-
"""
|
286 |
-
creds = None
|
287 |
-
# The file token.json stores the user's access and refresh tokens, and is
|
288 |
-
# created automatically when the authorization flow completes for the first time.
|
289 |
-
if os.path.exists('token.json'):
|
290 |
-
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
|
291 |
-
# If there are no (valid) credentials available, let the user log in.
|
292 |
-
if not creds or not creds.valid:
|
293 |
-
if creds and creds.expired and creds.refresh_token:
|
294 |
-
creds.refresh(Request())
|
295 |
else:
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
print(f'An error occurred: {error}')
|
309 |
-
return None
|
310 |
-
|
311 |
-
def get_latest_email(service):
|
312 |
-
"""Get the latest email from the inbox"""
|
313 |
-
try:
|
314 |
-
# Retrieve a list of messages
|
315 |
-
results = service.users().messages().list(userId='me', maxResults=1).execute()
|
316 |
-
messages = results.get('messages', [])
|
317 |
-
|
318 |
-
if not messages:
|
319 |
-
print('No messages found.')
|
320 |
-
return
|
321 |
-
|
322 |
-
# Get the message ID
|
323 |
-
message_id = messages[0]['id']
|
324 |
-
|
325 |
-
# Fetch the email content by message ID
|
326 |
-
message = service.users().messages().get(userId='me', id=message_id, format='full').execute()
|
327 |
-
|
328 |
-
# Get the email payload
|
329 |
-
payload = message['payload']
|
330 |
-
headers = payload.get('headers', [])
|
331 |
-
|
332 |
-
# Print the sender, subject, and body of the email
|
333 |
-
for header in headers:
|
334 |
-
if header['name'] == 'From':
|
335 |
-
print(f"From: {header['value']}")
|
336 |
-
if header['name'] == 'Subject':
|
337 |
-
print(f"Subject: {header['value']}")
|
338 |
-
|
339 |
-
# Extract the body
|
340 |
-
parts = payload.get('parts', [])
|
341 |
-
for part in parts:
|
342 |
-
if part.get('mimeType') == 'text/plain':
|
343 |
-
body = part.get('body', {}).get('data', '')
|
344 |
-
body_decoded = base64.urlsafe_b64decode(body).decode('utf-8')
|
345 |
-
print(f"Body: {body_decoded}")
|
346 |
-
|
347 |
-
except HttpError as error:
|
348 |
-
print(f'An error occurred: {error}')
|
349 |
|
350 |
if __name__ == "__main__":
|
351 |
|
|
|
7 |
import email, imaplib, json, time
|
8 |
import torch, logging
|
9 |
import uvicorn
|
10 |
+
from pydantic import BaseModel
|
11 |
|
12 |
app = FastAPI()
|
13 |
|
|
|
198 |
running = False
|
199 |
loop_thread = None
|
200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
# HTML content for the web interface
|
202 |
html_content = """
|
203 |
<!DOCTYPE html>
|
|
|
222 |
</head>
|
223 |
<body>
|
224 |
<h1>Email Processing Status: {{ status }}</h1>
|
|
|
|
|
225 |
</body>
|
226 |
</html>
|
227 |
"""
|
228 |
+
|
229 |
+
# Define a model for the incoming JSON data
|
230 |
+
class ActionModel(BaseModel):
|
231 |
+
action: str # The action can be 'start' or 'stop'
|
232 |
+
|
233 |
+
class ModelData(BaseModel):
|
234 |
+
data: str
|
235 |
+
|
236 |
+
# Function to process emails in a loop
|
237 |
+
def email_processing_loop():
|
238 |
+
global running
|
239 |
+
logger.info("Starting email processing loop...")
|
240 |
+
while running:
|
241 |
+
# read_email() # Assuming this is your email processing function
|
242 |
+
print("$"*100)
|
243 |
+
time.sleep(10) # Check for new emails every 10 seconds
|
244 |
+
|
245 |
+
# Endpoint to display the current email processor status
|
246 |
@app.get("/", response_class=HTMLResponse)
|
247 |
async def home():
|
|
|
|
|
|
|
|
|
|
|
248 |
global running
|
249 |
status = "Running" if running else "Stopped"
|
250 |
return HTMLResponse(content=html_content.replace("{{ status }}", status), status_code=200)
|
251 |
|
252 |
+
# Endpoint to receive JSON data to start/stop the email processing loop
|
253 |
+
@app.post("/control", response_class=HTMLResponse)
|
254 |
+
async def control_email_loop(action: ActionModel,data: ModelData):
|
255 |
global running, loop_thread
|
256 |
+
logger.info(action.action)
|
257 |
+
if action.action == "start":
|
258 |
+
if not running:
|
259 |
+
running = True
|
260 |
+
email_data = data.data.dict()
|
261 |
+
logger.info(email_data)
|
262 |
+
loop_thread = threading.Thread(target=email_processing_loop, daemon=True)
|
263 |
+
loop_thread.start()
|
264 |
+
logger.info("Email processing loop started.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
265 |
else:
|
266 |
+
logger.info("Email processing loop is already running.")
|
267 |
+
elif action.action == "stop":
|
268 |
+
if running:
|
269 |
+
running = False
|
270 |
+
logger.info("Email processing loop stopped.")
|
271 |
+
else:
|
272 |
+
logger.info("Email processing loop is not running.")
|
273 |
+
else:
|
274 |
+
raise HTTPException(status_code=400, detail="Invalid action. Use 'start' or 'stop'.")
|
275 |
+
|
276 |
+
status = "Running" if running else "Stopped"
|
277 |
+
return HTMLResponse(content=html_content.replace("{{ status }}", status), status_code=200)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
278 |
|
279 |
if __name__ == "__main__":
|
280 |
|