import base64
import io
import os
import tempfile
from dash import Dash, html, dcc, Input, Output, State, callback_context
import dash_bootstrap_components as dbc
from gradio_client import Client
from docx import Document
import requests
import threading
import time
#### #########
# MODELS: wrap each Gradio client call in functions for reuse
#### #########
model1_client = Client("yuntian-deng/ChatGPT")
model2_client = Client("GenAILearniverse/TextSummarizer")
model3_client = Client("suayptalha/Chat-with-Bitnet-b1.58-2B-4T")
def call_model_1_chat(message, chat_counter=0, chatbot=[]):
# returns chat response string
try:
result = model1_client.predict(
inputs=message,
top_p=1,
temperature=1,
chat_counter=chat_counter,
chatbot=chatbot,
api_name="/predict"
)
return result
except Exception as e:
return f"Error in Model1 chat: {str(e)}"
def call_model_2_summarize(text):
try:
result = model2_client.predict(
input=text,
api_name="/predict"
)
return result
except Exception as e:
return f"Error in Model2 summarization: {str(e)}"
def call_model_3_assist_chat(message):
try:
result = model3_client.predict(
message=message,
param_2="You are a helpful AI assistant.",
param_3=2048,
param_4=0.7,
param_5=0.95,
api_name="/chat"
)
return result
except Exception as e:
return f"Error in Model3 chat assist: {str(e)}"
#### Helper to read docx and get ~30% text
def extract_docx_text(docx_bytes):
# Read docx from bytes, collect paragraphs
try:
doc = Document(io.BytesIO(docx_bytes))
full_text = "\n".join([p.text for p in doc.paragraphs if p.text.strip() != ""])
return full_text
except Exception as e:
return ""
def summarize_docx_bytes(docx_bytes):
full_text = extract_docx_text(docx_bytes)
if not full_text:
return "No readable text found."
# Take 30% of the text - naive approach: approx 30% length substring
length = len(full_text)
partial_text = full_text[: max(10, int(length * 0.3))] # at least 10 chars
# Send to summarizer
summary = call_model_2_summarize(partial_text)
return summary
#### Fake Google Drive download function for demonstration
def download_gdrive_file(file_id):
# For demonstration, this just returns dummy content or simulate download
# API calls to Google drive need credentials & token - skipped.
# Here, just return a sample docx bytes or placeholder
# In real scenario, use googleapiclient.discovery to download file content
# Raise or return None if fail
return None
def summarize_google_drive_files(file_ids):
summaries = {}
for fid in file_ids:
file_bytes = download_gdrive_file(fid)
if file_bytes:
summary = summarize_docx_bytes(file_bytes)
summaries[summary] = f"Google Drive file ID: {fid}"
else:
summaries[f"[Failed to download file ID {fid}]"] = None
return summaries
# App init
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container([
html.H1("RAG/KAG Dash App with Chat & Document Analysis"),
dbc.Row([
dbc.Col([
dcc.Upload(
id='upload-docx',
children=html.Div([
"Drag and Drop or ",
html.A("Select docx Files")
]),
multiple=True,
accept=".docx",
style={
'width': '100%', 'height': '100px', 'lineHeight': '100px',
'borderWidth': '1px', 'borderStyle': 'dashed',
'borderRadius': '5px', 'textAlign': 'center',
'margin-bottom': '10px'
},
),
dbc.Input(id='gdrive-file-ids', placeholder="Enter comma-separated Google Drive File IDs", type='text'),
dbc.Button("Load Google Drive Files", id="load-gdrive-btn", color="primary", className="mb-3"),
html.Div(id='file-summary-div', children=[]),
], width=4),
dbc.Col([
html.Div(id='chat-display', style={'height': '400px', 'overflowY': 'scroll', 'border': '1px solid #ccc', 'padding': '10px', 'margin-bottom': '10px'}),
dbc.Input(id='chat-input', placeholder='Say something...', type='text'),
dbc.Button("Send", id='send-btn', color='success', className='mt-2'),
html.Div(id='model-result-output', style={'whiteSpace': 'pre-wrap', 'marginTop': '15px'})
], width=8)
]),
# Hidden elements to store intermediate states
dcc.Store(id='summaries-store', data={}), # summary -> filename or descriptor
dcc.Store(id='chat-history-store', data=[]),
dcc.Store(id='file-bytes-store', data={}), # fileName -> filebytes base64 string to allow reference if needed
])
@app.callback(
Output('summaries-store', 'data'),
Output('file-summary-div', 'children'),
Output('file-bytes-store', 'data'),
Input('upload-docx', 'contents'),
State('upload-docx', 'filename'),
State('summaries-store', 'data'),
State('file-bytes-store', 'data'),
prevent_initial_call=True
)
def handle_upload(file_contents, filenames, summaries, file_bytes_store):
# file_contents is a list of base64 encoded strings e.g. "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,..."
if not file_contents:
return dash.no_update, dash.no_update, dash.no_update
new_summaries = summaries.copy() if summaries else {}
new_filebytes = file_bytes_store.copy() if file_bytes_store else {}
display_children = []
for i, content in enumerate(file_contents):
filename = filenames[i]
content_type, content_string = content.split(',')
decoded = base64.b64decode(content_string)
# Store raw file bytes base64 for later if needed:
new_filebytes[filename] = content_string
# summarization
summary = summarize_docx_bytes(decoded)
new_summaries[summary] = filename
display_children.append(html.Div([
html.B(f"File: {filename}"),
html.P(f"Summary: {summary}")
]))
return new_summaries, display_children, new_filebytes
@app.callback(
Output('summaries-store', 'data'),
Output('file-summary-div', 'children'),
Output('file-bytes-store', 'data'),
Input('load-gdrive-btn', 'n_clicks'),
State('gdrive-file-ids', 'value'),
State('summaries-store', 'data'),
State('file-bytes-store', 'data'),
prevent_initial_call=True
)
def load_google_drive_files(n_clicks, gdrive_ids, summaries, file_bytes_store):
if not gdrive_ids or gdrive_ids.strip() == "":
return dash.no_update, dash.no_update, dash.no_update
ids = [i.strip() for i in gdrive_ids.split(",") if i.strip() != ""]
# For demonstration, skip actual download; create dummy summaries
new_summaries = summaries.copy() if summaries else {}
new_filebytes = file_bytes_store.copy() if file_bytes_store else {}
display_children = []
for fid in ids:
# Normally download file bytes - here returning dummy text representing the file content
dummy_text = f"Simulated content of Google Drive file {fid}."
summary = call_model_2_summarize(dummy_text[:max(10, int(len(dummy_text)*0.3))])
key = summary if summary else f"Summary failed for {fid}"
new_summaries[key] = f"GDrive File ID: {fid}"
display_children.append(html.Div([
html.B(f"GDrive File ID: {fid}"),
html.P(f"Summary: {key}")
]))
return new_summaries, display_children, new_filebytes
## UTIL - Infer chat intent from chat history
def infer_intent_from_chat(chat_history):
# Very simple keyword-based or heuristic:
# If user input contains keywords to "report" -> report
# "template" -> template
# else chat
last_msg = chat_history[-1]['message'].lower() if chat_history else ""
if "report" in last_msg:
return "generate_report"
elif "template" in last_msg:
return "create_template"
else:
return "chatting"
### Process user chat input and decide which model to call
@app.callback(
Output('chat-history-store', 'data'),
Output('chat-display', 'children'),
Output('model-result-output', 'children'),
Input('send-btn', 'n_clicks'),
State('chat-input', 'value'),
State('chat-history-store', 'data'),
State('summaries-store', 'data'),
prevent_initial_call=True
)
def process_chat(n_clicks, user_message, chat_history, summaries):
if not user_message or user_message.strip() == "":
return dash.no_update, dash.no_update, dash.no_update
chat_history = chat_history or []
summaries = summaries or {}
# Update chat with user's message
chat_history.append({"sender": "user", "message": user_message})
intent = infer_intent_from_chat(chat_history)
# Compose model input based on intent and summaries (knowledge)
# For example, concatenate summaries as context
knowledge_context = "\n".join([f"{k}: {v}" for k, v in summaries.items()])
response_text = ""
mode = intent
# Simulate delay or run in thread (to respect 20-30 sec delay), here we just do blocking
if mode == "chatting":
# Use model 1 or model 3 for chatting: let's pick model1 first for demo
response = call_model_1_chat(user_message)
if isinstance(response, list) or isinstance(response, dict):
response_text = str(response)
else:
response_text = response
elif mode == "create_template":
# perhaps call model3 chat assist with more params or give a template prompt
prompt = f"Create a template based on user input: {user_message}\nContext:\n{knowledge_context}"
response = call_model_3_assist_chat(prompt)
response_text = response
elif mode == "generate_report":
# Use all knowledge to build a report factoring in chat
prompt = f"Generate a well formatted report based on previous chat:\nUser asked: {user_message}\nKnowledge:\n{knowledge_context}"
response = call_model_3_assist_chat(prompt)
response_text = response
else:
response_text = "Unknown intent."
# Append assistant response
chat_history.append({"sender": "assistant", "message": response_text})
# Prepare chat display as html divs
chat_display_divs = []
for msg in chat_history:
align = "left" if msg["sender"] == "user" else "right"
color = "#DCF8C6" if msg["sender"] == "user" else "#ECECEC"
chat_display_divs.append(html.Div(msg["message"], style={
"backgroundColor": color,
"textAlign": align,
"margin": "5px",
"padding": "8px",
"borderRadius": "8px",
"maxWidth": "70%",
"wordBreak": "break-word"
}))
return chat_history, chat_display_divs, response_text
if __name__ == '__main__':
app.run_server(debug=True)