qqwjq1981 commited on
Commit
6e3e237
·
verified ·
1 Parent(s): f8ebc27

Update app.py

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