Update app.py
Browse files
app.py
CHANGED
|
@@ -268,90 +268,86 @@
|
|
| 268 |
|
| 269 |
# demo.launch()
|
| 270 |
|
|
|
|
|
|
|
| 271 |
import gradio as gr
|
| 272 |
from transformers import pipeline
|
| 273 |
import requests
|
| 274 |
-
import os
|
| 275 |
import pandas as pd
|
| 276 |
import time
|
| 277 |
-
import io
|
| 278 |
-
from contextlib import redirect_stdout
|
| 279 |
|
| 280 |
# =========================
|
| 281 |
-
#
|
| 282 |
# =========================
|
| 283 |
-
client_id = "
|
| 284 |
-
client_secret = "
|
| 285 |
-
token_url = "
|
| 286 |
|
| 287 |
-
cap_service_url_customers = "
|
| 288 |
-
cap_service_url_products = "
|
| 289 |
-
cap_service_url_saleorders = "
|
| 290 |
-
cap_service_url_saleorderitems = "
|
| 291 |
|
| 292 |
# =========================
|
| 293 |
-
# GLOBAL
|
| 294 |
# =========================
|
| 295 |
access_token = None
|
| 296 |
-
|
| 297 |
-
cached_products = None
|
| 298 |
-
cached_salesorders = None
|
| 299 |
-
cached_salesorderitems = None
|
| 300 |
last_refresh = 0
|
| 301 |
|
| 302 |
# =========================
|
| 303 |
-
# LOAD
|
| 304 |
# =========================
|
| 305 |
print("Loading model...")
|
| 306 |
pipe = pipeline(
|
| 307 |
"text-generation",
|
| 308 |
-
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 309 |
-
# model="Qwen/Qwen2.5-1.5B-Instruct", # Uncomment if you prefer 1.5B
|
| 310 |
device="cpu"
|
| 311 |
)
|
| 312 |
|
| 313 |
# =========================
|
| 314 |
-
# TOKEN
|
| 315 |
# =========================
|
| 316 |
-
def
|
| 317 |
global access_token
|
| 318 |
-
|
| 319 |
-
|
| 320 |
token_url,
|
| 321 |
data={"grant_type": "client_credentials"},
|
| 322 |
auth=(client_id, client_secret)
|
| 323 |
)
|
| 324 |
-
|
| 325 |
-
|
| 326 |
return None
|
| 327 |
-
|
| 328 |
-
|
| 329 |
return access_token
|
| 330 |
|
| 331 |
# =========================
|
| 332 |
-
# FETCH
|
| 333 |
# =========================
|
| 334 |
-
def
|
| 335 |
global access_token
|
|
|
|
| 336 |
if not access_token:
|
| 337 |
-
|
| 338 |
-
|
| 339 |
headers = {
|
| 340 |
"Authorization": f"Bearer {access_token}",
|
| 341 |
"Accept": "application/json"
|
| 342 |
}
|
| 343 |
-
|
| 344 |
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 345 |
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 346 |
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
| 347 |
res4 = requests.get(cap_service_url_saleorderitems, headers=headers)
|
| 348 |
|
| 349 |
# Retry if token expired
|
| 350 |
-
if res1.status_code in [
|
| 351 |
-
print("Token expired. Regenerating...")
|
| 352 |
access_token = None
|
| 353 |
-
|
| 354 |
headers["Authorization"] = f"Bearer {access_token}"
|
|
|
|
| 355 |
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 356 |
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 357 |
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
|
@@ -359,106 +355,116 @@ def fetch_sap_data():
|
|
| 359 |
|
| 360 |
df_customers = pd.DataFrame(res1.json()["value"])
|
| 361 |
df_products = pd.DataFrame(res2.json()["value"])
|
| 362 |
-
|
| 363 |
-
|
| 364 |
|
| 365 |
-
#
|
| 366 |
-
df_customers = df_customers[["ID",
|
| 367 |
-
df_products = df_products[["ID",
|
| 368 |
-
|
| 369 |
-
|
| 370 |
|
| 371 |
-
return df_customers, df_products,
|
| 372 |
|
| 373 |
# =========================
|
| 374 |
-
# CACHE
|
| 375 |
# =========================
|
| 376 |
-
def
|
| 377 |
-
global
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
last_refresh = time.time()
|
| 382 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
| 384 |
# =========================
|
| 385 |
-
# MAIN FUNCTION
|
| 386 |
# =========================
|
| 387 |
-
def generate_response(
|
| 388 |
try:
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
#
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
return_full_text=False
|
| 418 |
-
)
|
| 419 |
-
|
| 420 |
-
generated_code = result[0]["generated_text"].strip()
|
| 421 |
-
|
| 422 |
-
# Clean possible code fences
|
| 423 |
-
if generated_code.startswith("```"):
|
| 424 |
-
generated_code = generated_code.split("\n", 1)[1]
|
| 425 |
-
if "```" in generated_code:
|
| 426 |
-
generated_code = generated_code.split("```")[0]
|
| 427 |
-
|
| 428 |
-
# Execute the generated code safely
|
| 429 |
-
local_vars = {
|
| 430 |
-
"df_customers": df_customers,
|
| 431 |
-
"df_products": df_products,
|
| 432 |
-
"df_saleorders": df_saleorders,
|
| 433 |
-
"df_saleorderitems": df_saleorderitems,
|
| 434 |
-
"pd": pd
|
| 435 |
-
}
|
| 436 |
-
|
| 437 |
-
output_buffer = io.StringIO()
|
| 438 |
-
with redirect_stdout(output_buffer):
|
| 439 |
-
exec(generated_code, {"__builtins__": {}}, local_vars)
|
| 440 |
-
|
| 441 |
-
response = output_buffer.getvalue().strip()
|
| 442 |
-
return response if response else "No records found."
|
| 443 |
|
| 444 |
except Exception as e:
|
| 445 |
-
return f"Error: {str(e)}
|
| 446 |
|
| 447 |
# =========================
|
| 448 |
-
# GRADIO UI
|
| 449 |
# =========================
|
| 450 |
with gr.Blocks() as demo:
|
| 451 |
-
gr.Markdown("# SAP
|
| 452 |
-
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
btn = gr.Button("Generate")
|
| 455 |
|
| 456 |
btn.click(
|
| 457 |
fn=generate_response,
|
| 458 |
-
inputs=
|
| 459 |
-
outputs=output
|
| 460 |
-
api_name="predict"
|
| 461 |
)
|
| 462 |
|
| 463 |
-
demo.queue()
|
| 464 |
demo.launch()
|
|
|
|
| 268 |
|
| 269 |
# demo.launch()
|
| 270 |
|
| 271 |
+
|
| 272 |
+
|
| 273 |
import gradio as gr
|
| 274 |
from transformers import pipeline
|
| 275 |
import requests
|
|
|
|
| 276 |
import pandas as pd
|
| 277 |
import time
|
|
|
|
|
|
|
| 278 |
|
| 279 |
# =========================
|
| 280 |
+
# SAP CONFIG
|
| 281 |
# =========================
|
| 282 |
+
client_id = "YOUR_CLIENT_ID"
|
| 283 |
+
client_secret = "YOUR_CLIENT_SECRET"
|
| 284 |
+
token_url = "YOUR_TOKEN_URL"
|
| 285 |
|
| 286 |
+
cap_service_url_customers = "YOUR_URL/Customers"
|
| 287 |
+
cap_service_url_products = "YOUR_URL/Products"
|
| 288 |
+
cap_service_url_saleorders = "YOUR_URL/SalesOrders"
|
| 289 |
+
cap_service_url_saleorderitems = "YOUR_URL/SalesOrderItems"
|
| 290 |
|
| 291 |
# =========================
|
| 292 |
+
# GLOBAL CACHE
|
| 293 |
# =========================
|
| 294 |
access_token = None
|
| 295 |
+
cached_data = None
|
|
|
|
|
|
|
|
|
|
| 296 |
last_refresh = 0
|
| 297 |
|
| 298 |
# =========================
|
| 299 |
+
# LOAD SMALL FAST MODEL
|
| 300 |
# =========================
|
| 301 |
print("Loading model...")
|
| 302 |
pipe = pipeline(
|
| 303 |
"text-generation",
|
| 304 |
+
model="Qwen/Qwen2.5-0.5B-Instruct", # β‘ faster than 1.5B
|
|
|
|
| 305 |
device="cpu"
|
| 306 |
)
|
| 307 |
|
| 308 |
# =========================
|
| 309 |
+
# TOKEN GENERATION
|
| 310 |
# =========================
|
| 311 |
+
def generate_token():
|
| 312 |
global access_token
|
| 313 |
+
|
| 314 |
+
response = requests.post(
|
| 315 |
token_url,
|
| 316 |
data={"grant_type": "client_credentials"},
|
| 317 |
auth=(client_id, client_secret)
|
| 318 |
)
|
| 319 |
+
|
| 320 |
+
if response.status_code != 200:
|
| 321 |
return None
|
| 322 |
+
|
| 323 |
+
access_token = response.json().get("access_token")
|
| 324 |
return access_token
|
| 325 |
|
| 326 |
# =========================
|
| 327 |
+
# FETCH DATA
|
| 328 |
# =========================
|
| 329 |
+
def fetch_data():
|
| 330 |
global access_token
|
| 331 |
+
|
| 332 |
if not access_token:
|
| 333 |
+
generate_token()
|
| 334 |
+
|
| 335 |
headers = {
|
| 336 |
"Authorization": f"Bearer {access_token}",
|
| 337 |
"Accept": "application/json"
|
| 338 |
}
|
| 339 |
+
|
| 340 |
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 341 |
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 342 |
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
| 343 |
res4 = requests.get(cap_service_url_saleorderitems, headers=headers)
|
| 344 |
|
| 345 |
# Retry if token expired
|
| 346 |
+
if res1.status_code in [401, 403]:
|
|
|
|
| 347 |
access_token = None
|
| 348 |
+
generate_token()
|
| 349 |
headers["Authorization"] = f"Bearer {access_token}"
|
| 350 |
+
|
| 351 |
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 352 |
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 353 |
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
|
|
|
| 355 |
|
| 356 |
df_customers = pd.DataFrame(res1.json()["value"])
|
| 357 |
df_products = pd.DataFrame(res2.json()["value"])
|
| 358 |
+
df_orders = pd.DataFrame(res3.json()["value"])
|
| 359 |
+
df_items = pd.DataFrame(res4.json()["value"])
|
| 360 |
|
| 361 |
+
# Select columns
|
| 362 |
+
df_customers = df_customers[["ID","name","country","industry"]]
|
| 363 |
+
df_products = df_products[["ID","name","category","price","currency"]]
|
| 364 |
+
df_orders = df_orders[["ID","customer_ID","orderDate","status"]]
|
| 365 |
+
df_items = df_items[["ID","parent_ID","product_ID","quantity","netAmount"]]
|
| 366 |
|
| 367 |
+
return df_customers, df_products, df_orders, df_items
|
| 368 |
|
| 369 |
# =========================
|
| 370 |
+
# CACHE
|
| 371 |
# =========================
|
| 372 |
+
def get_data():
|
| 373 |
+
global cached_data, last_refresh
|
| 374 |
+
|
| 375 |
+
if cached_data is None or time.time() - last_refresh > 300:
|
| 376 |
+
cached_data = fetch_data()
|
| 377 |
last_refresh = time.time()
|
| 378 |
+
|
| 379 |
+
return cached_data
|
| 380 |
+
|
| 381 |
+
# =========================
|
| 382 |
+
# FORMAT FUNCTION
|
| 383 |
+
# =========================
|
| 384 |
+
def format_table(df):
|
| 385 |
+
if df.empty:
|
| 386 |
+
return "β No data found"
|
| 387 |
+
return df.to_markdown(index=False)
|
| 388 |
+
|
| 389 |
+
# =========================
|
| 390 |
+
# LLM (ONLY FOR COMPLEX)
|
| 391 |
+
# =========================
|
| 392 |
+
def call_llm(question, context):
|
| 393 |
+
messages = [
|
| 394 |
+
{"role": "system", "content": "Answer strictly based on data. Be short."},
|
| 395 |
+
{"role": "user", "content": f"Data:\n{context}\n\nQuestion: {question}"}
|
| 396 |
+
]
|
| 397 |
+
|
| 398 |
+
prompt = pipe.tokenizer.apply_chat_template(
|
| 399 |
+
messages,
|
| 400 |
+
tokenize=False,
|
| 401 |
+
add_generation_prompt=True
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
result = pipe(
|
| 405 |
+
prompt,
|
| 406 |
+
max_new_tokens=60,
|
| 407 |
+
do_sample=False # β‘ fast + deterministic
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
return result[0]["generated_text"].strip()
|
| 411 |
|
| 412 |
# =========================
|
| 413 |
+
# MAIN FUNCTION
|
| 414 |
# =========================
|
| 415 |
+
def generate_response(user_input):
|
| 416 |
try:
|
| 417 |
+
df_customers, df_products, df_orders, df_items = get_data()
|
| 418 |
+
query = user_input.lower()
|
| 419 |
+
|
| 420 |
+
# =====================
|
| 421 |
+
# DIRECT (NO LLM)
|
| 422 |
+
# =====================
|
| 423 |
+
if "customer" in query:
|
| 424 |
+
return "### π₯ Customers\n\n" + format_table(df_customers)
|
| 425 |
+
|
| 426 |
+
elif "product" in query:
|
| 427 |
+
return "### π¦ Products\n\n" + format_table(df_products)
|
| 428 |
+
|
| 429 |
+
elif "order item" in query:
|
| 430 |
+
return "### π§Ύ Order Items\n\n" + format_table(df_items)
|
| 431 |
+
|
| 432 |
+
elif "order" in query:
|
| 433 |
+
return "### π Orders\n\n" + format_table(df_orders)
|
| 434 |
+
|
| 435 |
+
# =====================
|
| 436 |
+
# π€ COMPLEX QUERY
|
| 437 |
+
# =====================
|
| 438 |
+
else:
|
| 439 |
+
# Send minimal context
|
| 440 |
+
context = df_orders.head(5).to_markdown(index=False)
|
| 441 |
+
|
| 442 |
+
answer = call_llm(user_input, context)
|
| 443 |
+
|
| 444 |
+
return f"### π€ Answer\n\n{answer}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
| 446 |
except Exception as e:
|
| 447 |
+
return f"β Error: {str(e)}"
|
| 448 |
|
| 449 |
# =========================
|
| 450 |
+
# GRADIO UI
|
| 451 |
# =========================
|
| 452 |
with gr.Blocks() as demo:
|
| 453 |
+
gr.Markdown("# π SAP Smart Assistant")
|
| 454 |
+
|
| 455 |
+
user_input = gr.Textbox(
|
| 456 |
+
label="Ask your question",
|
| 457 |
+
placeholder="e.g. show customers, list products..."
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
output = gr.Markdown(label="Response")
|
| 461 |
+
|
| 462 |
btn = gr.Button("Generate")
|
| 463 |
|
| 464 |
btn.click(
|
| 465 |
fn=generate_response,
|
| 466 |
+
inputs=user_input,
|
| 467 |
+
outputs=output
|
|
|
|
| 468 |
)
|
| 469 |
|
|
|
|
| 470 |
demo.launch()
|