qqwjq1981 commited on
Commit
1fde903
·
verified ·
1 Parent(s): 6c19f60

Update app.py

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