Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,21 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
import os
|
| 3 |
import tempfile
|
| 4 |
import uuid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import base64
|
|
|
|
| 6 |
import io
|
|
|
|
| 7 |
import json
|
| 8 |
import re
|
| 9 |
from datetime import datetime, timedelta
|
| 10 |
|
| 11 |
-
# Third-party imports
|
| 12 |
-
import gradio as gr
|
| 13 |
-
import groq
|
| 14 |
-
import numpy as np
|
| 15 |
-
import pandas as pd
|
| 16 |
-
import openpyxl
|
| 17 |
-
import requests
|
| 18 |
-
import fitz # PyMuPDF
|
| 19 |
-
from PIL import Image
|
| 20 |
-
from dotenv import load_dotenv
|
| 21 |
-
from transformers import AutoProcessor, AutoModelForVision2Seq
|
| 22 |
-
import torch
|
| 23 |
-
|
| 24 |
-
# LangChain imports
|
| 25 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 26 |
-
from langchain_community.vectorstores import FAISS
|
| 27 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 28 |
-
|
| 29 |
# Load environment variables
|
| 30 |
load_dotenv()
|
| 31 |
client = groq.Client(api_key=os.getenv("GROQ_TECH_API_KEY"))
|
|
@@ -80,102 +70,6 @@ body { background-color: var(--light-background); font-family: 'Google Sans', 'R
|
|
| 80 |
.qa-body { color: var(--dark-text); font-size: 0.95rem; margin-bottom: 10px; }
|
| 81 |
.qa-meta { display: flex; justify-content: space-between; color: #5F6368; font-size: 0.85rem; }
|
| 82 |
.tag { background-color: #E8F0FE; color: var(--primary-color); padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; margin-right: 5px; display: inline-block; }
|
| 83 |
-
.toggle-container { display: flex; align-items: center; margin-bottom: 15px; }
|
| 84 |
-
.toggle-label { margin-right: 10px; font-weight: 500; }
|
| 85 |
-
.search-toggle { margin-left: 5px; }
|
| 86 |
-
.voice-btn { background-color: var(--primary-color) !important; border-radius: 50% !important; width: 44px !important; height: 44px !important; display: flex !important; align-items: center !important; justify-content: center !important; color: var(--white) !important; box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important; }
|
| 87 |
-
.speak-btn { background-color: var(--secondary-color) !important; border-radius: 24px !important; color: var(--white) !important; padding: 8px 16px !important; font-weight: 500 !important; margin-left: 10px !important; }
|
| 88 |
-
.audio-controls { display: flex; align-items: center; margin-top: 10px; }
|
| 89 |
-
|
| 90 |
-
/* Audio Visualization Elements */
|
| 91 |
-
.audio-visualization {
|
| 92 |
-
display: flex;
|
| 93 |
-
align-items: center;
|
| 94 |
-
justify-content: center;
|
| 95 |
-
gap: 4px;
|
| 96 |
-
height: 40px;
|
| 97 |
-
padding: 10px;
|
| 98 |
-
background-color: rgba(0,0,0,0.05);
|
| 99 |
-
border-radius: 12px;
|
| 100 |
-
margin: 10px 0;
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
.audio-bar {
|
| 104 |
-
width: 3px;
|
| 105 |
-
background-color: var(--accent-color);
|
| 106 |
-
border-radius: 2px;
|
| 107 |
-
height: 5px;
|
| 108 |
-
transition: height 0.1s ease;
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
.audio-status {
|
| 112 |
-
font-size: 0.85rem;
|
| 113 |
-
color: var(--secondary-color);
|
| 114 |
-
text-align: center;
|
| 115 |
-
margin-top: 5px;
|
| 116 |
-
font-style: italic;
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
.recording-indicator {
|
| 120 |
-
width: 12px;
|
| 121 |
-
height: 12px;
|
| 122 |
-
border-radius: 50%;
|
| 123 |
-
background-color: #ff4b4b;
|
| 124 |
-
margin-right: 8px;
|
| 125 |
-
animation: blink 1s infinite;
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
.playing-indicator {
|
| 129 |
-
width: 12px;
|
| 130 |
-
height: 12px;
|
| 131 |
-
border-radius: 50%;
|
| 132 |
-
background-color: #4bff4b;
|
| 133 |
-
margin-right: 8px;
|
| 134 |
-
animation: pulse 1s infinite;
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
@keyframes blink {
|
| 138 |
-
0% { opacity: 1; }
|
| 139 |
-
50% { opacity: 0.4; }
|
| 140 |
-
100% { opacity: 1; }
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
@keyframes pulse {
|
| 144 |
-
0% { transform: scale(1); }
|
| 145 |
-
50% { transform: scale(1.2); }
|
| 146 |
-
100% { transform: scale(1); }
|
| 147 |
-
}
|
| 148 |
-
|
| 149 |
-
.file-upload-enhancement .file-preview {
|
| 150 |
-
max-height: 200px;
|
| 151 |
-
overflow: auto;
|
| 152 |
-
border: 1px solid var(--border-color);
|
| 153 |
-
border-radius: 8px;
|
| 154 |
-
padding: 10px;
|
| 155 |
-
margin-top: 10px;
|
| 156 |
-
background-color: rgba(0,0,0,0.02);
|
| 157 |
-
}
|
| 158 |
-
|
| 159 |
-
.excel-preview-table {
|
| 160 |
-
width: 100%;
|
| 161 |
-
border-collapse: collapse;
|
| 162 |
-
font-size: 0.85rem;
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
.excel-preview-table th, .excel-preview-table td {
|
| 166 |
-
border: 1px solid #ddd;
|
| 167 |
-
padding: 4px 8px;
|
| 168 |
-
text-align: left;
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
.excel-preview-table th {
|
| 172 |
-
background-color: var(--secondary-color);
|
| 173 |
-
color: white;
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
.excel-preview-table tr:nth-child(even) {
|
| 177 |
-
background-color: rgba(0,0,0,0.03);
|
| 178 |
-
}
|
| 179 |
"""
|
| 180 |
|
| 181 |
# Function to process PDF files
|
|
@@ -215,147 +109,8 @@ def process_pdf(pdf_file):
|
|
| 215 |
os.unlink(pdf_path)
|
| 216 |
return None, f"Error processing PDF: {str(e)}", {"page_images": [], "total_pages": 0, "total_words": 0}
|
| 217 |
|
| 218 |
-
# New function to process Excel files
|
| 219 |
-
def process_excel(excel_file):
|
| 220 |
-
if excel_file is None:
|
| 221 |
-
return None, "No file uploaded", {"data_preview": "", "total_sheets": 0, "total_rows": 0}
|
| 222 |
-
|
| 223 |
-
try:
|
| 224 |
-
session_id = str(uuid.uuid4())
|
| 225 |
-
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as temp_file:
|
| 226 |
-
temp_file.write(excel_file)
|
| 227 |
-
excel_path = temp_file.name
|
| 228 |
-
|
| 229 |
-
# Read Excel file with pandas
|
| 230 |
-
excel_data = pd.ExcelFile(excel_path)
|
| 231 |
-
sheet_names = excel_data.sheet_names
|
| 232 |
-
all_texts = []
|
| 233 |
-
total_rows = 0
|
| 234 |
-
|
| 235 |
-
# Process each sheet
|
| 236 |
-
for sheet in sheet_names:
|
| 237 |
-
df = pd.read_excel(excel_path, sheet_name=sheet)
|
| 238 |
-
total_rows += len(df)
|
| 239 |
-
|
| 240 |
-
# Convert dataframe to text for vectorization
|
| 241 |
-
sheet_text = f"Sheet: {sheet}\n"
|
| 242 |
-
sheet_text += df.to_string(index=False)
|
| 243 |
-
all_texts.append(sheet_text)
|
| 244 |
-
|
| 245 |
-
# Generate HTML preview of first sheet
|
| 246 |
-
first_df = pd.read_excel(excel_path, sheet_name=0)
|
| 247 |
-
preview_rows = min(10, len(first_df))
|
| 248 |
-
data_preview = first_df.head(preview_rows).to_html(classes="excel-preview-table", index=False)
|
| 249 |
-
|
| 250 |
-
# Process for vectorstore
|
| 251 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 252 |
-
chunks = text_splitter.create_documents(all_texts)
|
| 253 |
-
vectorstore = FAISS.from_documents(chunks, embeddings)
|
| 254 |
-
index_path = os.path.join(FAISS_INDEX_DIR, session_id)
|
| 255 |
-
vectorstore.save_local(index_path)
|
| 256 |
-
user_vectorstores[session_id] = vectorstore
|
| 257 |
-
|
| 258 |
-
os.unlink(excel_path)
|
| 259 |
-
excel_state = {"data_preview": data_preview, "total_sheets": len(sheet_names), "total_rows": total_rows}
|
| 260 |
-
return session_id, f"✅ Successfully processed {len(chunks)} text chunks from Excel file", excel_state
|
| 261 |
-
except Exception as e:
|
| 262 |
-
if "excel_path" in locals() and os.path.exists(excel_path):
|
| 263 |
-
os.unlink(excel_path)
|
| 264 |
-
return None, f"Error processing Excel file: {str(e)}", {"data_preview": "", "total_sheets": 0, "total_rows": 0}
|
| 265 |
-
|
| 266 |
-
# Function to analyze image using SmolDocling
|
| 267 |
-
def analyze_image(image_file):
|
| 268 |
-
"""
|
| 269 |
-
Basic image analysis function that doesn't rely on external models
|
| 270 |
-
"""
|
| 271 |
-
if image_file is None:
|
| 272 |
-
return "No image uploaded. Please upload an image to analyze."
|
| 273 |
-
|
| 274 |
-
try:
|
| 275 |
-
image = Image.open(image_file)
|
| 276 |
-
width, height = image.size
|
| 277 |
-
format = image.format
|
| 278 |
-
mode = image.mode
|
| 279 |
-
|
| 280 |
-
analysis = f"""## Technical Document Analysis
|
| 281 |
-
|
| 282 |
-
**Image Properties:**
|
| 283 |
-
- Dimensions: {width}x{height} pixels
|
| 284 |
-
- Format: {format}
|
| 285 |
-
- Color Mode: {mode}
|
| 286 |
-
|
| 287 |
-
**Technical Analysis:**
|
| 288 |
-
1. Document Quality:
|
| 289 |
-
- Resolution: {'High' if width > 2000 or height > 2000 else 'Medium' if width > 1000 or height > 1000 else 'Low'}
|
| 290 |
-
- Color Depth: {mode}
|
| 291 |
-
|
| 292 |
-
2. Recommendations:
|
| 293 |
-
- For text extraction, consider using PDF format
|
| 294 |
-
- For technical diagrams, ensure high resolution
|
| 295 |
-
- Consider OCR for text content
|
| 296 |
-
|
| 297 |
-
**Note:** For detailed technical analysis, please convert to PDF format
|
| 298 |
-
"""
|
| 299 |
-
return analysis
|
| 300 |
-
except Exception as e:
|
| 301 |
-
return f"Error analyzing image: {str(e)}\n\nPlease try using PDF format instead."
|
| 302 |
-
|
| 303 |
-
# Function to handle different file types
|
| 304 |
-
def process_file(file_data, file_type):
|
| 305 |
-
if file_data is None:
|
| 306 |
-
return None, "No file uploaded", None
|
| 307 |
-
|
| 308 |
-
if file_type == "pdf":
|
| 309 |
-
return process_pdf(file_data)
|
| 310 |
-
elif file_type == "excel":
|
| 311 |
-
return process_excel(file_data)
|
| 312 |
-
elif file_type == "image":
|
| 313 |
-
# For image files, we'll just use them directly for analysis
|
| 314 |
-
# But we'll return a session ID to maintain consistency
|
| 315 |
-
session_id = str(uuid.uuid4())
|
| 316 |
-
return session_id, "✅ Image file ready for analysis", None
|
| 317 |
-
else:
|
| 318 |
-
return None, "Unsupported file type", None
|
| 319 |
-
|
| 320 |
-
# Function for speech-to-text conversion
|
| 321 |
-
def speech_to_text():
|
| 322 |
-
try:
|
| 323 |
-
r = sr.Recognizer()
|
| 324 |
-
with sr.Microphone() as source:
|
| 325 |
-
r.adjust_for_ambient_noise(source)
|
| 326 |
-
audio = r.listen(source)
|
| 327 |
-
text = r.recognize_google(audio)
|
| 328 |
-
return text
|
| 329 |
-
except sr.UnknownValueError:
|
| 330 |
-
return "Could not understand audio. Please try again."
|
| 331 |
-
except sr.RequestError as e:
|
| 332 |
-
return f"Error with speech recognition service: {e}"
|
| 333 |
-
except Exception as e:
|
| 334 |
-
return f"Error converting speech to text: {str(e)}"
|
| 335 |
-
|
| 336 |
-
# Function for text-to-speech conversion
|
| 337 |
-
def text_to_speech(text, history):
|
| 338 |
-
if not text or not history:
|
| 339 |
-
return None
|
| 340 |
-
|
| 341 |
-
try:
|
| 342 |
-
# Get the last bot response
|
| 343 |
-
last_response = history[-1][1]
|
| 344 |
-
|
| 345 |
-
# Convert text to speech
|
| 346 |
-
tts = pyttsx3.init()
|
| 347 |
-
tts.setProperty('rate', 150)
|
| 348 |
-
tts.setProperty('volume', 0.9)
|
| 349 |
-
tts.save_to_file(last_response, "temp_output.mp3")
|
| 350 |
-
tts.runAndWait()
|
| 351 |
-
|
| 352 |
-
return "temp_output.mp3"
|
| 353 |
-
except Exception as e:
|
| 354 |
-
print(f"Error in text-to-speech: {e}")
|
| 355 |
-
return None
|
| 356 |
-
|
| 357 |
# Function to generate chatbot responses with Tech theme
|
| 358 |
-
def generate_response(message, session_id, model_name, history
|
| 359 |
if not message:
|
| 360 |
return history
|
| 361 |
try:
|
|
@@ -366,8 +121,8 @@ def generate_response(message, session_id, model_name, history, web_search_enabl
|
|
| 366 |
if docs:
|
| 367 |
context = "\n\nRelevant information from uploaded PDF:\n" + "\n".join(f"- {doc.page_content}" for doc in docs)
|
| 368 |
|
| 369 |
-
# Check if it's a GitHub repo search
|
| 370 |
-
if
|
| 371 |
query = re.sub(r'^/github\s+', '', message, flags=re.IGNORECASE)
|
| 372 |
repo_results = search_github_repos(query)
|
| 373 |
if repo_results:
|
|
@@ -384,8 +139,8 @@ def generate_response(message, session_id, model_name, history, web_search_enabl
|
|
| 384 |
history.append((message, "No GitHub repositories found for your query."))
|
| 385 |
return history
|
| 386 |
|
| 387 |
-
# Check if it's a Stack Overflow search
|
| 388 |
-
if
|
| 389 |
query = re.sub(r'^/stack\s+', '', message, flags=re.IGNORECASE)
|
| 390 |
qa_results = search_stackoverflow(query)
|
| 391 |
if qa_results:
|
|
@@ -682,155 +437,106 @@ def perform_stack_search(query, tag, sort_by):
|
|
| 682 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 683 |
current_session_id = gr.State(None)
|
| 684 |
pdf_state = gr.State({"page_images": [], "total_pages": 0, "total_words": 0})
|
| 685 |
-
excel_state = gr.State({"data_preview": "", "total_sheets": 0, "total_rows": 0})
|
| 686 |
-
file_type = gr.State("none")
|
| 687 |
-
audio_status = gr.State("Ready")
|
| 688 |
-
|
| 689 |
gr.HTML("""
|
| 690 |
<div class="header">
|
| 691 |
-
<div class="header-title">Tech-Vision
|
| 692 |
-
<div class="header-subtitle">Analyze technical documents
|
| 693 |
</div>
|
| 694 |
""")
|
| 695 |
with gr.Row(elem_classes="container"):
|
| 696 |
with gr.Column(scale=1, min_width=300):
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
pdf_upload_button = gr.Button("Process PDF", variant="primary")
|
| 701 |
-
|
| 702 |
-
with gr.TabItem("Excel"):
|
| 703 |
-
excel_file = gr.File(label="Upload Excel File", file_types=[".xlsx", ".xls"], type="binary")
|
| 704 |
-
excel_upload_button = gr.Button("Process Excel", variant="primary")
|
| 705 |
-
|
| 706 |
-
with gr.TabItem("Image"):
|
| 707 |
-
image_input = gr.File(
|
| 708 |
-
label="Upload Image",
|
| 709 |
-
file_types=["image"],
|
| 710 |
-
type="filepath"
|
| 711 |
-
)
|
| 712 |
-
analyze_btn = gr.Button("Analyze Image")
|
| 713 |
-
|
| 714 |
-
file_status = gr.Markdown("No file uploaded yet")
|
| 715 |
-
|
| 716 |
-
# Model selector
|
| 717 |
model_dropdown = gr.Dropdown(
|
| 718 |
choices=["llama3-70b-8192", "llama3-8b-8192", "mixtral-8x7b-32768", "gemma-7b-it"],
|
| 719 |
value="llama3-70b-8192",
|
| 720 |
label="Select Groq Model"
|
| 721 |
)
|
| 722 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
with gr.Column(scale=2, min_width=600):
|
| 724 |
with gr.Tabs():
|
| 725 |
with gr.TabItem("PDF Viewer"):
|
| 726 |
with gr.Column(elem_classes="pdf-viewer-container"):
|
| 727 |
page_slider = gr.Slider(minimum=1, maximum=1, step=1, label="Page Number", value=1)
|
| 728 |
pdf_image = gr.Image(label="PDF Page", type="pil", elem_classes="pdf-viewer-image")
|
| 729 |
-
|
| 730 |
|
| 731 |
-
with gr.TabItem("
|
| 732 |
-
|
| 733 |
-
excel_stats = gr.Markdown("No Excel file uploaded yet", elem_classes="stats-box")
|
| 734 |
|
| 735 |
-
with gr.TabItem("
|
| 736 |
-
|
| 737 |
-
|
|
|
|
|
|
|
| 738 |
|
| 739 |
-
# Audio visualization elements
|
| 740 |
-
with gr.Row(elem_classes="container"):
|
| 741 |
-
with gr.Column():
|
| 742 |
-
audio_vis = gr.HTML("""
|
| 743 |
-
<div class="audio-visualization">
|
| 744 |
-
<div class="audio-bar" style="height: 5px;"></div>
|
| 745 |
-
<div class="audio-bar" style="height: 12px;"></div>
|
| 746 |
-
<div class="audio-bar" style="height: 18px;"></div>
|
| 747 |
-
<div class="audio-bar" style="height: 15px;"></div>
|
| 748 |
-
<div class="audio-bar" style="height: 10px;"></div>
|
| 749 |
-
<div class="audio-bar" style="height: 20px;"></div>
|
| 750 |
-
<div class="audio-bar" style="height: 14px;"></div>
|
| 751 |
-
<div class="audio-bar" style="height: 8px;"></div>
|
| 752 |
-
</div>
|
| 753 |
-
""", visible=False)
|
| 754 |
-
audio_status_display = gr.Markdown("", elem_classes="audio-status")
|
| 755 |
-
|
| 756 |
-
# Chat interface
|
| 757 |
with gr.Row(elem_classes="container"):
|
| 758 |
with gr.Column(scale=2, min_width=600):
|
| 759 |
-
chatbot = gr.Chatbot(
|
| 760 |
-
height=400,
|
| 761 |
-
show_copy_button=True,
|
| 762 |
-
elem_classes="chat-container",
|
| 763 |
-
type="messages" # Use the new messages format
|
| 764 |
-
)
|
| 765 |
with gr.Row():
|
| 766 |
-
msg = gr.Textbox(
|
| 767 |
-
show_label=False,
|
| 768 |
-
placeholder="Ask about your document or click the microphone to speak...",
|
| 769 |
-
scale=5
|
| 770 |
-
)
|
| 771 |
-
voice_btn = gr.Button("🎤", elem_classes="voice-btn")
|
| 772 |
send_btn = gr.Button("Send", scale=1)
|
| 773 |
-
|
| 774 |
-
with gr.Row(elem_classes="audio-controls"):
|
| 775 |
-
clear_btn = gr.Button("Clear Conversation")
|
| 776 |
-
speak_btn = gr.Button("🔊 Speak Response", elem_classes="speak-btn")
|
| 777 |
-
audio_player = gr.Audio(label="Response Audio", type="filepath", visible=False)
|
| 778 |
|
| 779 |
-
# Event Handlers
|
| 780 |
-
|
| 781 |
-
lambda x: ("pdf", x),
|
| 782 |
-
inputs=[pdf_file],
|
| 783 |
-
outputs=[file_type, file_status]
|
| 784 |
-
).then(
|
| 785 |
process_pdf,
|
| 786 |
inputs=[pdf_file],
|
| 787 |
-
outputs=[current_session_id,
|
| 788 |
).then(
|
| 789 |
update_pdf_viewer,
|
| 790 |
inputs=[pdf_state],
|
| 791 |
-
outputs=[page_slider, pdf_image,
|
| 792 |
-
)
|
| 793 |
-
|
| 794 |
-
# Event Handlers for Excel processing
|
| 795 |
-
def update_excel_preview(state):
|
| 796 |
-
if not state:
|
| 797 |
-
return "", "No Excel file uploaded yet"
|
| 798 |
-
preview = state.get("data_preview", "")
|
| 799 |
-
sheets = state.get("total_sheets", 0)
|
| 800 |
-
rows = state.get("total_rows", 0)
|
| 801 |
-
stats = f"**Excel Statistics:**\nSheets: {sheets}\nTotal Rows: {rows}"
|
| 802 |
-
return preview, stats
|
| 803 |
-
|
| 804 |
-
excel_upload_button.click(
|
| 805 |
-
lambda x: ("excel", x),
|
| 806 |
-
inputs=[excel_file],
|
| 807 |
-
outputs=[file_type, file_status]
|
| 808 |
-
).then(
|
| 809 |
-
process_excel,
|
| 810 |
-
inputs=[excel_file],
|
| 811 |
-
outputs=[current_session_id, file_status, excel_state]
|
| 812 |
-
).then(
|
| 813 |
-
update_excel_preview,
|
| 814 |
-
inputs=[excel_state],
|
| 815 |
-
outputs=[excel_preview, excel_stats]
|
| 816 |
-
)
|
| 817 |
-
|
| 818 |
-
# Event Handlers for Image Analysis
|
| 819 |
-
analyze_btn.click(
|
| 820 |
-
lambda x: ("image", x),
|
| 821 |
-
inputs=[image_input],
|
| 822 |
-
outputs=[file_type, file_status]
|
| 823 |
-
).then(
|
| 824 |
-
analyze_image,
|
| 825 |
-
inputs=[image_input],
|
| 826 |
-
outputs=[image_analysis_results]
|
| 827 |
-
).then(
|
| 828 |
-
lambda x: Image.open(x) if x else None,
|
| 829 |
-
inputs=[image_input],
|
| 830 |
-
outputs=[image_preview]
|
| 831 |
)
|
| 832 |
|
| 833 |
-
# Chat message handling
|
| 834 |
msg.submit(
|
| 835 |
generate_response,
|
| 836 |
inputs=[msg, current_session_id, model_dropdown, chatbot],
|
|
@@ -843,55 +549,43 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
|
| 843 |
outputs=[chatbot]
|
| 844 |
).then(lambda: "", None, [msg])
|
| 845 |
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
outputs=[audio_status_display, audio_vis, msg]
|
| 851 |
-
)
|
| 852 |
-
|
| 853 |
-
# Improved text-to-speech with visual feedback
|
| 854 |
-
speak_btn.click(
|
| 855 |
-
text_to_speech,
|
| 856 |
-
inputs=[audio_status, chatbot],
|
| 857 |
-
outputs=[audio_status_display, audio_vis, audio_player]
|
| 858 |
-
).then(
|
| 859 |
-
lambda x: gr.update(visible=True) if x else gr.update(visible=False),
|
| 860 |
-
inputs=[audio_player],
|
| 861 |
-
outputs=[audio_player]
|
| 862 |
)
|
| 863 |
|
| 864 |
-
# Page navigation for PDF
|
| 865 |
page_slider.change(
|
| 866 |
update_image,
|
| 867 |
inputs=[page_slider, pdf_state],
|
| 868 |
outputs=[pdf_image]
|
| 869 |
)
|
| 870 |
|
| 871 |
-
#
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
|
|
|
| 887 |
)
|
| 888 |
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
|
| 896 |
# Launch the app
|
| 897 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import groq
|
| 3 |
import os
|
| 4 |
import tempfile
|
| 5 |
import uuid
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain.vectorstores import FAISS
|
| 9 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 10 |
+
import fitz # PyMuPDF
|
| 11 |
import base64
|
| 12 |
+
from PIL import Image
|
| 13 |
import io
|
| 14 |
+
import requests
|
| 15 |
import json
|
| 16 |
import re
|
| 17 |
from datetime import datetime, timedelta
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Load environment variables
|
| 20 |
load_dotenv()
|
| 21 |
client = groq.Client(api_key=os.getenv("GROQ_TECH_API_KEY"))
|
|
|
|
| 70 |
.qa-body { color: var(--dark-text); font-size: 0.95rem; margin-bottom: 10px; }
|
| 71 |
.qa-meta { display: flex; justify-content: space-between; color: #5F6368; font-size: 0.85rem; }
|
| 72 |
.tag { background-color: #E8F0FE; color: var(--primary-color); padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; margin-right: 5px; display: inline-block; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
"""
|
| 74 |
|
| 75 |
# Function to process PDF files
|
|
|
|
| 109 |
os.unlink(pdf_path)
|
| 110 |
return None, f"Error processing PDF: {str(e)}", {"page_images": [], "total_pages": 0, "total_words": 0}
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
# Function to generate chatbot responses with Tech theme
|
| 113 |
+
def generate_response(message, session_id, model_name, history):
|
| 114 |
if not message:
|
| 115 |
return history
|
| 116 |
try:
|
|
|
|
| 121 |
if docs:
|
| 122 |
context = "\n\nRelevant information from uploaded PDF:\n" + "\n".join(f"- {doc.page_content}" for doc in docs)
|
| 123 |
|
| 124 |
+
# Check if it's a GitHub repo search
|
| 125 |
+
if re.match(r'^/github\s+.+', message, re.IGNORECASE):
|
| 126 |
query = re.sub(r'^/github\s+', '', message, flags=re.IGNORECASE)
|
| 127 |
repo_results = search_github_repos(query)
|
| 128 |
if repo_results:
|
|
|
|
| 139 |
history.append((message, "No GitHub repositories found for your query."))
|
| 140 |
return history
|
| 141 |
|
| 142 |
+
# Check if it's a Stack Overflow search
|
| 143 |
+
if re.match(r'^/stack\s+.+', message, re.IGNORECASE):
|
| 144 |
query = re.sub(r'^/stack\s+', '', message, flags=re.IGNORECASE)
|
| 145 |
qa_results = search_stackoverflow(query)
|
| 146 |
if qa_results:
|
|
|
|
| 437 |
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 438 |
current_session_id = gr.State(None)
|
| 439 |
pdf_state = gr.State({"page_images": [], "total_pages": 0, "total_words": 0})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
gr.HTML("""
|
| 441 |
<div class="header">
|
| 442 |
+
<div class="header-title">Tech-Vision</div>
|
| 443 |
+
<div class="header-subtitle">Analyze technical documents with Groq's LLM API.</div>
|
| 444 |
</div>
|
| 445 |
""")
|
| 446 |
with gr.Row(elem_classes="container"):
|
| 447 |
with gr.Column(scale=1, min_width=300):
|
| 448 |
+
pdf_file = gr.File(label="Upload PDF Document", file_types=[".pdf"], type="binary")
|
| 449 |
+
upload_button = gr.Button("Process PDF", variant="primary")
|
| 450 |
+
pdf_status = gr.Markdown("No PDF uploaded yet")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
model_dropdown = gr.Dropdown(
|
| 452 |
choices=["llama3-70b-8192", "llama3-8b-8192", "mixtral-8x7b-32768", "gemma-7b-it"],
|
| 453 |
value="llama3-70b-8192",
|
| 454 |
label="Select Groq Model"
|
| 455 |
)
|
| 456 |
+
|
| 457 |
+
# Tech Tools Section
|
| 458 |
+
gr.Markdown("### Developer Tools", elem_classes="tool-title")
|
| 459 |
+
with gr.Group(elem_classes="tool-container"):
|
| 460 |
+
with gr.Tabs():
|
| 461 |
+
with gr.TabItem("GitHub Search"):
|
| 462 |
+
repo_query = gr.Textbox(label="Search Query", placeholder="Enter keywords to search for repositories")
|
| 463 |
+
with gr.Row():
|
| 464 |
+
language = gr.Dropdown(
|
| 465 |
+
choices=["any", "JavaScript", "Python", "Java", "C++", "TypeScript", "Go", "Rust", "PHP", "C#"],
|
| 466 |
+
value="any",
|
| 467 |
+
label="Language"
|
| 468 |
+
)
|
| 469 |
+
min_stars = gr.Dropdown(
|
| 470 |
+
choices=["0", "10", "50", "100", "1000", "10000"],
|
| 471 |
+
value="0",
|
| 472 |
+
label="Min Stars"
|
| 473 |
+
)
|
| 474 |
+
sort_by = gr.Dropdown(
|
| 475 |
+
choices=["stars", "forks", "updated"],
|
| 476 |
+
value="stars",
|
| 477 |
+
label="Sort By"
|
| 478 |
+
)
|
| 479 |
+
repo_search_btn = gr.Button("Search Repositories")
|
| 480 |
+
|
| 481 |
+
with gr.TabItem("Stack Overflow"):
|
| 482 |
+
stack_query = gr.Textbox(label="Search Query", placeholder="Enter your technical question")
|
| 483 |
+
with gr.Row():
|
| 484 |
+
tag = gr.Dropdown(
|
| 485 |
+
choices=["any", "python", "javascript", "java", "c++", "react", "node.js", "android", "ios", "sql"],
|
| 486 |
+
value="any",
|
| 487 |
+
label="Tag"
|
| 488 |
+
)
|
| 489 |
+
so_sort_by = gr.Dropdown(
|
| 490 |
+
choices=["votes", "newest", "activity"],
|
| 491 |
+
value="votes",
|
| 492 |
+
label="Sort By"
|
| 493 |
+
)
|
| 494 |
+
so_search_btn = gr.Button("Search Stack Overflow")
|
| 495 |
+
|
| 496 |
+
with gr.TabItem("Code Explainer"):
|
| 497 |
+
code_input = gr.Textbox(
|
| 498 |
+
label="Code to Explain",
|
| 499 |
+
placeholder="Paste your code here...",
|
| 500 |
+
lines=10
|
| 501 |
+
)
|
| 502 |
+
explain_btn = gr.Button("Explain Code")
|
| 503 |
+
|
| 504 |
with gr.Column(scale=2, min_width=600):
|
| 505 |
with gr.Tabs():
|
| 506 |
with gr.TabItem("PDF Viewer"):
|
| 507 |
with gr.Column(elem_classes="pdf-viewer-container"):
|
| 508 |
page_slider = gr.Slider(minimum=1, maximum=1, step=1, label="Page Number", value=1)
|
| 509 |
pdf_image = gr.Image(label="PDF Page", type="pil", elem_classes="pdf-viewer-image")
|
| 510 |
+
stats_display = gr.Markdown("No PDF uploaded yet", elem_classes="stats-box")
|
| 511 |
|
| 512 |
+
with gr.TabItem("GitHub Results"):
|
| 513 |
+
repo_results = gr.Markdown("Search for repositories to see results here")
|
|
|
|
| 514 |
|
| 515 |
+
with gr.TabItem("Stack Overflow Results"):
|
| 516 |
+
stack_results = gr.Markdown("Search for questions to see results here")
|
| 517 |
+
|
| 518 |
+
with gr.TabItem("Code Explanation"):
|
| 519 |
+
code_explanation = gr.Markdown("Paste your code and click 'Explain Code' to see an explanation here")
|
| 520 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
with gr.Row(elem_classes="container"):
|
| 522 |
with gr.Column(scale=2, min_width=600):
|
| 523 |
+
chatbot = gr.Chatbot(height=500, bubble_full_width=False, show_copy_button=True, elem_classes="chat-container")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
with gr.Row():
|
| 525 |
+
msg = gr.Textbox(show_label=False, placeholder="Ask about your document, type /github to search repos, or /stack to search Stack Overflow...", scale=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
send_btn = gr.Button("Send", scale=1)
|
| 527 |
+
clear_btn = gr.Button("Clear Conversation")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
|
| 529 |
+
# Event Handlers
|
| 530 |
+
upload_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 531 |
process_pdf,
|
| 532 |
inputs=[pdf_file],
|
| 533 |
+
outputs=[current_session_id, pdf_status, pdf_state]
|
| 534 |
).then(
|
| 535 |
update_pdf_viewer,
|
| 536 |
inputs=[pdf_state],
|
| 537 |
+
outputs=[page_slider, pdf_image, stats_display]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
)
|
| 539 |
|
|
|
|
| 540 |
msg.submit(
|
| 541 |
generate_response,
|
| 542 |
inputs=[msg, current_session_id, model_dropdown, chatbot],
|
|
|
|
| 549 |
outputs=[chatbot]
|
| 550 |
).then(lambda: "", None, [msg])
|
| 551 |
|
| 552 |
+
clear_btn.click(
|
| 553 |
+
lambda: ([], None, "No PDF uploaded yet", {"page_images": [], "total_pages": 0, "total_words": 0}, 0, None, "No PDF uploaded yet"),
|
| 554 |
+
None,
|
| 555 |
+
[chatbot, current_session_id, pdf_status, pdf_state, page_slider, pdf_image, stats_display]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
)
|
| 557 |
|
|
|
|
| 558 |
page_slider.change(
|
| 559 |
update_image,
|
| 560 |
inputs=[page_slider, pdf_state],
|
| 561 |
outputs=[pdf_image]
|
| 562 |
)
|
| 563 |
|
| 564 |
+
# Tech tool handlers
|
| 565 |
+
repo_search_btn.click(
|
| 566 |
+
perform_repo_search,
|
| 567 |
+
inputs=[repo_query, language, sort_by, min_stars],
|
| 568 |
+
outputs=[repo_results]
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
so_search_btn.click(
|
| 572 |
+
perform_stack_search,
|
| 573 |
+
inputs=[stack_query, tag, so_sort_by],
|
| 574 |
+
outputs=[stack_results]
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
explain_btn.click(
|
| 578 |
+
explain_code,
|
| 579 |
+
inputs=[code_input],
|
| 580 |
+
outputs=[code_explanation]
|
| 581 |
)
|
| 582 |
|
| 583 |
+
# Add footer with attribution
|
| 584 |
+
gr.HTML("""
|
| 585 |
+
<div style="text-align: center; margin-top: 20px; padding: 10px; color: #666; font-size: 0.8rem; border-top: 1px solid #eee;">
|
| 586 |
+
Created by Calvin Allen Crawford
|
| 587 |
+
</div>
|
| 588 |
+
""")
|
| 589 |
|
| 590 |
# Launch the app
|
| 591 |
if __name__ == "__main__":
|