Spaces:
Runtime error
Runtime error
File size: 12,612 Bytes
5536b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | from click import prompt
from langchain_core.runnables import RunnableParallel
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from streamlit import text_input
from langchain_community.vectorstores import FAISS
from langchain_ollama import OllamaEmbeddings
from langchain_ollama import ChatOllama
from langchain_core.prompts import PromptTemplate
from ollama import chat
from langchain_core.runnables import RunnableParallel
#### ************************************************************************************SQL***********************************************************************************
def sql_text(text_input):
embedding = OllamaEmbeddings(model="nomic-embed-text")
vector_store = FAISS.load_local(
"faiss_index",
embedding,
allow_dangerous_deserialization=True
)
retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 1})
llm = ChatOllama(
model="llama3.2",
temperature=0
)
prompt = PromptTemplate(
template="""
You are an SQL assistant.
Use ONLY the provided context.
Rules:
1. If the SQL query exists in the context, return ONLY that SQL query.
2. Do not explain.
3. Do not rewrite the question.
4. Do not generate a new query.
5. If the SQL query is missing, reply exactly:
I don't know.
Context:
{context}
Question:
{question}
SQL:
""",
input_variables=["context", "question"],
)
parallel_chain = RunnableParallel({
'context': retriever ,
'question': RunnablePassthrough()
})
parser = StrOutputParser()
main_chain = parallel_chain | prompt | llm | parser
response = main_chain.invoke(text_input)
return response
# def image_input( image_path):
# system_prompt = """
# Act as an expert OCR and data extraction assistant.
# Please format your response clearly using the following headings:
# ### User Statement
# Extract the introductory text written by the user at the very top of the image.
# ### Question Description
# Extract the problem statement from the left-hand panel under the Description tab.
# ### SQL Query
# Extract the exact SQL code written inside the dark-themed code editor on the right.
# ### Error Message
# Extract the red error message displayed at the bottom right.
# """
# response = chat(
# model="qwen2.5vl:7b",
# messages=[
# {
# "role": "system",
# "content": system_prompt
# },
# {
# "role": "user",
# "content": "Extract all requested information from this image.",
# "images": ["sql_eorror.png"]
# }
# ]
# )
# response_image_test =response.message.content
# llm = ChatOllama(
# model="llama3.2",
# temperature=0
# )
# embedding = OllamaEmbeddings(model="nomic-embed-text")
# vector_store = FAISS.load_local(
# "faiss_index",
# embedding,
# allow_dangerous_deserialization=True
# )
# retriever = vector_store.as_retriever(
# search_type="similarity",
# search_kwargs={"k": 1}
# )
# prompt = PromptTemplate(
# template="""
# You are an SQL assistant.
# Use ONLY the provided context.
# Rules:
# 1. If the SQL query exists in the context, return ONLY that SQL query.
# 2. Do not explain.
# 3. Do not rewrite the question.
# 4. Do not generate a new query.
# 5. If the SQL query is missing, reply exactly:
# I don't know.
# Context:
# {context}
# Question:
# {question}
# SQL:
# """,
# input_variables=["context", "question"],
# )
# parallel_chain = RunnableParallel({
# 'context': retriever ,
# 'question': RunnablePassthrough()
# })
# parser = StrOutputParser()
# main_chain = parallel_chain | prompt | llm | parser
# response = main_chain.invoke(response_image_test)
# return response
def sql_image(image_path):
# --------------------------------------------------
# STEP 1 : Extract ONLY the SQL question
# --------------------------------------------------
system_prompt = """
You are an OCR assistant.
Your job is to read the screenshot and extract ONLY the SQL problem statement.
Rules:
- Ignore the SQL editor.
- Ignore the error message.
- Ignore buttons.
- Ignore the database output.
- Ignore everything except the Question Description.
Return ONLY the question text.
Do not add headings.
Do not explain anything.
"""
response = chat(
model="qwen2.5vl:7b",
messages=[
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": "Extract only the SQL question.",
"images": [image_path]
}
]
)
extracted_question = response.message.content.strip()
print("\nExtracted Question:\n")
print(extracted_question)
# --------------------------------------------------
# STEP 2 : Load LLM
# --------------------------------------------------
llm = ChatOllama(
model="llama3.2",
temperature=0
)
# --------------------------------------------------
# STEP 3 : Load Embeddings
# --------------------------------------------------
embedding = OllamaEmbeddings(
model="nomic-embed-text"
)
vector_store = FAISS.load_local(
"faiss_index",
embedding,
allow_dangerous_deserialization=True
)
retriever = vector_store.as_retriever(
search_type="similarity",
search_kwargs={"k":3}
)
# --------------------------------------------------
# STEP 4 : Prompt
# --------------------------------------------------
prompt = PromptTemplate(
template="""
You are an SQL assistant.
Use ONLY the retrieved context.
Rules:
1. Return ONLY the SQL query.
2. No explanation.
3. No markdown.
4. Do not rewrite the question.
5. If the answer is not present in the context, reply exactly:
I don't know.
Context:
{context}
Question:
{question}
SQL:
""",
input_variables=["context", "question"],
)
# --------------------------------------------------
# STEP 5 : Chain
# --------------------------------------------------
parallel_chain = RunnableParallel(
{
"context": retriever,
"question": RunnablePassthrough()
}
)
parser = StrOutputParser()
main_chain = (
parallel_chain
| prompt
| llm
| parser
)
# --------------------------------------------------
# STEP 6 : Retrieve using ONLY the extracted question
# --------------------------------------------------
response = main_chain.invoke(extracted_question)
return response
def sql_text_image(question, image_path):
# --------------------------------------------------
# STEP 1 : Extract ONLY the SQL question from the image
# --------------------------------------------------
sql_answer1 = sql_image(image_path)
sql_answer2 = sql_text(question)
# --------------------------------------------------
# STEP 2 : Combine the extracted question and the text input
# --------------------------------------------------
# Build the Parallel Chain
prompt = f"""
You are an SQL expert.
Image SQL:
{sql_answer1}
User Question:
{sql_answer2}
Use BOTH pieces of information to produce the final SQL answer.
Output exactly in this format:
Kindly go through the provided information.
<final_answer> -> By Prince Kushwaha
Do not include any explanation or markdown.
Replace <final_answer> with the actual SQL answer.
"""
llm = ChatOllama(
model="llama3.2",
temperature=0
)
response = llm.invoke(prompt)
return response.content
### *************************************************************************Excel**************************************************************************
def excel_text(question):
# Load LLM
llm = ChatOllama(
model="llama3.2",
temperature=0
)
# Prompt
prompt = PromptTemplate(
template="""
You are an Excel expert.
Answer the following Excel question.
Rules:
1. Return only the final answer.
2. If the answer is an Excel formula, return only the formula.
3. Do not use markdown.
4. Keep the answer concise.
Question:
{question}
Answer:
""",
input_variables=["question"],
)
# Output Parser
parser = StrOutputParser()
# Chain
main_chain = prompt | llm | parser
# Generate Response
response = main_chain.invoke({
"question": text_input
})
return response.content.strip()
def excel_image(image_path):
# --------------------------------------------------
# STEP 1 : Extract ONLY the Excel question
# --------------------------------------------------
system_prompt = """
You are an OCR assistant.
Your task is to read the screenshot and extract ONLY the Excel question.
Rules:
- Ignore the Excel ribbon.
- Ignore row and column headers.
- Ignore formulas already written.
- Ignore buttons and menus.
- Ignore answer choices if not part of the question.
- Return ONLY the question text.
Do not explain anything.
Do not add headings.
"""
response = chat(
model="qwen2.5vl:7b",
messages=[
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": "Extract only the Excel question.",
"images": [image_path]
}
]
)
extracted_question = response.message.content.strip()
print("\nExtracted Question:\n")
print(extracted_question)
# --------------------------------------------------
# STEP 2 : Load LLM
# --------------------------------------------------
llm = ChatOllama(
model="llama3.2",
temperature=0
)
# --------------------------------------------------
# STEP 3 : Prompt
# --------------------------------------------------
prompt = PromptTemplate(
template="""
You are an Excel expert.
Answer the following Excel question.
Rules:
1. Provide the correct answer only.
2. If a formula is required, return only the formula.
3. If an explanation is required, keep it concise.
4. Do not use markdown.
Question:
{question}
Answer:
""",
input_variables=["question"],
)
parser = StrOutputParser()
chain = prompt | llm | parser
# --------------------------------------------------
# STEP 4 : Generate Answer
# --------------------------------------------------
answer = chain.invoke({
"question": extracted_question
})
return answer
def excel_text_image(question, image_path):
"""
question : Extracted text from OCR
image_path : Path to the Excel screenshot (optional, not used here)
"""
# Load LLM
llm = ChatOllama(
model="llama3.2",
temperature=0
)
# Prompt
prompt = PromptTemplate(
template="""
You are an Excel expert.
Answer the following Excel question.
Rules:
1. Return only the final answer.
2. If the answer is an Excel formula, return only the formula.
3. If the question asks for a value, return only the value.
4. If an explanation is needed, keep it brief.
5. Do not use markdown.
Question:
{question}
Answer:
""",
input_variables=["question"],
)
parser = StrOutputParser()
# Chain
chain = prompt | llm | parser
# Generate answer
response = chain.invoke({
"question": question
})
return response |