Update app.py
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ from report_generator import (
|
|
| 11 |
import cohere
|
| 12 |
|
| 13 |
# Initialize the Cohere client using your provided API key.
|
|
|
|
| 14 |
COHERE_API_KEY = "ffwtfyfLwqSOtw65psZardfqhUxMr1h7u5vzYotI"
|
| 15 |
co = cohere.Client(COHERE_API_KEY)
|
| 16 |
|
|
@@ -30,6 +31,7 @@ def cohere_parse_command(command):
|
|
| 30 |
inputs=[command],
|
| 31 |
examples=cohere_examples
|
| 32 |
)
|
|
|
|
| 33 |
prediction = response.classifications[0].prediction
|
| 34 |
return prediction
|
| 35 |
except Exception as e:
|
|
@@ -43,19 +45,22 @@ def cohere_parse_command(command):
|
|
| 43 |
return "unknown"
|
| 44 |
|
| 45 |
# Global containers for pending tasks and generated files.
|
| 46 |
-
task_bucket = [] # Queue
|
| 47 |
-
generated_files = [] # List of filenames generated.
|
| 48 |
bucket_lock = threading.Lock()
|
| 49 |
|
| 50 |
def process_single_task(task):
|
| 51 |
-
"""Process
|
| 52 |
print(f"[{datetime.now()}] Processing task: {task['command']}")
|
|
|
|
| 53 |
for remaining in range(5, 0, -1):
|
| 54 |
task["timer"] = remaining
|
| 55 |
time.sleep(1)
|
|
|
|
| 56 |
intent = cohere_parse_command(task["command"])
|
| 57 |
cmd = task["command"].lower()
|
| 58 |
|
|
|
|
| 59 |
if intent == "report":
|
| 60 |
if "csv" in cmd:
|
| 61 |
filename = generate_csv_report()
|
|
@@ -64,6 +69,7 @@ def process_single_task(task):
|
|
| 64 |
filename = generate_xlsx_report()
|
| 65 |
task["result"] = f"XLSX report generated for '{task['command']}'"
|
| 66 |
else:
|
|
|
|
| 67 |
filename = generate_pdf_report(subject=task["command"])
|
| 68 |
task["result"] = f"PDF report generated for '{task['command']}'"
|
| 69 |
elif intent == "diagram":
|
|
@@ -81,9 +87,9 @@ def process_single_task(task):
|
|
| 81 |
print(f"[{datetime.now()}] Task completed: {task}")
|
| 82 |
|
| 83 |
def background_task_processor():
|
| 84 |
-
"""Continuously
|
| 85 |
while True:
|
| 86 |
-
time.sleep(1)
|
| 87 |
task = None
|
| 88 |
with bucket_lock:
|
| 89 |
if task_bucket:
|
|
@@ -93,7 +99,10 @@ def background_task_processor():
|
|
| 93 |
threading.Thread(target=process_single_task, args=(task,), daemon=True).start()
|
| 94 |
|
| 95 |
def submit_task(command, current_tasks):
|
| 96 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 97 |
if command.strip() == "":
|
| 98 |
return current_tasks, generated_files, command
|
| 99 |
new_task = {
|
|
@@ -109,19 +118,18 @@ def submit_task(command, current_tasks):
|
|
| 109 |
with bucket_lock:
|
| 110 |
task_bucket.append(new_task)
|
| 111 |
current_tasks.append(new_task)
|
| 112 |
-
return current_tasks, generated_files, command
|
| 113 |
|
| 114 |
def build_tasks_html(tasks):
|
| 115 |
-
"""
|
| 116 |
html = """
|
| 117 |
<style>
|
| 118 |
-
table {width: 100%; border-collapse: collapse; margin:
|
| 119 |
-
th, td {border: 1px solid #
|
| 120 |
-
th {background-color: #
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
input[type=checkbox] {width: 18px; height: 18px; transform: scale(1.2);}
|
| 125 |
</style>
|
| 126 |
<table>
|
| 127 |
<tr>
|
|
@@ -141,7 +149,7 @@ def build_tasks_html(tasks):
|
|
| 141 |
result = task.get("result", "")
|
| 142 |
completed_at = task.get("completed_at", "")
|
| 143 |
details = task.get("details", "")
|
| 144 |
-
checkbox = "<input type='checkbox' disabled " + ("checked" if status=="Complete" else "") + ">"
|
| 145 |
html += (
|
| 146 |
f"<tr class='{status}'>"
|
| 147 |
f"<td>{task.get('submitted_at','')}</td>"
|
|
@@ -158,80 +166,73 @@ def build_tasks_html(tasks):
|
|
| 158 |
return html
|
| 159 |
|
| 160 |
def refresh_ui(tasks, files):
|
| 161 |
-
"""
|
| 162 |
tasks_html = build_tasks_html(tasks)
|
| 163 |
return tasks, files, tasks_html
|
| 164 |
|
| 165 |
def main():
|
| 166 |
-
# Start background task
|
| 167 |
threading.Thread(target=background_task_processor, daemon=True).start()
|
| 168 |
|
| 169 |
-
with gr.Blocks(
|
| 170 |
-
|
| 171 |
-
.gradio-container {max-width: 900px; margin: auto; padding: 20px; background-color: #1e1e1e; border-radius: 8px; box-shadow: 0px 0px 15px rgba(0,0,0,0.5);}
|
| 172 |
-
.title {text-align: center; color: #fdfdfd; margin-bottom: 20px;}
|
| 173 |
-
.section-title {color: #fdfdfd; margin-top: 30px; border-bottom: 2px solid #fdfdfd; padding-bottom: 5px;}
|
| 174 |
-
""") as demo:
|
| 175 |
-
gr.Markdown("<h1 class='title'>Advanced Multi-Task Application</h1>")
|
| 176 |
gr.Markdown(
|
| 177 |
-
"Enter
|
| 178 |
-
"
|
|
|
|
|
|
|
| 179 |
)
|
| 180 |
|
| 181 |
with gr.Row():
|
| 182 |
with gr.Column(scale=8):
|
| 183 |
-
command_input = gr.Textbox(label="Task Command", placeholder="Type your command here..."
|
| 184 |
with gr.Column(scale=2):
|
| 185 |
-
submit_btn = gr.Button("Submit"
|
| 186 |
|
| 187 |
-
gr.Markdown("
|
| 188 |
with gr.Row():
|
| 189 |
sample1 = gr.Button("Report on US Unemployment 2024")
|
| 190 |
sample2 = gr.Button("Diagram of Sales Data")
|
| 191 |
sample3 = gr.Button("CSV Report of User Activity")
|
| 192 |
|
| 193 |
-
gr.Markdown("
|
| 194 |
tasks_html_output = gr.HTML(label="Tasks Overview")
|
| 195 |
|
| 196 |
-
gr.Markdown("
|
| 197 |
-
file_output = gr.Files(label="
|
| 198 |
-
|
| 199 |
-
with gr.Row():
|
| 200 |
-
refresh_btn = gr.Button("Manual Refresh")
|
| 201 |
-
auto_refresh_toggle = gr.Checkbox(value=True, label="Auto Refresh Task List")
|
| 202 |
|
|
|
|
| 203 |
tasks_state = gr.State([])
|
| 204 |
files_state = gr.State([])
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
submit_btn.click(
|
| 207 |
submit_task,
|
| 208 |
inputs=[command_input, tasks_state],
|
| 209 |
outputs=[tasks_state, files_state, command_input]
|
| 210 |
)
|
|
|
|
| 211 |
sample1.click(lambda: "generate a report on unemployment in the United States in 2024", None, command_input)
|
| 212 |
sample2.click(lambda: "generate diagram of sales data", None, command_input)
|
| 213 |
sample3.click(lambda: "generate csv report of user activity", None, command_input)
|
|
|
|
| 214 |
refresh_btn.click(
|
| 215 |
refresh_ui,
|
| 216 |
inputs=[tasks_state, files_state],
|
| 217 |
outputs=[tasks_state, files_state, tasks_html_output]
|
| 218 |
)
|
|
|
|
| 219 |
auto_refresh_btn = gr.Button("Auto Refresh", visible=False, elem_id="auto_refresh_btn")
|
| 220 |
auto_refresh_btn.click(
|
| 221 |
refresh_ui,
|
| 222 |
inputs=[tasks_state, files_state],
|
| 223 |
outputs=[tasks_state, files_state, tasks_html_output]
|
| 224 |
)
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
setInterval(function(){
|
| 228 |
-
if(document.getElementById('auto_refresh_toggle').checked){
|
| 229 |
-
document.getElementById('auto_refresh_btn').click();
|
| 230 |
-
}
|
| 231 |
-
}, 5000);
|
| 232 |
-
</script>
|
| 233 |
-
""")
|
| 234 |
-
auto_refresh_toggle.elem_id = "auto_refresh_toggle"
|
| 235 |
|
| 236 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 237 |
|
|
|
|
| 11 |
import cohere
|
| 12 |
|
| 13 |
# Initialize the Cohere client using your provided API key.
|
| 14 |
+
# (For production, load the API key from a secure environment variable.)
|
| 15 |
COHERE_API_KEY = "ffwtfyfLwqSOtw65psZardfqhUxMr1h7u5vzYotI"
|
| 16 |
co = cohere.Client(COHERE_API_KEY)
|
| 17 |
|
|
|
|
| 31 |
inputs=[command],
|
| 32 |
examples=cohere_examples
|
| 33 |
)
|
| 34 |
+
# Get the prediction for the first input.
|
| 35 |
prediction = response.classifications[0].prediction
|
| 36 |
return prediction
|
| 37 |
except Exception as e:
|
|
|
|
| 45 |
return "unknown"
|
| 46 |
|
| 47 |
# Global containers for pending tasks and generated files.
|
| 48 |
+
task_bucket = [] # Queue of tasks waiting to be processed.
|
| 49 |
+
generated_files = [] # List of filenames for files generated by completed tasks.
|
| 50 |
bucket_lock = threading.Lock()
|
| 51 |
|
| 52 |
def process_single_task(task):
|
| 53 |
+
"""Process one task with a countdown timer and update its details."""
|
| 54 |
print(f"[{datetime.now()}] Processing task: {task['command']}")
|
| 55 |
+
# Simulate processing delay with a countdown.
|
| 56 |
for remaining in range(5, 0, -1):
|
| 57 |
task["timer"] = remaining
|
| 58 |
time.sleep(1)
|
| 59 |
+
# Use Cohere (or fallback) to classify the intent.
|
| 60 |
intent = cohere_parse_command(task["command"])
|
| 61 |
cmd = task["command"].lower()
|
| 62 |
|
| 63 |
+
# Process based on the detected intent.
|
| 64 |
if intent == "report":
|
| 65 |
if "csv" in cmd:
|
| 66 |
filename = generate_csv_report()
|
|
|
|
| 69 |
filename = generate_xlsx_report()
|
| 70 |
task["result"] = f"XLSX report generated for '{task['command']}'"
|
| 71 |
else:
|
| 72 |
+
# Default to PDF (with subject included)
|
| 73 |
filename = generate_pdf_report(subject=task["command"])
|
| 74 |
task["result"] = f"PDF report generated for '{task['command']}'"
|
| 75 |
elif intent == "diagram":
|
|
|
|
| 87 |
print(f"[{datetime.now()}] Task completed: {task}")
|
| 88 |
|
| 89 |
def background_task_processor():
|
| 90 |
+
"""Continuously monitors the task bucket and spawns a new thread per task."""
|
| 91 |
while True:
|
| 92 |
+
time.sleep(1) # Poll every second.
|
| 93 |
task = None
|
| 94 |
with bucket_lock:
|
| 95 |
if task_bucket:
|
|
|
|
| 99 |
threading.Thread(target=process_single_task, args=(task,), daemon=True).start()
|
| 100 |
|
| 101 |
def submit_task(command, current_tasks):
|
| 102 |
+
"""
|
| 103 |
+
Called when the user clicks Submit.
|
| 104 |
+
Adds a new task (without clearing the textbox) so you can review it.
|
| 105 |
+
"""
|
| 106 |
if command.strip() == "":
|
| 107 |
return current_tasks, generated_files, command
|
| 108 |
new_task = {
|
|
|
|
| 118 |
with bucket_lock:
|
| 119 |
task_bucket.append(new_task)
|
| 120 |
current_tasks.append(new_task)
|
| 121 |
+
return current_tasks, generated_files, command # Keep command in textbox.
|
| 122 |
|
| 123 |
def build_tasks_html(tasks):
|
| 124 |
+
"""Build an HTML table showing task details with checkboxes for completed tasks."""
|
| 125 |
html = """
|
| 126 |
<style>
|
| 127 |
+
table {width: 100%; border-collapse: collapse; margin: 10px 0; font-family: Arial, sans-serif;}
|
| 128 |
+
th, td {border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 14px;}
|
| 129 |
+
th {background-color: #f2f2f2;}
|
| 130 |
+
.Complete {background-color: #d4edda;}
|
| 131 |
+
.In\\ Progress {background-color: #fff3cd;}
|
| 132 |
+
.Pending {background-color: #f8d7da;}
|
|
|
|
| 133 |
</style>
|
| 134 |
<table>
|
| 135 |
<tr>
|
|
|
|
| 149 |
result = task.get("result", "")
|
| 150 |
completed_at = task.get("completed_at", "")
|
| 151 |
details = task.get("details", "")
|
| 152 |
+
checkbox = "<input type='checkbox' disabled " + ("checked" if status == "Complete" else "") + ">"
|
| 153 |
html += (
|
| 154 |
f"<tr class='{status}'>"
|
| 155 |
f"<td>{task.get('submitted_at','')}</td>"
|
|
|
|
| 166 |
return html
|
| 167 |
|
| 168 |
def refresh_ui(tasks, files):
|
| 169 |
+
"""Refresh the UI by rebuilding the HTML task list."""
|
| 170 |
tasks_html = build_tasks_html(tasks)
|
| 171 |
return tasks, files, tasks_html
|
| 172 |
|
| 173 |
def main():
|
| 174 |
+
# Start the background task processor.
|
| 175 |
threading.Thread(target=background_task_processor, daemon=True).start()
|
| 176 |
|
| 177 |
+
with gr.Blocks() as demo:
|
| 178 |
+
gr.Markdown("# Advanced Multi-Task Report & Diagram Generator")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
gr.Markdown(
|
| 180 |
+
"Enter your task command below or click one of the sample commands. For example:<br>"
|
| 181 |
+
"<i>generate a report on unemployment in the United States in 2024</i><br>"
|
| 182 |
+
"The system automatically detects your intent and generates a PDF report (unless another format is specified).<br>"
|
| 183 |
+
"Multiple tasks run concurrently and you can watch their live progress below."
|
| 184 |
)
|
| 185 |
|
| 186 |
with gr.Row():
|
| 187 |
with gr.Column(scale=8):
|
| 188 |
+
command_input = gr.Textbox(label="Enter Task Command", placeholder="Type your command here...")
|
| 189 |
with gr.Column(scale=2):
|
| 190 |
+
submit_btn = gr.Button("Submit")
|
| 191 |
|
| 192 |
+
gr.Markdown("#### Sample Commands")
|
| 193 |
with gr.Row():
|
| 194 |
sample1 = gr.Button("Report on US Unemployment 2024")
|
| 195 |
sample2 = gr.Button("Diagram of Sales Data")
|
| 196 |
sample3 = gr.Button("CSV Report of User Activity")
|
| 197 |
|
| 198 |
+
gr.Markdown("### Task List")
|
| 199 |
tasks_html_output = gr.HTML(label="Tasks Overview")
|
| 200 |
|
| 201 |
+
gr.Markdown("### Download Generated Files")
|
| 202 |
+
file_output = gr.Files(label="Generated Files", file_count="multiple")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
# Hidden states.
|
| 205 |
tasks_state = gr.State([])
|
| 206 |
files_state = gr.State([])
|
| 207 |
|
| 208 |
+
with gr.Row():
|
| 209 |
+
refresh_btn = gr.Button("Refresh Task List")
|
| 210 |
+
|
| 211 |
+
# When Submit is clicked, add a task.
|
| 212 |
submit_btn.click(
|
| 213 |
submit_task,
|
| 214 |
inputs=[command_input, tasks_state],
|
| 215 |
outputs=[tasks_state, files_state, command_input]
|
| 216 |
)
|
| 217 |
+
# Sample buttons populate the command textbox.
|
| 218 |
sample1.click(lambda: "generate a report on unemployment in the United States in 2024", None, command_input)
|
| 219 |
sample2.click(lambda: "generate diagram of sales data", None, command_input)
|
| 220 |
sample3.click(lambda: "generate csv report of user activity", None, command_input)
|
| 221 |
+
# Manual refresh button.
|
| 222 |
refresh_btn.click(
|
| 223 |
refresh_ui,
|
| 224 |
inputs=[tasks_state, files_state],
|
| 225 |
outputs=[tasks_state, files_state, tasks_html_output]
|
| 226 |
)
|
| 227 |
+
# Create a hidden auto-refresh button with a fixed element ID.
|
| 228 |
auto_refresh_btn = gr.Button("Auto Refresh", visible=False, elem_id="auto_refresh_btn")
|
| 229 |
auto_refresh_btn.click(
|
| 230 |
refresh_ui,
|
| 231 |
inputs=[tasks_state, files_state],
|
| 232 |
outputs=[tasks_state, files_state, tasks_html_output]
|
| 233 |
)
|
| 234 |
+
# JavaScript to click the hidden auto-refresh button every 5 seconds.
|
| 235 |
+
gr.HTML("<script>setInterval(function(){document.getElementById('auto_refresh_btn').click();}, 5000);</script>")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 238 |
|