Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import glob
|
|
| 4 |
import re
|
| 5 |
import pandas as pd
|
| 6 |
import gradio as gr
|
| 7 |
-
import spaces
|
| 8 |
from pypdf import PdfReader
|
| 9 |
import docx2txt
|
| 10 |
import speech_recognition as sr
|
|
@@ -22,7 +22,7 @@ os.makedirs(PROCESSED_DIR, exist_ok=True)
|
|
| 22 |
# -------------------------------------------------------------
|
| 23 |
# CORE PIPELINE LOGIC (TRANSCRIBER, PARSER, CHUNKER)
|
| 24 |
# -------------------------------------------------------------
|
| 25 |
-
@spaces.GPU
|
| 26 |
def transcribe_video_audio(file_path):
|
| 27 |
try:
|
| 28 |
gr.Info(f"๐ฌ Extracting track layers from {os.path.basename(file_path)}...")
|
|
@@ -50,9 +50,56 @@ def clean_text_formatting(text):
|
|
| 50 |
text = text.replace(" ", " ")
|
| 51 |
return text.strip()
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
def parse_incoming_file_to_text(file_path):
|
| 54 |
ext = os.path.splitext(file_path)[1].lower()
|
|
|
|
| 55 |
text = ""
|
|
|
|
| 56 |
if ext == ".txt":
|
| 57 |
with open(file_path, "r", encoding="utf-8") as f:
|
| 58 |
text = f.read()
|
|
@@ -64,8 +111,9 @@ def parse_incoming_file_to_text(file_path):
|
|
| 64 |
elif ext == ".docx":
|
| 65 |
text = docx2txt.process(file_path)
|
| 66 |
elif ext in [".csv", ".xlsx"]:
|
|
|
|
| 67 |
df = pd.read_csv(file_path) if ext == ".csv" else pd.read_excel(file_path)
|
| 68 |
-
text =
|
| 69 |
elif ext in [".mp4", ".wav", ".mp3"]:
|
| 70 |
text = transcribe_video_audio(file_path)
|
| 71 |
|
|
@@ -88,10 +136,10 @@ def structure_unsloth_rows(chunks, archetype):
|
|
| 88 |
elif "๐งฎ Math Wizard" in archetype or "๐ Day Trading" in archetype:
|
| 89 |
instr = "Deconstruct structural math patterns or trading indicator calculations."
|
| 90 |
if "๐ Day Trading" in archetype:
|
| 91 |
-
instr = "
|
| 92 |
rows.append({
|
| 93 |
"instruction": instr,
|
| 94 |
-
"input": f"
|
| 95 |
"output": chunk
|
| 96 |
})
|
| 97 |
elif "๐ป Code Assistant" in archetype:
|
|
@@ -104,10 +152,10 @@ def structure_unsloth_rows(chunks, archetype):
|
|
| 104 |
rows.append({"text": chunk})
|
| 105 |
return rows
|
| 106 |
|
| 107 |
-
@spaces.GPU
|
| 108 |
def execute_dataset_builder_pipeline(files, archetype, enable_chunking, chunk_size, chunk_overlap):
|
| 109 |
if not files:
|
| 110 |
-
return "โ ๏ธ Target file loading queue is empty. Please upload files."
|
| 111 |
|
| 112 |
for f in glob.glob(os.path.join(PROCESSED_DIR, "*.jsonl")):
|
| 113 |
os.remove(f)
|
|
@@ -122,7 +170,7 @@ def execute_dataset_builder_pipeline(files, archetype, enable_chunking, chunk_si
|
|
| 122 |
total_files_compiled += 1
|
| 123 |
|
| 124 |
if not all_extracted_text_blocks:
|
| 125 |
-
return "โ Failed to extract content from assets."
|
| 126 |
|
| 127 |
combined_master_string = "\n\n--- FILE SPLIT ---\n\n".join(all_extracted_text_blocks)
|
| 128 |
|
|
@@ -138,7 +186,9 @@ def execute_dataset_builder_pipeline(files, archetype, enable_chunking, chunk_si
|
|
| 138 |
for obj in formatted_dataset_objects:
|
| 139 |
master_f.write(json.dumps(obj) + "\n")
|
| 140 |
|
| 141 |
-
|
|
|
|
|
|
|
| 142 |
|
| 143 |
# -------------------------------------------------------------
|
| 144 |
# THEME TOGGLE SWITCH LOGIC โ๏ธ/๐
|
|
@@ -175,7 +225,6 @@ custom_theme = gr.themes.Default(
|
|
| 175 |
neutral_hue="zinc"
|
| 176 |
)
|
| 177 |
|
| 178 |
-
# Removed theme and title parameters from constructor to prevent Gradio 6 layout deprecation warnings
|
| 179 |
with gr.Blocks() as demo:
|
| 180 |
ui_theme_state = gr.State("dark")
|
| 181 |
|
|
@@ -187,7 +236,7 @@ with gr.Blocks() as demo:
|
|
| 187 |
|
| 188 |
with gr.Row():
|
| 189 |
with gr.Column(scale=1):
|
| 190 |
-
file_uploader = gr.File(file_count="multiple", label="๐ฅ Drop Assets Here (.pdf, .txt, .docx, .mp4)")
|
| 191 |
archetype_dropdown = gr.Dropdown(choices=archetype_choices, value=archetype_choices[0], label="๐ค Choose Target AI Archetype Layout Mapping")
|
| 192 |
|
| 193 |
with gr.Accordion("โ๏ธ Text Chunking Control Panel", open=True):
|
|
@@ -198,12 +247,13 @@ with gr.Blocks() as demo:
|
|
| 198 |
run_btn = gr.Button("๐ Run Conversion & Combine Files", variant="primary")
|
| 199 |
|
| 200 |
with gr.Column(scale=1):
|
| 201 |
-
log_monitor = gr.Textbox(label="๐ฅ๏ธ Core Engine Pipeline Logs", lines=
|
|
|
|
| 202 |
|
| 203 |
run_btn.click(
|
| 204 |
fn=execute_dataset_builder_pipeline,
|
| 205 |
inputs=[file_uploader, archetype_dropdown, chunk_toggle, size_input, overlap_input],
|
| 206 |
-
outputs=log_monitor
|
| 207 |
)
|
| 208 |
|
| 209 |
theme_toggle_btn.click(
|
|
@@ -219,5 +269,4 @@ with gr.Blocks() as demo:
|
|
| 219 |
demo.load(fn=lambda: "dark", outputs=ui_theme_state).then(fn=None, inputs=[ui_theme_state], js=js_theme_switcher)
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
-
# Theme configuration parameters passed to launch method matching Gradio 6 guidelines
|
| 223 |
demo.launch(theme=custom_theme)
|
|
|
|
| 4 |
import re
|
| 5 |
import pandas as pd
|
| 6 |
import gradio as gr
|
| 7 |
+
import spaces
|
| 8 |
from pypdf import PdfReader
|
| 9 |
import docx2txt
|
| 10 |
import speech_recognition as sr
|
|
|
|
| 22 |
# -------------------------------------------------------------
|
| 23 |
# CORE PIPELINE LOGIC (TRANSCRIBER, PARSER, CHUNKER)
|
| 24 |
# -------------------------------------------------------------
|
| 25 |
+
@spaces.GPU
|
| 26 |
def transcribe_video_audio(file_path):
|
| 27 |
try:
|
| 28 |
gr.Info(f"๐ฌ Extracting track layers from {os.path.basename(file_path)}...")
|
|
|
|
| 50 |
text = text.replace(" ", " ")
|
| 51 |
return text.strip()
|
| 52 |
|
| 53 |
+
# ๐ฅ NEW: ADVANCED FINANCIAL CSV PARSER & TIMESTAMP INJECTOR ๐ฅ
|
| 54 |
+
def process_financial_csv(df, file_name=""):
|
| 55 |
+
"""Detects financial data, sorts chronologically, auto-injects missing timestamps, and translates to NLP sentences."""
|
| 56 |
+
|
| 57 |
+
# 1. Detect and establish the time column
|
| 58 |
+
time_col = None
|
| 59 |
+
for col in df.columns:
|
| 60 |
+
if str(col).lower() in ['date', 'time', 'timestamp', 'datetime', 'timeframe']:
|
| 61 |
+
time_col = col
|
| 62 |
+
break
|
| 63 |
+
|
| 64 |
+
if time_col:
|
| 65 |
+
# Sort existing timestamps chronologically
|
| 66 |
+
df[time_col] = pd.to_datetime(df[time_col], errors='coerce')
|
| 67 |
+
df = df.dropna(subset=[time_col]).sort_values(by=time_col)
|
| 68 |
+
else:
|
| 69 |
+
# Auto-Inject missing timestamps to establish sequence logic
|
| 70 |
+
gr.Info(f"โฑ๏ธ No timestamp found in {file_name}. Auto-generating chronological sequence...")
|
| 71 |
+
# (Note: The 1-minute timeframe interval is used here purely as a default structural baseline)
|
| 72 |
+
df['Generated_Timestamp'] = pd.date_range(start=pd.Timestamp.now().floor('D'), periods=len(df), freq='1min')
|
| 73 |
+
time_col = 'Generated_Timestamp'
|
| 74 |
+
|
| 75 |
+
# 2. Detect if the file is financial/quantitative data
|
| 76 |
+
is_financial = any(str(c).lower() in ['open', 'close', 'high', 'low', 'volume', 'vwap', 'rvol'] for c in df.columns)
|
| 77 |
+
|
| 78 |
+
text_output = []
|
| 79 |
+
|
| 80 |
+
if is_financial:
|
| 81 |
+
gr.Info(f"๐น Financial dataset detected ({file_name}). Translating rows into optimized LLM sentences...")
|
| 82 |
+
for _, row in df.iterrows():
|
| 83 |
+
row_time = row[time_col]
|
| 84 |
+
# Strip the time column out of the details list so it isn't repeated
|
| 85 |
+
details = [f"{col}: {row[col]}" for col in df.columns if col != time_col]
|
| 86 |
+
# Construct the predictive NLP sentence
|
| 87 |
+
sentence = f"Market Data at {row_time} -> " + ", ".join(details) + "."
|
| 88 |
+
text_output.append(sentence)
|
| 89 |
+
else:
|
| 90 |
+
# Standard fallback for non-financial CSV files (e.g., Q&A sheets)
|
| 91 |
+
for _, row in df.iterrows():
|
| 92 |
+
details = [f"{col}: {row[col]}" for col in df.columns]
|
| 93 |
+
text_output.append(" | ".join(details))
|
| 94 |
+
|
| 95 |
+
# Return the data as a massive, chronological string ready for the sentence chunker
|
| 96 |
+
return "\n".join(text_output)
|
| 97 |
+
|
| 98 |
def parse_incoming_file_to_text(file_path):
|
| 99 |
ext = os.path.splitext(file_path)[1].lower()
|
| 100 |
+
base_name = os.path.basename(file_path)
|
| 101 |
text = ""
|
| 102 |
+
|
| 103 |
if ext == ".txt":
|
| 104 |
with open(file_path, "r", encoding="utf-8") as f:
|
| 105 |
text = f.read()
|
|
|
|
| 111 |
elif ext == ".docx":
|
| 112 |
text = docx2txt.process(file_path)
|
| 113 |
elif ext in [".csv", ".xlsx"]:
|
| 114 |
+
# Pass dataframes directly into the new translation engine
|
| 115 |
df = pd.read_csv(file_path) if ext == ".csv" else pd.read_excel(file_path)
|
| 116 |
+
text = process_financial_csv(df, base_name)
|
| 117 |
elif ext in [".mp4", ".wav", ".mp3"]:
|
| 118 |
text = transcribe_video_audio(file_path)
|
| 119 |
|
|
|
|
| 136 |
elif "๐งฎ Math Wizard" in archetype or "๐ Day Trading" in archetype:
|
| 137 |
instr = "Deconstruct structural math patterns or trading indicator calculations."
|
| 138 |
if "๐ Day Trading" in archetype:
|
| 139 |
+
instr = "Analyze the chronological sequence of market data parameters to establish structural setup context."
|
| 140 |
rows.append({
|
| 141 |
"instruction": instr,
|
| 142 |
+
"input": f"Market Narrative Segment {idx}:",
|
| 143 |
"output": chunk
|
| 144 |
})
|
| 145 |
elif "๐ป Code Assistant" in archetype:
|
|
|
|
| 152 |
rows.append({"text": chunk})
|
| 153 |
return rows
|
| 154 |
|
| 155 |
+
@spaces.GPU
|
| 156 |
def execute_dataset_builder_pipeline(files, archetype, enable_chunking, chunk_size, chunk_overlap):
|
| 157 |
if not files:
|
| 158 |
+
return "โ ๏ธ Target file loading queue is empty. Please upload files.", None
|
| 159 |
|
| 160 |
for f in glob.glob(os.path.join(PROCESSED_DIR, "*.jsonl")):
|
| 161 |
os.remove(f)
|
|
|
|
| 170 |
total_files_compiled += 1
|
| 171 |
|
| 172 |
if not all_extracted_text_blocks:
|
| 173 |
+
return "โ Failed to extract content from assets.", None
|
| 174 |
|
| 175 |
combined_master_string = "\n\n--- FILE SPLIT ---\n\n".join(all_extracted_text_blocks)
|
| 176 |
|
|
|
|
| 186 |
for obj in formatted_dataset_objects:
|
| 187 |
master_f.write(json.dumps(obj) + "\n")
|
| 188 |
|
| 189 |
+
success_log = f"๐ฅ Conversion Complete!\n\nโข Processed: {total_files_compiled}/{len(files)} files\nโข Rows Generated: {len(formatted_dataset_objects)}\nโข Saved At: {MASTER_FILE}"
|
| 190 |
+
|
| 191 |
+
return success_log, MASTER_FILE
|
| 192 |
|
| 193 |
# -------------------------------------------------------------
|
| 194 |
# THEME TOGGLE SWITCH LOGIC โ๏ธ/๐
|
|
|
|
| 225 |
neutral_hue="zinc"
|
| 226 |
)
|
| 227 |
|
|
|
|
| 228 |
with gr.Blocks() as demo:
|
| 229 |
ui_theme_state = gr.State("dark")
|
| 230 |
|
|
|
|
| 236 |
|
| 237 |
with gr.Row():
|
| 238 |
with gr.Column(scale=1):
|
| 239 |
+
file_uploader = gr.File(file_count="multiple", label="๐ฅ Drop Assets Here (.pdf, .txt, .docx, .mp4, .csv)")
|
| 240 |
archetype_dropdown = gr.Dropdown(choices=archetype_choices, value=archetype_choices[0], label="๐ค Choose Target AI Archetype Layout Mapping")
|
| 241 |
|
| 242 |
with gr.Accordion("โ๏ธ Text Chunking Control Panel", open=True):
|
|
|
|
| 247 |
run_btn = gr.Button("๐ Run Conversion & Combine Files", variant="primary")
|
| 248 |
|
| 249 |
with gr.Column(scale=1):
|
| 250 |
+
log_monitor = gr.Textbox(label="๐ฅ๏ธ Core Engine Pipeline Logs", lines=12)
|
| 251 |
+
download_btn = gr.DownloadButton("๐พ Download Compiled Dataset (.jsonl)", variant="primary")
|
| 252 |
|
| 253 |
run_btn.click(
|
| 254 |
fn=execute_dataset_builder_pipeline,
|
| 255 |
inputs=[file_uploader, archetype_dropdown, chunk_toggle, size_input, overlap_input],
|
| 256 |
+
outputs=[log_monitor, download_btn]
|
| 257 |
)
|
| 258 |
|
| 259 |
theme_toggle_btn.click(
|
|
|
|
| 269 |
demo.load(fn=lambda: "dark", outputs=ui_theme_state).then(fn=None, inputs=[ui_theme_state], js=js_theme_switcher)
|
| 270 |
|
| 271 |
if __name__ == "__main__":
|
|
|
|
| 272 |
demo.launch(theme=custom_theme)
|