qqwjq1981 commited on
Commit
33d8b75
·
verified ·
1 Parent(s): 994df47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1150 -3
app.py CHANGED
@@ -1,13 +1,1160 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import uvicorn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  app = FastAPI()
6
 
7
- @app.get("/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  async def index():
9
- return {"message": "App is running"}
 
 
 
 
 
 
 
 
 
 
 
 
10
 
 
11
  if __name__ == "__main__":
12
  port = int(os.getenv("PORT", 7860)) # Default to 7860 if PORT is not set
13
  uvicorn.run(app, host="0.0.0.0", port=port)
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+
5
+ # In[2]:
6
+
7
+
8
+ #pip install evernote-sdk-python3
9
+ # import evernote.edam.notestore.NoteStore as NoteStore
10
+ # import evernote.edam.type.ttypes as Types
11
+ # from evernote.api.client import EvernoteClient
12
+
13
+
14
+ # In[3]:
15
+
16
+
17
+ import os
18
+ import yaml
19
+ import pandas as pd
20
+ import numpy as np
21
+
22
+ from datetime import datetime, timedelta
23
+
24
+ # perspective generation
25
+ import openai
26
  import os
27
+ from openai import OpenAI
28
+
29
+ import gradio as gr
30
+
31
+ import json
32
+
33
+ import sqlite3
34
+ import uuid
35
+ import socket
36
+ import difflib
37
+ import time
38
+ import shutil
39
+ import requests
40
+ import re
41
+
42
+ import json
43
+ import markdown
44
+ from fpdf import FPDF
45
+ import hashlib
46
+
47
+ from transformers import pipeline
48
+ from transformers.pipelines.audio_utils import ffmpeg_read
49
+
50
+ from todoist_api_python.api import TodoistAPI
51
+
52
+ # from flask import Flask, request, jsonify
53
+ from twilio.rest import Client
54
+
55
+ import asyncio
56
  import uvicorn
57
+ from fastapi import FastAPI, Request, HTTPException
58
+ from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
59
+
60
+ import nest_asyncio
61
+ from twilio.twiml.messaging_response import MessagingResponse
62
+
63
+ from requests.auth import HTTPBasicAuth
64
+
65
+ from google.cloud import storage, exceptions # Import exceptions for error handling
66
+ from google.cloud.exceptions import NotFound
67
+ from google.oauth2 import service_account
68
+
69
+ from reportlab.pdfgen import canvas
70
+ from reportlab.lib.pagesizes import letter
71
+ from reportlab.pdfbase import pdfmetrics
72
+ from reportlab.lib import colors
73
+ from reportlab.pdfbase.ttfonts import TTFont
74
+
75
+ import logging
76
+
77
+ # Configure logging
78
+ logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
79
+ logger = logging.getLogger(__name__)
80
+
81
+
82
+ # In[4]:
83
+
84
+ # Access the API keys and other configuration data
85
+ openai_api_key = os.environ["OPENAI_API_KEY"]
86
+ # Access the API keys and other configuration data
87
+ todoist_api_key = os.environ["TODOIST_API_KEY"]
88
+
89
+ EVERNOTE_API_TOKEN = os.environ["EVERNOTE_API_TOKEN"]
90
+
91
+ account_sid = os.environ["TWILLO_ACCOUNT_SID"]
92
+ auth_token = os.environ["TWILLO_AUTH_TOKEN"]
93
+ twilio_phone_number = os.environ["TWILLO_PHONE_NUMBER"]
94
+
95
+ google_credentials_json = os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
96
+ twillo_client = Client(account_sid, auth_token)
97
+
98
+ # Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
99
+
100
+ # Load Reasoning Graph JSON File
101
+ def load_reasoning_json(filepath):
102
+ """Load JSON file and return the dictionary."""
103
+ with open(filepath, "r") as file:
104
+ data = json.load(file)
105
+ return data
106
+
107
+ # Load Action Map
108
+ def load_action_map(filepath):
109
+ """Load action map JSON file and map strings to actual function objects."""
110
+ with open(filepath, "r") as file:
111
+ action_map_raw = json.load(file)
112
+ # Map string names to actual functions using globals()
113
+ return {action: globals()[func_name] for action, func_name in action_map_raw.items()}
114
+
115
+
116
+ # In[5]:
117
+
118
+
119
+ # Define all actions as functions
120
+
121
+ def find_reference(task_topic):
122
+ """Finds a reference related to the task topic."""
123
+ print(f"Finding reference for topic: {task_topic}")
124
+ return f"Reference found for topic: {task_topic}"
125
+
126
+ def generate_summary(reference):
127
+ """Generates a summary of the reference."""
128
+ print(f"Generating summary for reference: {reference}")
129
+ return f"Summary of {reference}"
130
+
131
+ def suggest_relevance(summary):
132
+ """Suggests how the summary relates to the project."""
133
+ print(f"Suggesting relevance of summary: {summary}")
134
+ return f"Relevance of {summary} suggested"
135
+
136
+ def tool_research(task_topic):
137
+ """Performs tool research and returns analysis."""
138
+ print("Performing tool research")
139
+ return "Tool analysis data"
140
+
141
+ def generate_comparison_table(tool_analysis):
142
+ """Generates a comparison table for a competitive tool."""
143
+ print(f"Generating comparison table for analysis: {tool_analysis}")
144
+ return f"Comparison table for {tool_analysis}"
145
+
146
+ def generate_integration_memo(tool_analysis):
147
+ """Generates an integration memo for a tool."""
148
+ print(f"Generating integration memo for analysis: {tool_analysis}")
149
+ return f"Integration memo for {tool_analysis}"
150
+
151
+ def analyze_issue(task_topic):
152
+ """Analyzes an issue and returns the analysis."""
153
+ print("Analyzing issue")
154
+ return "Issue analysis data"
155
+
156
+ def generate_issue_memo(issue_analysis):
157
+ """Generates an issue memo based on the analysis."""
158
+ print(f"Generating issue memo for analysis: {issue_analysis}")
159
+ return f"Issue memo for {issue_analysis}"
160
+
161
+ def list_ideas(task_topic):
162
+ """Lists potential ideas for brainstorming."""
163
+ print("Listing ideas")
164
+ return ["Idea 1", "Idea 2", "Idea 3"]
165
+
166
+ def construct_matrix(ideas):
167
+ """Constructs a matrix (e.g., feasibility or impact/effort) for the ideas."""
168
+ print(f"Constructing matrix for ideas: {ideas}")
169
+ return {"Idea 1": "High Impact/Low Effort", "Idea 2": "Low Impact/High Effort", "Idea 3": "High Impact/High Effort"}
170
+
171
+ def prioritize_ideas(matrix):
172
+ """Prioritizes ideas based on the matrix."""
173
+ print(f"Prioritizing ideas based on matrix: {matrix}")
174
+ return ["Idea 3", "Idea 1", "Idea 2"]
175
+
176
+ def setup_action_plan(prioritized_ideas):
177
+ """Sets up an action plan based on the prioritized ideas."""
178
+ print(f"Setting up action plan for ideas: {prioritized_ideas}")
179
+ return f"Action plan created for {prioritized_ideas}"
180
+
181
+ def unsupported_task(task_topic):
182
+ """Handles unsupported tasks."""
183
+ print("Task not supported")
184
+ return "Unsupported task"
185
+
186
+
187
+ # In[6]:
188
+
189
+
190
+ todoist_api = TodoistAPI(todoist_api_key)
191
+
192
+ # Fetch recent Todoist task
193
+ def fetch_todoist_task():
194
+ try:
195
+ tasks = todoist_api.get_tasks()
196
+ if tasks:
197
+ recent_task = tasks[0] # Fetch the most recent task
198
+ return f"Recent Task: {recent_task.content}"
199
+ return "No tasks found in Todoist."
200
+ except Exception as e:
201
+ return f"Error fetching tasks: {str(e)}"
202
+
203
+ def add_to_todoist(task_topic, todoist_priority = 3):
204
+ try:
205
+ # Create a task in Todoist using the Todoist API
206
+ # Assuming you have a function `todoist_api.add_task()` that handles the API request
207
+ todoist_api.add_task(
208
+ content=task_topic,
209
+ priority=todoist_priority
210
+ )
211
+ msg = f"Task added: {task_topic} with priority {todoist_priority}"
212
+ logger.debug(msg)
213
+
214
+ return msg
215
+ except Exception as e:
216
+ # Return an error message if something goes wrong
217
+ return f"An error occurred: {e}"
218
+
219
+ # def save_todo(reasoning_steps):
220
+ # """
221
+ # Save reasoning steps to Todoist as tasks.
222
+
223
+ # Args:
224
+ # reasoning_steps (list of dict): A list of steps with "step" and "priority" keys.
225
+ # """
226
+ # try:
227
+ # # Validate that reasoning_steps is a list
228
+ # if not isinstance(reasoning_steps, list):
229
+ # raise ValueError("The input reasoning_steps must be a list.")
230
+
231
+ # # Iterate over the reasoning steps
232
+ # for step in reasoning_steps:
233
+ # # Ensure each step is a dictionary and contains required keys
234
+ # if not isinstance(step, dict) or "step" not in step or "priority" not in step:
235
+ # logger.error(f"Invalid step data: {step}, skipping.")
236
+ # continue
237
+
238
+ # task_content = step["step"]
239
+ # priority_level = step["priority"]
240
+
241
+ # # Map priority to Todoist's priority levels (1 - low, 4 - high)
242
+ # priority_mapping = {"Low": 1, "Medium": 2, "High": 4}
243
+ # todoist_priority = priority_mapping.get(priority_level, 1) # Default to low if not found
244
+
245
+ # # Create a task in Todoist using the Todoist API
246
+ # # Assuming you have a function `todoist_api.add_task()` that handles the API request
247
+ # todoist_api.add_task(
248
+ # content=task_content,
249
+ # priority=todoist_priority
250
+ # )
251
+
252
+ # logger.debug(f"Task added: {task_content} with priority {priority_level}")
253
+
254
+ # return "All tasks processed."
255
+ # except Exception as e:
256
+ # # Return an error message if something goes wrong
257
+ # return f"An error occurred: {e}"
258
+
259
+
260
+ # In[7]:
261
+
262
+
263
+ # evernote_client = EvernoteClient(token=EVERNOTE_API_TOKEN, sandbox=False)
264
+ # note_store = evernote_client.get_note_store()
265
+
266
+ # def add_to_evernote(task_topic, notebook_title="Inspirations"):
267
+ # """
268
+ # Add a task topic to the 'Inspirations' notebook in Evernote. If the notebook doesn't exist, create it.
269
+
270
+ # Args:
271
+ # task_topic (str): The content of the task to be added.
272
+ # notebook_title (str): The title of the Evernote notebook. Default is 'Inspirations'.
273
+ # """
274
+ # try:
275
+ # # Check if the notebook exists
276
+ # notebooks = note_store.listNotebooks()
277
+ # notebook = next((nb for nb in notebooks if nb.name == notebook_title), None)
278
+
279
+ # # If the notebook doesn't exist, create it
280
+ # if not notebook:
281
+ # notebook = Types.Notebook()
282
+ # notebook.name = notebook_title
283
+ # notebook = note_store.createNotebook(notebook)
284
+
285
+ # # Search for an existing note with the same title
286
+ # filter = NoteStore.NoteFilter()
287
+ # filter.notebookGuid = notebook.guid
288
+ # filter.words = notebook_title
289
+ # notes_metadata_result = note_store.findNotesMetadata(filter, 0, 1, NoteStore.NotesMetadataResultSpec(includeTitle=True))
290
+
291
+ # # If a note with the title exists, append to it; otherwise, create a new note
292
+ # if notes_metadata_result.notes:
293
+ # note_guid = notes_metadata_result.notes[0].guid
294
+ # existing_note = note_store.getNote(note_guid, True, False, False, False)
295
+ # existing_note.content = existing_note.content.replace("</en-note>", f"<div>{task_topic}</div></en-note>")
296
+ # note_store.updateNote(existing_note)
297
+ # else:
298
+ # # Create a new note
299
+ # note = Types.Note()
300
+ # note.title = notebook_title
301
+ # note.notebookGuid = notebook.guid
302
+ # note.content = f'<?xml version="1.0" encoding="UTF-8"?>' \
303
+ # f'<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' \
304
+ # f'<en-note><div>{task_topic}</div></en-note>'
305
+ # note_store.createNote(note)
306
+
307
+ # print(f"Task '{task_topic}' successfully added to Evernote under '{notebook_title}'.")
308
+ # except Exception as e:
309
+ # print(f"Error adding task to Evernote: {e}")
310
+
311
+ # Mock Functions for Task Actions
312
+ def add_to_evernote(task_topic):
313
+ return f"Task added to Evernote with title '{task_topic}'."
314
+
315
+
316
+ # In[8]:
317
+
318
+
319
+ # Access the API keys and other configuration data
320
+ TASK_WORKFLOW_TREE = load_reasoning_json('curify_ideas_reasoning.json')
321
+ action_map = load_action_map('action_map.json')
322
+
323
+ # In[9]:
324
+
325
+
326
+ def generate_task_hash(task_description):
327
+ try:
328
+ # Ensure task_description is a string
329
+ if not isinstance(task_description, str):
330
+ logger.warning("task_description is not a string, attempting conversion.")
331
+ task_description = str(task_description)
332
+
333
+ # Safely encode with UTF-8 and ignore errors
334
+ encoded_description = task_description.encode("utf-8", errors="ignore")
335
+ task_hash = hashlib.md5(encoded_description).hexdigest()
336
+
337
+ logger.debug(f"Generated task hash: {task_hash}")
338
+ return task_hash
339
+ except Exception as e:
340
+ # Log any unexpected issues
341
+ logger.error(f"Error generating task hash: {e}", exc_info=True)
342
+ return 'output'
343
+
344
+ def save_to_google_storage(bucket_name, file_path, destination_blob_name, expiration_minutes = 1440):
345
+ credentials_dict = json.loads(google_credentials_json)
346
+
347
+ # Step 3: Use `service_account.Credentials.from_service_account_info` to authenticate directly with the JSON
348
+ credentials = service_account.Credentials.from_service_account_info(credentials_dict)
349
+ gcs_client = storage.Client(credentials=credentials, project=credentials.project_id)
350
+
351
+ # Check if the bucket exists; if not, create it
352
+ try:
353
+ bucket = gcs_client.get_bucket(bucket_name)
354
+ except NotFound:
355
+ print(f"❌ Bucket '{bucket_name}' not found. Please check the bucket name.")
356
+ bucket = gcs_client.create_bucket(bucket_name)
357
+ print(f"✅ Bucket '{bucket_name}' created.")
358
+ except Exception as e:
359
+ print(f"❌ An unexpected error occurred: {e}")
360
+ raise
361
+ # Get a reference to the blob
362
+ blob = bucket.blob(destination_blob_name)
363
+
364
+ # Upload the file
365
+ blob.upload_from_filename(file_path)
366
+
367
+ # Generate a signed URL for the file
368
+ signed_url = blob.generate_signed_url(
369
+ version="v4",
370
+ expiration=timedelta(minutes=expiration_minutes),
371
+ method="GET"
372
+ )
373
+ print(f"✅ File uploaded to Google Cloud Storage. Signed URL: {signed_url}")
374
+ return signed_url
375
+
376
+
377
+ # Function to check if content is Simplified Chinese
378
+ def is_simplified(text):
379
+ simplified_range = re.compile('[\u4e00-\u9fff]') # Han characters in general
380
+ simplified_characters = [char for char in text if simplified_range.match(char)]
381
+ return len(simplified_characters) > len(text) * 0.5 # Threshold of 50% to be considered simplified
382
+
383
+ # Function to choose the appropriate font for the content
384
+ def choose_font_for_content(content):
385
+ return 'NotoSansSC' if is_simplified(content) else 'NotoSansTC'
386
+
387
+ # Function to generate and save a document using ReportLab
388
+ def generate_document(task_description, md_content, user_name='jayw', bucket_name='curify'):
389
+ logger.debug("Starting to generate document")
390
+
391
+ # Hash the task description to generate a unique filename
392
+ task_hash = generate_task_hash(task_description)
393
+
394
+ # Truncate the hash if needed (64 characters is sufficient for uniqueness)
395
+ max_hash_length = 64 # Adjust if needed
396
+ truncated_hash = task_hash[:max_hash_length]
397
+
398
+ # Generate PDF file locally
399
+ local_filename = f"{truncated_hash}.pdf" # Use the truncated hash as the local file name
400
+ c = canvas.Canvas(local_filename, pagesize=letter)
401
+
402
+ # Paths to the TTF fonts for Simplified and Traditional Chinese
403
+ sc_font_path = 'NotoSansSC-Regular.ttf' # Path to Simplified Chinese font
404
+ tc_font_path = 'NotoSansTC-Regular.ttf' # Path to Traditional Chinese font
405
+
406
+ try:
407
+ # Register the Simplified Chinese font
408
+ sc_font = TTFont('NotoSansSC', sc_font_path)
409
+ pdfmetrics.registerFont(sc_font)
410
+
411
+ # Register the Traditional Chinese font
412
+ tc_font = TTFont('NotoSansTC', tc_font_path)
413
+ pdfmetrics.registerFont(tc_font)
414
+
415
+ # Set default font (Simplified Chinese or Traditional Chinese depending on content)
416
+ c.setFont('NotoSansSC', 12)
417
+ except Exception as e:
418
+ logger.error(f"Error loading font files: {e}")
419
+ raise RuntimeError("Failed to load one or more fonts. Ensure the font files are accessible.")
420
+
421
+ # Set initial Y position for drawing text
422
+ y_position = 750 # Starting position for text
423
+
424
+ # Process dictionary and render content
425
+ for key, value in md_content.items():
426
+ # Choose the font based on the key (header)
427
+ c.setFont(choose_font_for_content(key), 14)
428
+ c.drawString(100, y_position, f"# {key}")
429
+ y_position -= 20
430
+
431
+ # Choose the font for the value
432
+ c.setFont(choose_font_for_content(str(value)), 12)
433
+
434
+ # Add value
435
+ if isinstance(value, list): # Handle lists
436
+ for item in value:
437
+ c.drawString(100, y_position, f"- {item}")
438
+ y_position -= 15
439
+ else: # Handle single strings
440
+ c.drawString(100, y_position, value)
441
+ y_position -= 15
442
+
443
+ # Check if the page needs to be broken (if Y position is too low)
444
+ if y_position < 100:
445
+ c.showPage() # Create a new page
446
+ c.setFont('NotoSansSC', 12) # Reset font
447
+ y_position = 750 # Reset the Y position for the new page
448
+
449
+ # Save the PDF
450
+ c.save()
451
+
452
+ # Organize files into user-specific folders
453
+ destination_blob_name = f"{user_name}/{truncated_hash}.pdf"
454
+
455
+ # Upload to Google Cloud Storage and get the public URL
456
+ public_url = save_to_google_storage(bucket_name, local_filename, destination_blob_name)
457
+ logger.debug("Finished generating document")
458
+ return public_url
459
+
460
+ # In[10]:
461
+
462
+
463
+ def execute_with_retry(sql, params=(), attempts=5, delay=1, db_name = 'curify_ideas.db'):
464
+ for attempt in range(attempts):
465
+ try:
466
+ with sqlite3.connect(db_name) as conn:
467
+ cursor = conn.cursor()
468
+ cursor.execute(sql, params)
469
+ conn.commit()
470
+ break
471
+ except sqlite3.OperationalError as e:
472
+ if "database is locked" in str(e) and attempt < attempts - 1:
473
+ time.sleep(delay)
474
+ else:
475
+ raise e
476
+
477
+ # def enable_wal_mode(db_name = 'curify_ideas.db'):
478
+ # with sqlite3.connect(db_name) as conn:
479
+ # cursor = conn.cursor()
480
+ # cursor.execute("PRAGMA journal_mode=WAL;")
481
+ # conn.commit()
482
+
483
+ # # Create SQLite DB and table
484
+ # def create_db(db_name = 'curify_ideas.db'):
485
+ # with sqlite3.connect(db_name, timeout=30) as conn:
486
+ # c = conn.cursor()
487
+ # c.execute('''CREATE TABLE IF NOT EXISTS sessions (
488
+ # session_id TEXT,
489
+ # ip_address TEXT,
490
+ # project_desc TEXT,
491
+ # idea_desc TEXT,
492
+ # idea_analysis TEXT,
493
+ # prioritization_steps TEXT,
494
+ # timestamp DATETIME,
495
+ # PRIMARY KEY (session_id, timestamp)
496
+ # )
497
+ # ''')
498
+ # conn.commit()
499
+
500
+ # # Function to insert session data into the SQLite database
501
+ # def insert_session_data(session_id, ip_address, project_desc, idea_desc, idea_analysis, prioritization_steps, db_name = 'curify_ideas.db'):
502
+ # execute_with_retry('''
503
+ # INSERT INTO sessions (session_id, ip_address, project_desc, idea_desc, idea_analysis, prioritization_steps, timestamp)
504
+ # VALUES (?, ?, ?, ?, ?, ?, ?)
505
+ # ''', (session_id, ip_address, project_desc, idea_desc, json.dumps(idea_analysis), json.dumps(prioritization_steps), datetime.now()), db_name)
506
+
507
+
508
+ # In[11]:
509
+
510
+
511
+ def convert_to_listed_json(input_string):
512
+ """
513
+ Converts a string to a listed JSON object.
514
+
515
+ Parameters:
516
+ input_string (str): The JSON-like string to be converted.
517
+
518
+ Returns:
519
+ list: A JSON object parsed into a Python list of dictionaries.
520
+ """
521
+ try:
522
+ # Parse the string into a Python object
523
+ trimmed_string = input_string[input_string.index('['):input_string.rindex(']') + 1]
524
+
525
+ json_object = json.loads(trimmed_string)
526
+ return json_object
527
+ except json.JSONDecodeError as e:
528
+ return None
529
+ return None
530
+ #raise ValueError(f"Invalid JSON format: {e}")
531
+
532
+ def validate_and_extract_json(json_string):
533
+ """
534
+ Validates the JSON string, extracts fields with possible variants using fuzzy matching.
535
+
536
+ Args:
537
+ - json_string (str): The JSON string to validate and extract from.
538
+ - field_names (list): List of field names to extract, with possible variants.
539
+
540
+ Returns:
541
+ - dict: Extracted values with the best matched field names.
542
+ """
543
+ # Try to parse the JSON string
544
+ trimmed_string = json_string[json_string.index('{'):json_string.rindex('}') + 1]
545
+ try:
546
+ parsed_json = json.loads(trimmed_string)
547
+ return parsed_json
548
+ except json.JSONDecodeError as e:
549
+ return None
550
+
551
+ # {"error": "Parsed JSON is not a dictionary."}
552
+ return None
553
+
554
+ def json_to_pandas(dat_json, dat_schema = {'name':"", 'description':""}):
555
+ dat_df = pd.DataFrame([dat_schema])
556
+ try:
557
+ dat_df = pd.DataFrame(dat_json)
558
+
559
+ except Exception as e:
560
+ dat_df = pd.DataFrame([dat_schema])
561
+ # ValueError(f"Failed to parse LLM output as JSON: {e}\nOutput: {res}")
562
+ return dat_df
563
+
564
+
565
+ # In[12]:
566
+
567
+
568
+ client = OpenAI(
569
+ api_key= os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted
570
+ )
571
+
572
+ # Function to call OpenAI API with compact error handling
573
+ def call_openai_api(prompt, model="gpt-4o", max_tokens=5000, retries=3, backoff_factor=2):
574
+ """
575
+ Send a prompt to the OpenAI API and handle potential errors robustly.
576
+
577
+ Parameters:
578
+ prompt (str): The user input or task prompt to send to the model.
579
+ model (str): The OpenAI model to use (default is "gpt-4").
580
+ max_tokens (int): The maximum number of tokens in the response.
581
+ retries (int): Number of retry attempts in case of transient errors.
582
+ backoff_factor (int): Backoff time multiplier for retries.
583
+
584
+ Returns:
585
+ str: The model's response content if successful.
586
+ """
587
+ for attempt in range(1, retries + 1):
588
+ try:
589
+ response = client.chat.completions.create(
590
+ model="gpt-4o",
591
+ messages=[{"role": "user", "content": prompt}],
592
+ max_tokens=5000,
593
+ )
594
+ return response.choices[0].message.content.strip()
595
+
596
+ except (openai.RateLimitError, openai.APIConnectionError) as e:
597
+ logging.warning(f"Transient error: {e}. Attempt {attempt} of {retries}. Retrying...")
598
+ except (openai.BadRequestError, openai.AuthenticationError) as e:
599
+ logging.error(f"Unrecoverable error: {e}. Check your inputs or API key.")
600
+ break
601
+ except Exception as e:
602
+ logging.error(f"Unexpected error: {e}. Attempt {attempt} of {retries}. Retrying...")
603
+
604
+ # Exponential backoff before retrying
605
+ if attempt < retries:
606
+ time.sleep(backoff_factor * attempt)
607
+
608
+ raise RuntimeError(f"Failed to fetch response from OpenAI API after {retries} attempts.")
609
+
610
+ def fn_analyze_task(project_context, task_description):
611
+ prompt = (
612
+ f"You are working in the context of {project_context}. "
613
+ f"Your task is to analyze the task: {task_description} "
614
+ "Please analyze the following aspects: "
615
+ "1) Determine which project this item belongs to. If the idea does not belong to any existing project, categorize it under 'Other'. "
616
+ "2) Assess whether this idea can be treated as a concrete task. "
617
+ "3) Evaluate whether a document can be generated as an intermediate result. "
618
+ "4) Identify the appropriate category of the task. Possible categories are: 'Blogs/Papers', 'Tools', 'Brainstorming', 'Issues', and 'Others'. "
619
+ "5) Extract the topic of the task. "
620
+ "Please provide the output in JSON format using the structure below: "
621
+ "{"
622
+ " \"description\": \"\", "
623
+ " \"project_association\": \"\", "
624
+ " \"is_task\": \"Yes/No\", "
625
+ " \"is_document\": \"Yes/No\", "
626
+ " \"task_category\": \"\", "
627
+ " \"task_topic\": \"\" "
628
+ "}"
629
+ )
630
+ res_task_analysis = call_openai_api(prompt)
631
+
632
+ try:
633
+ json_task_analysis = validate_and_extract_json(res_task_analysis)
634
+
635
+ return json_task_analysis
636
+ except ValueError as e:
637
+ logger.debug("ValueError occurred: %s", str(e), exc_info=True) # Log the exception details
638
+ return None
639
+
640
+
641
+ # In[13]:
642
+
643
+ # Recursive Task Executor
644
+ def fn_process_task(project_desc_table, task_description, bucket_name='curify'):
645
+
646
+ project_context = project_desc_table.to_string(index=False)
647
+ task_analysis = fn_analyze_task(project_context, task_description)
648
+
649
+ if task_analysis:
650
+ execution_status = []
651
+ execution_results = task_analysis.copy()
652
+ execution_results['deliverables'] = ''
653
+
654
+ def traverse(node, previous_output=None):
655
+ if not node: # If the node is None or invalid
656
+ return # Exit if the node is invalid
657
+
658
+ # Check if there is a condition to evaluate
659
+ if "check" in node:
660
+ # Safely attempt to retrieve the value from execution_results
661
+ if node["check"] in execution_results:
662
+ value = execution_results[node["check"]] # Evaluate the check condition
663
+ traverse(node.get(value, node.get("default")), previous_output)
664
+ else:
665
+ # Log an error and exit, but keep partial results
666
+ logger.error(f"Key '{node['check']}' not found in execution_results.")
667
+ return
668
+
669
+ # If the node contains an action
670
+ elif "action" in node:
671
+ action_name = node["action"]
672
+ input_key = node.get("input", 'task_topic')
673
+
674
+ if input_key in execution_results.keys():
675
+ inputs = {input_key: execution_results[input_key]}
676
+ else:
677
+ # Log an error and exit, but keep partial results
678
+ logger.error(f"Workflow action {action_name} input key {input_key} not in execution_results.")
679
+ return
680
+
681
+ logger.debug(f"Executing: {action_name} with inputs: {inputs}")
682
+
683
+ # Execute the action function
684
+ action_func = action_map.get(action_name, unsupported_task)
685
+ try:
686
+ output = action_func(**inputs)
687
+ except Exception as e:
688
+ # Handle action function failure
689
+ logger.error(f"Error executing action '{action_name}': {e}")
690
+ return
691
+
692
+ # Store execution results or append to previous outputs
693
+ execution_status.append({"action": action_name, "output": output})
694
+
695
+ # Check if 'output' field exists in the node
696
+ if 'output' in node:
697
+ # If 'output' exists, assign the output to execution_results with the key from node['output']
698
+ execution_results[node['output']] = output
699
+ else:
700
+ # If 'output' does not exist, append the output to 'deliverables'
701
+ execution_results['deliverables'] += output
702
+
703
+ # Traverse to the next node, if it exists
704
+ if "next" in node and node["next"]:
705
+ traverse(node["next"], previous_output)
706
+
707
+ try:
708
+ traverse(TASK_WORKFLOW_TREE["start"])
709
+ execution_results['doc_url'] = generate_document(task_description, execution_results)
710
+ except Exception as e:
711
+ logger.error(f"Traverse Error: {e}")
712
+ finally:
713
+ # Always return partial results, even if an error occurs
714
+ return task_analysis, pd.DataFrame(execution_status), execution_results
715
+ else:
716
+ logger.error("Empty task analysis.")
717
+ return {}, pd.DataFrame(), {}
718
+
719
+ # In[14]:
720
+
721
+
722
+ # Initialize dataframes for the schema
723
+ ideas_df = pd.DataFrame(columns=["Idea ID", "Content", "Tags"])
724
+
725
+ def extract_ideas(context, text):
726
+ """
727
+ Extract project ideas from text, with or without a context, and return in JSON format.
728
+
729
+ Parameters:
730
+ context (str): Context of the extraction. Can be empty.
731
+ text (str): Text to extract ideas from.
732
+
733
+ Returns:
734
+ list: A list of ideas, each represented as a dictionary with name and description.
735
+ """
736
+ if context:
737
+ # Template when context is provided
738
+ prompt = (
739
+ f"You are working in the context of {context}. "
740
+ "Please extract the ongoing projects with project name and description."
741
+ "Please only the listed JSON as output string."
742
+ f"Ongoing projects: {text}"
743
+ )
744
+ else:
745
+ # Template when context is not provided
746
+ prompt = (
747
+ "Given the following information about the user."
748
+ "Please extract the ongoing projects with project name and description."
749
+ "Please only the listed JSON as output string."
750
+ f"Ongoing projects: {text}"
751
+ )
752
+
753
+ # return the raw string
754
+ return call_openai_api(prompt)
755
+
756
+ def df_to_string(df, empty_message = ''):
757
+ """
758
+ Converts a DataFrame to a string if it is not empty.
759
+ If the DataFrame is empty, returns an empty string.
760
+
761
+ Parameters:
762
+ ideas_df (pd.DataFrame): The DataFrame to be converted.
763
+
764
+ Returns:
765
+ str: A string representation of the DataFrame or an empty string.
766
+ """
767
+ if df.empty:
768
+ return empty_message
769
+ else:
770
+ return df.to_string(index=False)
771
+
772
+
773
+ # In[15]:
774
+
775
+
776
+ # Shared state variables
777
+ shared_state = {"project_desc_table": pd.DataFrame(), "task_analysis_txt": "", "execution_status": pd.DataFrame(), "execution_results": {}}
778
+
779
+ # Button Action: Fetch State
780
+ def fetch_updated_state():
781
+ response = requests.get("http://localhost:5000/state")
782
+ state = response.json()
783
+ """Fetch the updated shared state from FastAPI."""
784
+ return pd.DataFrame(state["project_desc_table"]), state["task_analysis_txt"], pd.DataFrame(state["execution_status"]), state["execution_results"]
785
+
786
+ def update_gradio_state(project_desc_table, task_analysis_txt, execution_status, execution_results):
787
+ # You can update specific components like Textbox or State
788
+ shared_state['project_desc_table'] = project_desc_table
789
+ shared_state['task_analysis_txt'] = task_analysis_txt
790
+ shared_state['execution_status'] = execution_status
791
+ shared_state['execution_results'] = execution_results
792
+ return True
793
+
794
+
795
+ # In[16]:
796
+
797
+
798
+ # # Initialize the database
799
+ # new_db = 'curify.db'
800
+
801
+ # # Copy the old database to a new one
802
+ # shutil.copy("curify_idea.db", new_db)
803
+
804
+ #create_db(new_db)
805
+ #enable_wal_mode(new_db)
806
+ def project_extraction(project_description):
807
+
808
+ str_projects = extract_ideas('AI-powered tools for productivity', project_description)
809
+ json_projects = convert_to_listed_json(str_projects)
810
+
811
+ project_desc_table = json_to_pandas(json_projects)
812
+ update_gradio_state(project_desc_table, "", pd.DataFrame(), {})
813
+ return project_desc_table
814
+
815
+
816
+ # In[17]:
817
+
818
+
819
+ # project_description = 'work on a number of projects including curify (digest, ideas, careers, projects etc), and writing a book on LLM for recommendation system, educating my 3.5-year-old boy and working on a paper for LLM reasoning.'
820
+
821
+ # # convert_to_listed_json(extract_ideas('AI-powered tools for productivity', project_description))
822
+
823
+ # task_description = 'Build an interview bot for the curify digest project.'
824
+ # task_analysis, reasoning_path = generate_reasoning_path(project_description, task_description)
825
+
826
+ # steps = store_and_execute_task(task_description, reasoning_path)
827
+
828
+ # def message_back(task_message, execution_status, doc_url, from_whatsapp):
829
+ # # Convert task steps to a simple numbered list
830
+ # task_steps_list = "\n".join(
831
+ # [f"{i + 1}. {step['action']} - {step.get('output', '')}" for i, step in enumerate(execution_status.to_dict(orient="records"))]
832
+ # )
833
+
834
+ # # Format the body message
835
+ # body_message = (
836
+ # f"*Task Message:*\n{task_message}\n\n"
837
+ # f"*Execution Status:*\n{task_steps_list}\n\n"
838
+ # f"*Doc URL:*\n{doc_url}\n\n"
839
+ # )
840
+
841
+ # # Send response back to WhatsApp
842
+ # try:
843
+ # twillo_client.messages.create(
844
+ # from_=twilio_phone_number,
845
+ # to=from_whatsapp,
846
+ # body=body_message
847
+ # )
848
+ # except Exception as e:
849
+ # logger.error(f"Twilio Error: {e}")
850
+ # raise HTTPException(status_code=500, detail=f"Error sending WhatsApp message: {str(e)}")
851
+
852
+ # return {"status": "success"}
853
+
854
+ # # Initialize the Whisper pipeline
855
+ # whisper_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-medium")
856
+
857
+ # # Function to transcribe audio from a media URL
858
+ # def transcribe_audio_from_media_url(media_url):
859
+ # try:
860
+ # media_response = requests.get(media_url, auth=HTTPBasicAuth(account_sid, auth_token))
861
+ # # Download the media file
862
+ # media_response.raise_for_status()
863
+ # audio_data = media_response.content
864
+
865
+ # # Save the audio data to a file for processing
866
+ # audio_file_path = "temp_audio_file.mp3"
867
+ # with open(audio_file_path, "wb") as audio_file:
868
+ # audio_file.write(audio_data)
869
+
870
+ # # Transcribe the audio using Whisper
871
+ # transcription = whisper_pipeline(audio_file_path, return_timestamps=True)
872
+ # logger.debug(f"Transcription: {transcription['text']}")
873
+ # return transcription["text"]
874
+
875
+ # except Exception as e:
876
+ # logger.error(f"An error occurred: {e}")
877
+ # return None
878
+
879
+
880
+ # In[18]:
881
+
882
 
883
  app = FastAPI()
884
 
885
+ # @app.get("/state")
886
+ # async def fetch_state():
887
+ # return shared_state
888
+
889
+ # @app.route("/whatsapp-webhook/", methods=["POST"])
890
+ # async def whatsapp_webhook(request: Request):
891
+ # form_data = await request.form()
892
+ # # Log the form data to debug
893
+ # print("Received data:", form_data)
894
+
895
+ # # Extract message and user information
896
+ # incoming_msg = form_data.get("Body", "").strip()
897
+ # from_number = form_data.get("From", "")
898
+ # media_url = form_data.get("MediaUrl0", "")
899
+ # media_type = form_data.get("MediaContentType0", "")
900
+
901
+ # # Initialize response variables
902
+ # transcription = None
903
+
904
+ # if media_type.startswith("audio"):
905
+ # # If the media is an audio or video file, process it
906
+ # try:
907
+ # transcription = transcribe_audio_from_media_url(media_url)
908
+ # except Exception as e:
909
+ # return JSONResponse(
910
+ # {"error": f"Failed to process voice input: {str(e)}"}, status_code=500
911
+ # )
912
+ # # Determine message content: use transcription if available, otherwise use text message
913
+ # processed_input = transcription if transcription else incoming_msg
914
+
915
+ # logger.debug(f"Processed input: {processed_input}")
916
+ # try:
917
+ # # Generate response
918
+ # project_desc_table, _ = fetch_updated_state()
919
+ # if not project_desc_table.empty:
920
+ # task_analysis_txt, execution_status, execution_results = fn_process_task(project_desc_table, processed_input)
921
+ # update_gradio_state(task_analysis_txt, execution_status, execution_results)
922
+
923
+ # doc_url = 'Fail to generate doc'
924
+ # if 'doc_url' in execution_results:
925
+ # doc_url = execution_results['doc_url']
926
+
927
+ # # Respond to the user on WhatsApp with the processed idea
928
+ # response = message_back(processed_input, execution_status, doc_url, from_number)
929
+ # logger.debug(response)
930
+
931
+ # return JSONResponse(content=str(response))
932
+ # except Exception as e:
933
+ # logger.error(f"Error during task processing: {e}")
934
+ # return {"error": str(e)}
935
+
936
+
937
+ # # In[19]:
938
+
939
+
940
+ # # Mock Gmail Login Function
941
+ # def mock_login(email):
942
+ # if email.endswith("@gmail.com"):
943
+ # return f"✅ Logged in as {email}", gr.update(visible=False), gr.update(visible=True)
944
+ # else:
945
+ # return "❌ Invalid Gmail address. Please try again.", gr.update(), gr.update()
946
+
947
+ # # User Onboarding Function
948
+ # def onboarding_survey(role, industry, project_description):
949
+ # return (project_extraction(project_description),
950
+ # gr.update(visible=False), gr.update(visible=True))
951
+
952
+ # # Mock Integration Functions
953
+ # def integrate_todoist():
954
+ # return "✅ Successfully connected to Todoist!"
955
+
956
+ # def integrate_evernote():
957
+ # return "✅ Successfully connected to Evernote!"
958
+
959
+ # def integrate_calendar():
960
+ # return "✅ Successfully connected to Google Calendar!"
961
+
962
+ # def load_svg_with_size(file_path, width="600px", height="400px"):
963
+ # # Read the SVG content from the file
964
+ # with open(file_path, "r", encoding="utf-8") as file:
965
+ # svg_content = file.read()
966
+
967
+ # # Add inline styles to control width and height
968
+ # styled_svg = f"""
969
+ # <div style="width: {width}; height: {height}; overflow: auto;">
970
+ # {svg_content}
971
+ # </div>
972
+ # """
973
+ # return styled_svg
974
+
975
+
976
+ # # In[20]:
977
+
978
+
979
+ # # Gradio Demo
980
+ # def create_gradio_interface(state=None):
981
+ # with gr.Blocks(
982
+ # css="""
983
+ # .gradio-table td {
984
+ # white-space: normal !important;
985
+ # word-wrap: break-word !important;
986
+ # }
987
+ # .gradio-table {
988
+ # width: 100% !important; /* Adjust to 100% to fit the container */
989
+ # table-layout: fixed !important; /* Fixed column widths */
990
+ # overflow-x: hidden !important; /* Disable horizontal scrolling */
991
+ # }
992
+ # .gradio-container {
993
+ # overflow-x: hidden !important; /* Disable horizontal scroll for entire container */
994
+ # padding: 0 !important; /* Remove any default padding */
995
+ # }
996
+ # .gradio-column {
997
+ # max-width: 100% !important; /* Ensure columns take up full width */
998
+ # overflow: hidden !important; /* Hide overflow to prevent horizontal scroll */
999
+ # }
1000
+ # .gradio-row {
1001
+ # overflow-x: hidden !important; /* Prevent horizontal scroll on rows */
1002
+ # }
1003
+ # """) as demo:
1004
+
1005
+ # # Page 1: Mock Gmail Login
1006
+ # with gr.Group(visible=True) as login_page:
1007
+ # gr.Markdown("### **1️⃣ Login with Gmail**")
1008
+ # email_input = gr.Textbox(label="Enter your Gmail Address", placeholder="[email protected]")
1009
+ # login_button = gr.Button("Login")
1010
+ # login_result = gr.Textbox(label="Login Status", interactive=False, visible=False)
1011
+ # # Page 2: User Onboarding
1012
+ # with gr.Group(visible=False) as onboarding_page:
1013
+ # gr.Markdown("### **2️⃣ Tell Us About Yourself**")
1014
+ # role = gr.Textbox(label="What is your role?", placeholder="e.g. Developer, Designer")
1015
+ # industry = gr.Textbox(label="Which industry are you in?", placeholder="e.g. Software, Finance")
1016
+ # project_description = gr.Textbox(label="Describe your project", placeholder="e.g. A task management app")
1017
+ # submit_survey = gr.Button("Submit")
1018
+
1019
+ # # Page 3: Mock Integrations with Separate Buttons
1020
+ # with gr.Group(visible=False) as integrations_page:
1021
+ # gr.Markdown("### **3️⃣ Connect Integrations**")
1022
+ # gr.Markdown("Click on the buttons below to connect each tool:")
1023
+
1024
+ # # Separate Buttons and Results for Each Integration
1025
+ # todoist_button = gr.Button("Connect to Todoist")
1026
+ # todoist_result = gr.Textbox(label="Todoist Status", interactive=False, visible=False)
1027
+
1028
+ # evernote_button = gr.Button("Connect to Evernote")
1029
+ # evernote_result = gr.Textbox(label="Evernote Status", interactive=False, visible=False)
1030
+
1031
+ # calendar_button = gr.Button("Connect to Google Calendar")
1032
+ # calendar_result = gr.Textbox(label="Google Calendar Status", interactive=False, visible=False)
1033
+
1034
+ # # Skip Button to proceed directly to next page
1035
+ # skip_integrations = gr.Button("Skip ➡️")
1036
+ # next_button = gr.Button("Proceed to QR Code")
1037
+
1038
+ # with gr.Group(visible=False) as qr_code_page:
1039
+ # # Page 4: QR Code and Curify Ideas
1040
+ # gr.Markdown("## Curify: Unified AI Tools for Productivity")
1041
+
1042
+ # with gr.Tab("Curify Idea"):
1043
+ # with gr.Row():
1044
+ # with gr.Column():
1045
+ # gr.Markdown("#### ** QR Code**")
1046
+ # # Path to your local SVG file
1047
+ # svg_file_path = "qr.svg"
1048
+ # # Load the SVG content
1049
+ # svg_content = load_svg_with_size(svg_file_path, width="200px", height="200px")
1050
+ # gr.HTML(svg_content)
1051
+
1052
+ # # Column 1: Webpage rendering
1053
+ # with gr.Column():
1054
+
1055
+ # gr.Markdown("## Projects Overview")
1056
+ # project_desc_table = gr.DataFrame(
1057
+ # type="pandas"
1058
+ # )
1059
+
1060
+ # gr.Markdown("## Enter task message.")
1061
+ # idea_input = gr.Textbox(
1062
+ # label=None,
1063
+ # placeholder="Describe the task you want to execute (e.g., Research Paper Review)")
1064
+
1065
+ # task_btn = gr.Button("Generate Task Steps")
1066
+ # fetch_state_btn = gr.Button("Fetch Updated State")
1067
+
1068
+ # with gr.Column():
1069
+ # gr.Markdown("## Task analysis")
1070
+ # task_analysis_txt = gr.Textbox(
1071
+ # label=None,
1072
+ # placeholder="Here is the execution status of your task...")
1073
+
1074
+ # gr.Markdown("## Execution status")
1075
+ # execution_status = gr.DataFrame(
1076
+ # type="pandas"
1077
+ # )
1078
+ # gr.Markdown("## Execution output")
1079
+ # execution_results = gr.JSON(
1080
+ # label=None
1081
+ # )
1082
+ # state_output = gr.State() # Add a state output to hold the state
1083
+
1084
+ # task_btn.click(
1085
+ # fn_process_task,
1086
+ # inputs=[project_desc_table, idea_input],
1087
+ # outputs=[task_analysis_txt, execution_status, execution_results]
1088
+ # )
1089
+
1090
+ # fetch_state_btn.click(
1091
+ # fetch_updated_state,
1092
+ # inputs=None,
1093
+ # outputs=[project_desc_table, task_analysis_txt, execution_status, execution_results]
1094
+ # )
1095
+
1096
+ # # Page 1 -> Page 2 Transition
1097
+ # login_button.click(
1098
+ # mock_login,
1099
+ # inputs=email_input,
1100
+ # outputs=[login_result, login_page, onboarding_page]
1101
+ # )
1102
+
1103
+ # # Page 2 -> Page 3 Transition (Submit and Skip)
1104
+ # submit_survey.click(
1105
+ # onboarding_survey,
1106
+ # inputs=[role, industry, project_description],
1107
+ # outputs=[project_desc_table, onboarding_page, integrations_page]
1108
+ # )
1109
+
1110
+ # # Integration Buttons
1111
+ # todoist_button.click(integrate_todoist, outputs=todoist_result)
1112
+ # evernote_button.click(integrate_evernote, outputs=evernote_result)
1113
+ # calendar_button.click(integrate_calendar, outputs=calendar_result)
1114
+
1115
+ # # Skip Integrations and Proceed
1116
+ # skip_integrations.click(
1117
+ # lambda: (gr.update(visible=False), gr.update(visible=True)),
1118
+ # outputs=[integrations_page, qr_code_page]
1119
+ # )
1120
+
1121
+ # # # Set the load_fn to initialize the state when the page is loaded
1122
+ # # demo.load(
1123
+ # # curify_ideas,
1124
+ # # inputs=[project_input, idea_input],
1125
+ # # outputs=[task_steps, task_analysis_txt, state_output]
1126
+ # # )
1127
+ # return demo
1128
+ # # Load function to initialize the state
1129
+ # # demo.load(load_fn, inputs=None, outputs=[state]) # Initialize the state when the page is loaded
1130
+
1131
+ @app.on_event("startup")
1132
+ async def startup_event():
1133
+ logger.debug("Application startup initiated")
1134
+ # Simulate heavy operation
1135
+ # from transformers import pipeline
1136
+ # global model
1137
+ # model = pipeline("automatic-speech-recognition", model="openai/whisper-medium")
1138
+ logger.debug("Application startup complete")
1139
+
1140
+ # In[21]:
1141
+ @app.get("/", response_class=JSONResponse)
1142
  async def index():
1143
+ return {"status": "FastAPI is running!"}
1144
+
1145
+ # demo = create_gradio_interface()
1146
+ # # Use Gradio's `server_app` to get an ASGI app for Blocks
1147
+ # gradio_asgi_app = gr.routes.App.create_app(demo)
1148
+
1149
+ # # Mount the Gradio ASGI app at "/gradio"
1150
+ # app.mount("/gradio", gradio_asgi_app)
1151
+
1152
+ # # Redirect from the root endpoint to the Gradio app
1153
+ # @app.get("/", response_class=RedirectResponse)
1154
+ # async def index():
1155
+ # return RedirectResponse(url="/gradio", status_code=307)
1156
 
1157
+ # Run the FastAPI server using uvicorn
1158
  if __name__ == "__main__":
1159
  port = int(os.getenv("PORT", 7860)) # Default to 7860 if PORT is not set
1160
  uvicorn.run(app, host="0.0.0.0", port=port)