Spaces:
Sleeping
Sleeping
Update function/chat.py
Browse files- function/chat.py +863 -860
function/chat.py
CHANGED
|
@@ -1,860 +1,863 @@
|
|
| 1 |
-
from langchain_community.utilities.sql_database import SQLDatabase
|
| 2 |
-
from langchain_experimental.sql import SQLDatabaseChain
|
| 3 |
-
import sys
|
| 4 |
-
import os
|
| 5 |
-
import pymysql
|
| 6 |
-
from fastapi import HTTPException
|
| 7 |
-
from fastapi.encoders import jsonable_encoder
|
| 8 |
-
import re
|
| 9 |
-
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".")))
|
| 10 |
-
import prompt.prompt_main as prompt
|
| 11 |
-
import prompt.prompt_custom as prompt_cus
|
| 12 |
-
os.environ["GOOGLE_API_KEY"] = "AIzaSyBoPdVLTJNxfDg9wxWDpY4QJezHiyjKbTE"
|
| 13 |
-
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 14 |
-
from bson import ObjectId
|
| 15 |
-
import os
|
| 16 |
-
from dotenv import load_dotenv
|
| 17 |
-
import os
|
| 18 |
-
from dotenv import load_dotenv
|
| 19 |
-
from dotenv import load_dotenv, find_dotenv
|
| 20 |
-
load_dotenv(find_dotenv(), override=True)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
DB_HOST = os.getenv("DB_HOST")
|
| 25 |
-
DB_USER = os.getenv("DB_USER")
|
| 26 |
-
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
| 27 |
-
DB_NAME = os.getenv("DB_NAME")
|
| 28 |
-
DB_PORT = os.getenv("DB_PORT")
|
| 29 |
-
# Tạo connection string
|
| 30 |
-
import os
|
| 31 |
-
from urllib.parse import quote
|
| 32 |
-
|
| 33 |
-
password = os.getenv("DB_PASSWORD") # VD: 'Yahana0509@'
|
| 34 |
-
DB_PASSWORD = quote(password)
|
| 35 |
-
connection_uri =
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
import
|
| 42 |
-
import
|
| 43 |
-
|
| 44 |
-
import
|
| 45 |
-
|
| 46 |
-
import
|
| 47 |
-
import
|
| 48 |
-
import
|
| 49 |
-
import
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
import
|
| 72 |
-
import
|
| 73 |
-
import
|
| 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 |
-
for
|
| 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 |
-
" (1054, \"Unknown column '
|
| 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 |
-
match = re.search(r"
|
| 269 |
-
if match:
|
| 270 |
-
return clean_sql(match.group(1))
|
| 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 |
-
if
|
| 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 |
-
if
|
| 477 |
-
raise HTTPException(status_code=400, detail="
|
| 478 |
-
|
| 479 |
-
if not
|
| 480 |
-
raise HTTPException(status_code=400, detail="
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
if
|
| 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 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
"
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
)
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
if
|
| 613 |
-
raise HTTPException(status_code=400, detail="
|
| 614 |
-
|
| 615 |
-
if not
|
| 616 |
-
raise HTTPException(status_code=400, detail="
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
if
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
#
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
#
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
#
|
| 672 |
-
#
|
| 673 |
-
#
|
| 674 |
-
#
|
| 675 |
-
#
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
"
|
| 690 |
-
"
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
"
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
if
|
| 717 |
-
raise HTTPException(status_code=400, detail="User not found or has been deleted in
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
"
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
import
|
| 777 |
-
from
|
| 778 |
-
from function.analyze
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
if
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
if
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
code_clean =
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
result_check
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_community.utilities.sql_database import SQLDatabase
|
| 2 |
+
from langchain_experimental.sql import SQLDatabaseChain
|
| 3 |
+
import sys
|
| 4 |
+
import os
|
| 5 |
+
import pymysql
|
| 6 |
+
from fastapi import HTTPException
|
| 7 |
+
from fastapi.encoders import jsonable_encoder
|
| 8 |
+
import re
|
| 9 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".")))
|
| 10 |
+
import prompt.prompt_main as prompt
|
| 11 |
+
import prompt.prompt_custom as prompt_cus
|
| 12 |
+
os.environ["GOOGLE_API_KEY"] = "AIzaSyBoPdVLTJNxfDg9wxWDpY4QJezHiyjKbTE"
|
| 13 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 14 |
+
from bson import ObjectId
|
| 15 |
+
import os
|
| 16 |
+
from dotenv import load_dotenv
|
| 17 |
+
import os
|
| 18 |
+
from dotenv import load_dotenv
|
| 19 |
+
from dotenv import load_dotenv, find_dotenv
|
| 20 |
+
load_dotenv(find_dotenv(), override=True)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
DB_HOST = os.getenv("DB_HOST")
|
| 25 |
+
DB_USER = os.getenv("DB_USER")
|
| 26 |
+
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
| 27 |
+
DB_NAME = os.getenv("DB_NAME")
|
| 28 |
+
DB_PORT = os.getenv("DB_PORT")
|
| 29 |
+
# Tạo connection string
|
| 30 |
+
import os
|
| 31 |
+
from urllib.parse import quote
|
| 32 |
+
|
| 33 |
+
password = os.getenv("DB_PASSWORD") # VD: 'Yahana0509@'
|
| 34 |
+
DB_PASSWORD = quote(password)
|
| 35 |
+
connection_uri = (
|
| 36 |
+
f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
| 37 |
+
"?ssl_verify_cert=false&ssl_verify_identity=false"
|
| 38 |
+
)
|
| 39 |
+
db = SQLDatabase.from_uri(connection_uri)
|
| 40 |
+
from dotenv import load_dotenv
|
| 41 |
+
import filter.filter_role as filter_role_1
|
| 42 |
+
import filter.filter_sql_injection as filter_sql_injection_1
|
| 43 |
+
import filter.result as query_result_1
|
| 44 |
+
import support.get_key as get_key
|
| 45 |
+
import response.ResponseChat as res_chat
|
| 46 |
+
from datetime import datetime
|
| 47 |
+
import pytz
|
| 48 |
+
from mongoengine import connect
|
| 49 |
+
import sys
|
| 50 |
+
import os
|
| 51 |
+
import nltk
|
| 52 |
+
import function.agent.pipeline_agent as pipeline_agent
|
| 53 |
+
nltk.download('punkt')
|
| 54 |
+
from models.Database_Entity import User, ChatHistory, DetailChat
|
| 55 |
+
from dotenv import load_dotenv
|
| 56 |
+
load_dotenv()
|
| 57 |
+
MONGO_URI = os.getenv("MONGO_URI", "")
|
| 58 |
+
connect("chatbot_hmdrinks", host=MONGO_URI)
|
| 59 |
+
|
| 60 |
+
load_dotenv()
|
| 61 |
+
|
| 62 |
+
#setup model
|
| 63 |
+
from bson import ObjectId
|
| 64 |
+
import random
|
| 65 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
|
| 70 |
+
sys.path.insert(0, BASE_DIR)
|
| 71 |
+
from repository.MySQL import UserRepository
|
| 72 |
+
from prompt.prompt_syntax_insert import is_insert_related_to_product_category_variant, filter_syntax_sql
|
| 73 |
+
import sqlparse
|
| 74 |
+
import re
|
| 75 |
+
import sys
|
| 76 |
+
import os
|
| 77 |
+
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '..')))
|
| 78 |
+
from prompt import prompt_detail_table
|
| 79 |
+
|
| 80 |
+
schema_mapping = {
|
| 81 |
+
"user": prompt_detail_table.prompt_users,
|
| 82 |
+
"user_voucher": prompt_detail_table.prompt_user_voucher,
|
| 83 |
+
"category": prompt_detail_table.prompt_categort,
|
| 84 |
+
"category_translation": prompt_detail_table.prompt_category_translation,
|
| 85 |
+
"cart": prompt_detail_table.prompt_cart,
|
| 86 |
+
"cart_item": prompt_detail_table.prompt_cart_item,
|
| 87 |
+
"orders":prompt_detail_table.prompt_orders,
|
| 88 |
+
"order_item": prompt_detail_table.prompt_order_item,
|
| 89 |
+
"payment": prompt_detail_table.prompt_payments,
|
| 90 |
+
"payments": prompt_detail_table.prompt_payments,
|
| 91 |
+
"favourite": prompt_detail_table.prompt_favourite,
|
| 92 |
+
"favourite_item": prompt_detail_table.prompt_fav_item,
|
| 93 |
+
"post": prompt_detail_table.prompt_post,
|
| 94 |
+
"post_translation": prompt_detail_table.prompt_post_translation,
|
| 95 |
+
"product": prompt_detail_table.prompt_product,
|
| 96 |
+
"product_translation": prompt_detail_table.prompt_product_translation,
|
| 97 |
+
"shipment": prompt_detail_table.prompt_shipment,
|
| 98 |
+
"product_variants": prompt_detail_table.prompt_product_variants,
|
| 99 |
+
"review": prompt_detail_table.prompt_review,
|
| 100 |
+
"user_coin": prompt_detail_table.prompt_user_coin,
|
| 101 |
+
"absence": prompt_detail_table.prompt_absence,
|
| 102 |
+
"cart_group": prompt_detail_table.prompt_cart_group,
|
| 103 |
+
"cart_item_group": prompt_detail_table.prompt_cartitem_group,
|
| 104 |
+
"group_orders": prompt_detail_table.prompt_group_orders,
|
| 105 |
+
"payments_group": prompt_detail_table.prompt_payments_group,
|
| 106 |
+
"group_order_members":prompt_detail_table.prompt_group_orders_member,
|
| 107 |
+
"shipment_group":prompt_detail_table.prompt_shipment_group,
|
| 108 |
+
"shipper_attendance":prompt_detail_table.prompt_shipper_attendance,
|
| 109 |
+
"shipper_commission_detail":prompt_detail_table.prompt_shipper_commission_detail,
|
| 110 |
+
"shipper_salary_summary":prompt_detail_table.prompt_shipper_salary_summary,
|
| 111 |
+
"voucher": prompt_detail_table.prompt_voucher
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_schemas_from_sql(sql_query: str, schema_mapping: dict):
|
| 116 |
+
import sqlglot
|
| 117 |
+
|
| 118 |
+
parsed_query = sqlglot.parse_one(sql_query, read="mysql")
|
| 119 |
+
|
| 120 |
+
# Lấy danh sách bảng duy nhất trong query
|
| 121 |
+
table_names = list({t.name for t in parsed_query.find_all(sqlglot.exp.Table)})
|
| 122 |
+
|
| 123 |
+
schemas_used = {}
|
| 124 |
+
for table in table_names:
|
| 125 |
+
if table in schema_mapping:
|
| 126 |
+
schemas_used[table] = schema_mapping[table]
|
| 127 |
+
else:
|
| 128 |
+
print(f"⚠️ Warning: Table '{table}' not found in schema_mapping")
|
| 129 |
+
|
| 130 |
+
# Gom toàn bộ schema thành 1 chuỗi duy nhất
|
| 131 |
+
all_schemas = "\n\n".join(
|
| 132 |
+
[f"Schema for table '{table}':\n{schemas_used[table]}" for table in schemas_used]
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
return all_schemas
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def build_sql_fix_prompt(schemas_result: dict, sql: str) -> str:
|
| 139 |
+
|
| 140 |
+
prompt = f"""
|
| 141 |
+
Bạn là một chuyên gia cơ sở dữ liệu.
|
| 142 |
+
|
| 143 |
+
Dưới đây là mô tả schema chi tiết của các bảng có trong hệ thống:
|
| 144 |
+
Đọc rõ và ghi nhớ tùng thuộc tính của mỗi bảng mà bạn truy vấn:
|
| 145 |
+
{schemas_result}
|
| 146 |
+
|
| 147 |
+
---
|
| 148 |
+
|
| 149 |
+
Dưới đây là một câu SQL đang bị lỗi do không đúng tên bảng hoặc tên cột:
|
| 150 |
+
|
| 151 |
+
```sql
|
| 152 |
+
{sql.strip()}
|
| 153 |
+
Yêu cầu của bạn là:
|
| 154 |
+
|
| 155 |
+
Dựa trên các schema ở trên, hãy kiểm tra và chỉnh sửa câu SQL sao cho:
|
| 156 |
+
Tên bảng, tên cột(thuộc tính) phải chính xác theo trình bày bên trong schema.
|
| 157 |
+
Nếu tên cột trong bảng đó có mô tả trong schema mà trình bày khác thì phải thay đổi sao cho cú pháp sql chính xác.
|
| 158 |
+
Logic và mục đích của truy vấn được giữ nguyên.
|
| 159 |
+
Chỉ trả lại phần SQL đã được chỉnh sửa (không giải thích, không chú thích, không thêm nhận xét).
|
| 160 |
+
Trả lời dưới dạng một truy vấn SQL duy nhất.
|
| 161 |
+
Không dùng pt.`language_ code` = 'EN
|
| 162 |
+
Với các câu hỏi liên quan đến product luôn trả về kèm theo pro_id cho mình.
|
| 163 |
+
- "- Tránh các lỗi như :\n"
|
| 164 |
+
" (1054, \"Unknown column 'oi.pro_id' in 'field list'\")\n . Luôn đảm bảo bạn không bao giờ bị lỗi này"
|
| 165 |
+
" (1054, \"Unknown column 'oi.note' in 'field list'\") . Luôn đảm bảo bạn không bao giờ bị lỗi này\n"
|
| 166 |
+
" (1054, \"Unknown column 'oi.size' in 'field list'\") . Luôn đảm bảo bạn không bao giờ bị lỗi này \n"
|
| 167 |
+
" (1054, \"Unknown column 'c.is_deleted' in 'on clause'\"). Luôn đảm bảo bạn không bao giờ bị lỗi này\n"
|
| 168 |
+
""".strip()
|
| 169 |
+
return prompt
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def contains_delete(sql: str) -> bool:
|
| 173 |
+
return bool(re.search(r'\bdelete\b', sql, re.IGNORECASE))
|
| 174 |
+
|
| 175 |
+
async def execute_query_user(user_input: str, user_id: int, languages: str, role: str):
|
| 176 |
+
api_key = get_key.get_random_api_key()
|
| 177 |
+
os.environ["GOOGLE_API_KEY"] = api_key
|
| 178 |
+
llm1 = ChatGoogleGenerativeAI(model='gemini-2.0-flash-thinking-exp-01-21',temperature=0.2)
|
| 179 |
+
db = SQLDatabase.from_uri(connection_uri)
|
| 180 |
+
PROMPT_CUSTOM = await prompt_cus.get_prompt_custom(user_input)
|
| 181 |
+
check_insert = is_insert_related_to_product_category_variant(user_input)
|
| 182 |
+
|
| 183 |
+
db_config = {
|
| 184 |
+
"host": os.getenv("DB_HOST"),
|
| 185 |
+
"user": os.getenv("DB_USER"),
|
| 186 |
+
"database": os.getenv("DB_NAME"),
|
| 187 |
+
"password": os.getenv("DB_PASSWORD"),
|
| 188 |
+
"port": int(os.getenv("DB_PORT", 3306)),
|
| 189 |
+
"charset": "utf8mb4",
|
| 190 |
+
"cursorclass": pymysql.cursors.DictCursor,
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
def regenerate_sql_until_safe():
|
| 194 |
+
max_retry = 5
|
| 195 |
+
retry_count = 0
|
| 196 |
+
|
| 197 |
+
while retry_count < max_retry:
|
| 198 |
+
try:
|
| 199 |
+
regenerated_data = db_chain.run(f"""
|
| 200 |
+
Role: {text_role}
|
| 201 |
+
Language: {languages}
|
| 202 |
+
Question: {user_input}.
|
| 203 |
+
""")
|
| 204 |
+
regenerated_sql = extract_sql_from_response(regenerated_data)
|
| 205 |
+
if regenerated_sql:
|
| 206 |
+
regenerated_sql = clean_sql(regenerated_sql)
|
| 207 |
+
if not re.search(r"%{1,2}s", regenerated_sql): # đã sạch
|
| 208 |
+
return regenerated_sql
|
| 209 |
+
retry_count += 1
|
| 210 |
+
except Exception as e:
|
| 211 |
+
return f"❌ Lỗi khi tạo lại truy vấn lần {retry_count + 1}: {str(e)}"
|
| 212 |
+
return "❌ Lỗi: Không thể tạo được truy vấn an toàn sau nhiều lần thử."
|
| 213 |
+
def execute_query_with_pymysql(query, multi=False):
|
| 214 |
+
connection = pymysql.connect(**db_config)
|
| 215 |
+
try:
|
| 216 |
+
with connection.cursor() as cursor:
|
| 217 |
+
results = []
|
| 218 |
+
if multi:
|
| 219 |
+
statements = sqlparse.split(query)
|
| 220 |
+
for stmt in statements:
|
| 221 |
+
stmt = stmt.strip()
|
| 222 |
+
if stmt:
|
| 223 |
+
try:
|
| 224 |
+
cursor.execute(stmt)
|
| 225 |
+
try:
|
| 226 |
+
results.append(cursor.fetchall())
|
| 227 |
+
except pymysql.ProgrammingError:
|
| 228 |
+
results.append("✅ Executed")
|
| 229 |
+
except Exception as e:
|
| 230 |
+
results.append(f"❌ Error in query: {stmt}\n{str(e)}")
|
| 231 |
+
else:
|
| 232 |
+
try:
|
| 233 |
+
cursor.execute(query)
|
| 234 |
+
results = cursor.fetchall()
|
| 235 |
+
except Exception as e:
|
| 236 |
+
return f"❌ Error executing query: {str(e)}"
|
| 237 |
+
connection.commit()
|
| 238 |
+
return results
|
| 239 |
+
except pymysql.MySQLError as e:
|
| 240 |
+
return f"❌ MySQL Error: {str(e)}"
|
| 241 |
+
finally:
|
| 242 |
+
connection.close()
|
| 243 |
+
|
| 244 |
+
def clean_sql(sql) -> str:
|
| 245 |
+
if isinstance(sql, dict) and sql:
|
| 246 |
+
first_value = next(iter(sql.values()))
|
| 247 |
+
sql = first_value
|
| 248 |
+
sql = re.sub(r"```sql", "", sql, flags=re.IGNORECASE)
|
| 249 |
+
sql = sql.replace("```sql", "")
|
| 250 |
+
sql = re.sub(r"```", "", sql)
|
| 251 |
+
return sql.strip()
|
| 252 |
+
|
| 253 |
+
def extract_sql_from_response(data):
|
| 254 |
+
# Định dạng markdown block [SQL: ```sql ... ```]
|
| 255 |
+
match = re.search(r"\[SQL:\s*```sql\s*(.*?)\s*```]", data, re.DOTALL)
|
| 256 |
+
if match:
|
| 257 |
+
return clean_sql(match.group(1))
|
| 258 |
+
|
| 259 |
+
# Định dạng đơn giản SQLQuery: ...
|
| 260 |
+
match = re.search(r"SQLQuery:\s*(.*)", data, re.DOTALL)
|
| 261 |
+
if match:
|
| 262 |
+
return clean_sql(match.group(1))
|
| 263 |
+
|
| 264 |
+
return None
|
| 265 |
+
|
| 266 |
+
def extract_sql_from_error(error_msg):
|
| 267 |
+
# Case 1: [SQL: ```sql ... ```]
|
| 268 |
+
match = re.search(r"\[SQL:\s*```sql\s*(.*?)\s*```]", error_msg, re.DOTALL)
|
| 269 |
+
if match:
|
| 270 |
+
return clean_sql(match.group(1))
|
| 271 |
+
match = re.search(r"```(?:sql)?\s*\r?\n(.*?)```", error_msg, re.DOTALL)
|
| 272 |
+
if match:
|
| 273 |
+
return clean_sql(match.group(1))
|
| 274 |
+
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
def process_and_execute_sql(sql):
|
| 278 |
+
data = sql
|
| 279 |
+
if isinstance(data, dict) and data:
|
| 280 |
+
first_key, first_value = next(iter(data.items()))
|
| 281 |
+
sql = first_value
|
| 282 |
+
elif isinstance(data, list) and data:
|
| 283 |
+
sql = "\n\n".join(data)
|
| 284 |
+
sql_clean = clean_sql(sql)
|
| 285 |
+
if re.search(r"%{1,2}s", sql_clean):
|
| 286 |
+
regenerated_sql = regenerate_sql_until_safe()
|
| 287 |
+
sql_clean = clean_sql(regenerated_sql)
|
| 288 |
+
result = get_schemas_from_sql(sql_clean, schema_mapping)
|
| 289 |
+
print("result",result)
|
| 290 |
+
prompt = build_sql_fix_prompt(result,sql =sql_clean)
|
| 291 |
+
from advance_shopping.call_gemini import tool_call
|
| 292 |
+
data = tool_call.generate(prompt = prompt)
|
| 293 |
+
sql_clean = clean_sql(data)
|
| 294 |
+
print("SQL step2: ", sql_clean)
|
| 295 |
+
if sql_clean == None:
|
| 296 |
+
return "❌ Lỗi không thể thực thi truy vấn: Không tìm thấy SQL trong phản hồi."
|
| 297 |
+
if contains_delete(sql_clean):
|
| 298 |
+
return "Lỗi: Bạn không dược phép thực hiện truy vấn DELETE trong hệ thống này."
|
| 299 |
+
if re.search(r"\\bIF\\b.*\\bTHEN\\b", sql_clean, re.IGNORECASE):
|
| 300 |
+
return "❌ Lỗi: Không được dùng IF...THEN trong SQL. Vui lòng chia nhỏ truy vấn."
|
| 301 |
+
|
| 302 |
+
if check_insert:
|
| 303 |
+
check_syntax = filter_syntax_sql(sql_clean, PROMPT_CUSTOM, user_input)
|
| 304 |
+
|
| 305 |
+
if check_syntax is True:
|
| 306 |
+
try:
|
| 307 |
+
connection = pymysql.connect(**db_config)
|
| 308 |
+
with connection.cursor() as cursor:
|
| 309 |
+
statements = sqlparse.split(sql_clean)
|
| 310 |
+
results = []
|
| 311 |
+
for stmt in statements:
|
| 312 |
+
stmt = stmt.strip()
|
| 313 |
+
if stmt:
|
| 314 |
+
try:
|
| 315 |
+
cursor.execute(stmt)
|
| 316 |
+
try:
|
| 317 |
+
results.append(cursor.fetchall())
|
| 318 |
+
except:
|
| 319 |
+
results.append("✅ OK")
|
| 320 |
+
except Exception as e:
|
| 321 |
+
return f"❌ Lỗi tại truy vấn: `{stmt}`\nChi tiết: {str(e)}"
|
| 322 |
+
connection.commit()
|
| 323 |
+
return results
|
| 324 |
+
except Exception as e:
|
| 325 |
+
return f"❌ Lỗi khi thực thi từng truy vấn: {str(e)}"
|
| 326 |
+
finally:
|
| 327 |
+
connection.close()
|
| 328 |
+
else:
|
| 329 |
+
try:
|
| 330 |
+
regenerated_data = db_chain.run(f"""
|
| 331 |
+
Role: {text_role}
|
| 332 |
+
Language: {languages}
|
| 333 |
+
Question: {user_input}.
|
| 334 |
+
""")
|
| 335 |
+
regenerated_sql = extract_sql_from_response(regenerated_data)
|
| 336 |
+
if regenerated_sql:
|
| 337 |
+
return process_and_execute_sql(regenerated_sql)
|
| 338 |
+
else:
|
| 339 |
+
return "❌ Lỗi: Không thể tạo lại truy vấn hợp lệ."
|
| 340 |
+
except Exception as regen_error:
|
| 341 |
+
return f"❌ Lỗi khi tạo lại truy vấn: {str(regen_error)}"
|
| 342 |
+
else:
|
| 343 |
+
return execute_query_with_pymysql(sql_clean, multi=True)
|
| 344 |
+
|
| 345 |
+
if "Do not use IF...THEN" not in PROMPT_CUSTOM.template:
|
| 346 |
+
PROMPT_CUSTOM.template += (
|
| 347 |
+
"\n\n⚠️ Note: Do NOT use IF...THEN...ELSE...END in SQL. "
|
| 348 |
+
"Only use plain SELECT, INSERT, UPDATE, DELETE, SET statements."
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
db_chain = SQLDatabaseChain.from_llm(llm=llm1, db=db, prompt=PROMPT_CUSTOM)
|
| 352 |
+
text_role = f"{role} (userId = {user_id})" if role == "ADMIN" else f"{role} (userId = {user_id}), not role ADMIN"
|
| 353 |
+
try:
|
| 354 |
+
data = db_chain.run(f"""
|
| 355 |
+
Role: {text_role}
|
| 356 |
+
Language: {languages}
|
| 357 |
+
Question: {user_input}.
|
| 358 |
+
""")
|
| 359 |
+
extracted_sql = extract_sql_from_response(data)
|
| 360 |
+
if extracted_sql:
|
| 361 |
+
print("SQL:",extracted_sql)
|
| 362 |
+
print(extracted_sql)
|
| 363 |
+
return process_and_execute_sql(extracted_sql)
|
| 364 |
+
else:
|
| 365 |
+
return data
|
| 366 |
+
|
| 367 |
+
except Exception as e:
|
| 368 |
+
error_message = str(e)
|
| 369 |
+
print("Lỗi: ",error_message)
|
| 370 |
+
extracted_sql = extract_sql_from_error(error_message)
|
| 371 |
+
print("SQL lỗi: ",extracted_sql)
|
| 372 |
+
if extracted_sql == None:
|
| 373 |
+
return "❌ Lỗi không thể thực thi truy vấn: Không tìm thấy SQL trong phản hồi."
|
| 374 |
+
fix_sql = re.sub(r"```sql", "", extracted_sql, flags=re.IGNORECASE)
|
| 375 |
+
fix_sql = re.sub(r"```", "", fix_sql)
|
| 376 |
+
fix_sql = re.sub(r'%%s', r'%s', fix_sql)
|
| 377 |
+
print(fix_sql)
|
| 378 |
+
print("SQL fix:",fix_sql)
|
| 379 |
+
if contains_delete(fix_sql):
|
| 380 |
+
return "Lỗi: Bạn không dược phép thực hiện truy vấn DELETE trong hệ thống này."
|
| 381 |
+
if extracted_sql:
|
| 382 |
+
return process_and_execute_sql(fix_sql)
|
| 383 |
+
else:
|
| 384 |
+
return f"❌ Lỗi không thể thực thi truy vấn: {error_message}"
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
async def create_new_chat_history(user_id: int) -> str:
|
| 388 |
+
"""
|
| 389 |
+
Tạo một đoạn chat mới cho user_id và trả về ObjectId của đoạn chat.
|
| 390 |
+
"""
|
| 391 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 392 |
+
if check is None:
|
| 393 |
+
raise HTTPException(status_code=404, detail="User not found or has been deleted in MySQL")
|
| 394 |
+
|
| 395 |
+
user = User.objects(user_id=user_id).first()
|
| 396 |
+
if not user:
|
| 397 |
+
user = User(id=ObjectId(), user_id=user_id, user_name=f"User_{user_id}")
|
| 398 |
+
user.save()
|
| 399 |
+
random_name_chat = str(random.randint(10**14, 10**15 - 1))
|
| 400 |
+
name_chat = f"Chat_{random_name_chat}"
|
| 401 |
+
new_chat = ChatHistory(id=ObjectId(), user=user, name_chat=name_chat)
|
| 402 |
+
new_chat.save()
|
| 403 |
+
|
| 404 |
+
return res_chat.CreateNewChat(idMongo=str(new_chat.id), chat_name=name_chat)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
async def update_chat_name(chat_id: str, new_name: str,user_id:int) -> str:
|
| 408 |
+
"""
|
| 409 |
+
Cập nhật name_chat của một ChatHistory dựa trên chat_id.
|
| 410 |
+
"""
|
| 411 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 412 |
+
if check is None:
|
| 413 |
+
raise HTTPException(status_code=404, detail="User not found or has been deleted in MySQL")
|
| 414 |
+
|
| 415 |
+
user = User.objects(user_id=user_id, is_deleted=False).first()
|
| 416 |
+
if not user:
|
| 417 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MongoDB")
|
| 418 |
+
|
| 419 |
+
chat = ChatHistory.objects(_id=ObjectId(chat_id)).first()
|
| 420 |
+
|
| 421 |
+
if not chat:
|
| 422 |
+
raise HTTPException(status_code=404, detail="Chat not found in MongoDB")
|
| 423 |
+
|
| 424 |
+
chat.name_chat = new_name
|
| 425 |
+
chat.save()
|
| 426 |
+
|
| 427 |
+
return f"Updated chat name to {new_name}"
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
async def soft_delete_chat(chat_id: str,user_id:int):
|
| 431 |
+
"""
|
| 432 |
+
Cập nhật `is_deleted=True` và `date_deleted` cho `ChatHistory` và các `DetailChat` liên quan.
|
| 433 |
+
"""
|
| 434 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 435 |
+
if check is None:
|
| 436 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MySQL")
|
| 437 |
+
|
| 438 |
+
check_history_id = UserRepository.getChatHistory(user_id,chat_id)
|
| 439 |
+
if check_history_id is None:
|
| 440 |
+
raise HTTPException(status_code=400, detail="Chat history not found or has been deleted in MySQL")
|
| 441 |
+
|
| 442 |
+
user = User.objects(user_id=user_id, is_deleted=False).first()
|
| 443 |
+
if not user:
|
| 444 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MongoDB")
|
| 445 |
+
|
| 446 |
+
chat = ChatHistory.objects(_id=ObjectId(chat_id)).first()
|
| 447 |
+
|
| 448 |
+
if not chat:
|
| 449 |
+
raise HTTPException(status_code=400, detail="Chat not found or has been deleted in MongoDB")
|
| 450 |
+
chat.is_deleted = True
|
| 451 |
+
chat.date_deleted = datetime.now(pytz.UTC)
|
| 452 |
+
chat.save()
|
| 453 |
+
|
| 454 |
+
DetailChat.objects(chat_history=chat).update(
|
| 455 |
+
set__is_deleted=True,
|
| 456 |
+
set__date_deleted=datetime.now(pytz.UTC)
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
return {"message": "Chat and related details marked as deleted"}
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
from datetime import datetime, timedelta
|
| 463 |
+
async def chat_with_user(
|
| 464 |
+
user_input: str,
|
| 465 |
+
user_id: int,
|
| 466 |
+
languages: str,
|
| 467 |
+
role: str,
|
| 468 |
+
token: str,
|
| 469 |
+
chat_history_id: str = None,
|
| 470 |
+
|
| 471 |
+
) -> str:
|
| 472 |
+
"""
|
| 473 |
+
Xử lý tin nhắn của người dùng, lưu vào lịch sử chat và trả về phản hồi từ AI.
|
| 474 |
+
"""
|
| 475 |
+
|
| 476 |
+
if role not in ["ADMIN", "CUSTOMER", "SHIPPER"]:
|
| 477 |
+
raise HTTPException(status_code=400, detail="ROLE not valid")
|
| 478 |
+
user_id = int(user_id)
|
| 479 |
+
if languages not in ["VN", "EN"]:
|
| 480 |
+
raise HTTPException(status_code=400, detail="Language not valid")
|
| 481 |
+
|
| 482 |
+
if not user_input:
|
| 483 |
+
raise HTTPException(status_code=400, detail="User input empty")
|
| 484 |
+
if not isinstance(user_id, int) or user_id <= 0:
|
| 485 |
+
raise HTTPException(status_code=400, detail="Invalid user_id: must be a positive integer")
|
| 486 |
+
|
| 487 |
+
languages = "Vietnamese" if languages == "VN" else "English"
|
| 488 |
+
|
| 489 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 490 |
+
if check is None:
|
| 491 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MySQL")
|
| 492 |
+
|
| 493 |
+
check_history_id = UserRepository.getChatHistory(user_id,chat_history_id)
|
| 494 |
+
if check_history_id is None:
|
| 495 |
+
raise HTTPException(status_code=400, detail="Chat not found or has been deleted in MySQL")
|
| 496 |
+
|
| 497 |
+
user = User.objects(user_id=user_id).first()
|
| 498 |
+
if not user:
|
| 499 |
+
return {"error": "User not found or has been deleted in MongoDB"}
|
| 500 |
+
|
| 501 |
+
chat_history = None
|
| 502 |
+
if chat_history_id:
|
| 503 |
+
try:
|
| 504 |
+
chat_history_obj_id = ObjectId(chat_history_id)
|
| 505 |
+
chat_history = ChatHistory.objects(_id=chat_history_obj_id, user=user).first()
|
| 506 |
+
except Exception as e:
|
| 507 |
+
|
| 508 |
+
print(f"⚠️ Invalid chat_history_id: {e}")
|
| 509 |
+
if not chat_history:
|
| 510 |
+
raise HTTPException(status_code=400, detail="Chat history not found or has been deleted in MongoDB")
|
| 511 |
+
# filtered_input = filter_sql_injection_1.filter_sql_injection(user_input)
|
| 512 |
+
# filtered_role_input = filter_role_1.filter_role(filtered_input)
|
| 513 |
+
# result = await execute_query_user(filtered_role_input, user_id, languages, role)
|
| 514 |
+
# result_final = query_result_1.query_result(user_input, result)
|
| 515 |
+
result_final = await pipeline_agent.multi_query_user(user_input,user_id,role,languages,chat_history_id, token)
|
| 516 |
+
|
| 517 |
+
detail_chat = DetailChat(
|
| 518 |
+
id=ObjectId(),
|
| 519 |
+
chat_history=chat_history,
|
| 520 |
+
you_message=user_input,
|
| 521 |
+
ai_message=result_final,
|
| 522 |
+
timestamp=datetime.now(pytz.UTC)
|
| 523 |
+
)
|
| 524 |
+
detail_chat.save()
|
| 525 |
+
chat_history_messages = DetailChat.objects(chat_history=chat_history).order_by('timestamp')
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def convert_to_vn_time(timestamp):
|
| 529 |
+
return (timestamp + timedelta(hours=7)).strftime('%Y-%m-%dT%H:%M:%S')
|
| 530 |
+
|
| 531 |
+
sorted_messages = sorted(chat_history_messages, key=lambda msg: msg.timestamp, reverse=True)
|
| 532 |
+
|
| 533 |
+
formatted_messages = [
|
| 534 |
+
{
|
| 535 |
+
"index": i + 1, # Đánh số từ 1
|
| 536 |
+
"id": str(msg.id),
|
| 537 |
+
"you_message": msg.you_message,
|
| 538 |
+
"ai_message": msg.ai_message,
|
| 539 |
+
"timestamp": convert_to_vn_time(msg.timestamp)
|
| 540 |
+
}
|
| 541 |
+
for i, msg in enumerate(sorted_messages)
|
| 542 |
+
]
|
| 543 |
+
|
| 544 |
+
return jsonable_encoder({
|
| 545 |
+
"new_message": {
|
| 546 |
+
"id": str(detail_chat.id),
|
| 547 |
+
"you_message": detail_chat.you_message,
|
| 548 |
+
"ai_message": detail_chat.ai_message,
|
| 549 |
+
"timestamp": convert_to_vn_time(detail_chat.timestamp)
|
| 550 |
+
},
|
| 551 |
+
"previous_messages": formatted_messages
|
| 552 |
+
})
|
| 553 |
+
|
| 554 |
+
from bson import ObjectId
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
async def get_chat_details(chat_id: str,user_id:int):
|
| 558 |
+
"""
|
| 559 |
+
Lấy tất cả `DetailChat` thuộc `ChatHistory` có `chat_id`, chỉ lấy bản ghi `is_deleted=False`.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 563 |
+
if check is None:
|
| 564 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MySQL")
|
| 565 |
+
|
| 566 |
+
check_history_id = UserRepository.getChatHistory(user_id,chat_id)
|
| 567 |
+
if check_history_id is None:
|
| 568 |
+
raise HTTPException(status_code=400, detail="Chat history not found or has been deleted in MySQL")
|
| 569 |
+
|
| 570 |
+
user = User.objects(user_id=user_id, is_deleted=False).first()
|
| 571 |
+
if not user:
|
| 572 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MongoDB")
|
| 573 |
+
|
| 574 |
+
chat = ChatHistory.objects(_id=ObjectId(chat_id), is_deleted=False).first()
|
| 575 |
+
|
| 576 |
+
if not chat:
|
| 577 |
+
raise HTTPException(status_code=400, detail="Chat history not found or has been deleted in MongoDB")
|
| 578 |
+
|
| 579 |
+
chat_details = DetailChat.objects(chat_history=chat, is_deleted=False)
|
| 580 |
+
def convert_to_vn_time(timestamp):
|
| 581 |
+
return (timestamp + timedelta(hours=7)).strftime('%Y-%m-%dT%H:%M:%S')
|
| 582 |
+
|
| 583 |
+
list_detail_response = [
|
| 584 |
+
res_chat.DetailResponse(
|
| 585 |
+
id=str(index + 1), # ✅ Đánh số lại từ 1
|
| 586 |
+
you_message=detail.you_message,
|
| 587 |
+
ai_message=detail.ai_message,
|
| 588 |
+
timestamp=convert_to_vn_time(detail.timestamp) # ✅ Chuyển sang GMT+7
|
| 589 |
+
)
|
| 590 |
+
for index, detail in enumerate(sorted(chat_details, key=lambda d: d.timestamp, reverse=True)) # ✅ Sắp xếp giảm dần
|
| 591 |
+
]
|
| 592 |
+
|
| 593 |
+
return res_chat.ListDetailResponse(
|
| 594 |
+
chat_id=str(chat.id),
|
| 595 |
+
chat_name=chat.name_chat,
|
| 596 |
+
list_detail_response=list_detail_response
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
async def regenerate(
|
| 602 |
+
user_question_new: str,
|
| 603 |
+
user_id: int,
|
| 604 |
+
languages: str,
|
| 605 |
+
role: str,
|
| 606 |
+
chat_history_id: str = None
|
| 607 |
+
) -> str:
|
| 608 |
+
"""
|
| 609 |
+
Xử lý tin nhắn của người dùng, lưu vào lịch sử chat và trả về phản hồi từ AI.
|
| 610 |
+
"""
|
| 611 |
+
PROMPT_CUSTOM = await prompt_cus.get_prompt_custom(user_question_new)
|
| 612 |
+
if role not in ["ADMIN", "CUSTOMER", "SHIPPER"]:
|
| 613 |
+
raise HTTPException(status_code=400, detail="ROLE not valid")
|
| 614 |
+
user_id = int(user_id)
|
| 615 |
+
if languages not in ["VN", "EN"]:
|
| 616 |
+
raise HTTPException(status_code=400, detail="Language not valid")
|
| 617 |
+
|
| 618 |
+
if not user_question_new:
|
| 619 |
+
raise HTTPException(status_code=400, detail="User input empty")
|
| 620 |
+
if not isinstance(user_id, int) or user_id <= 0:
|
| 621 |
+
raise HTTPException(status_code=400, detail="Invalid user_id: must be a positive integer")
|
| 622 |
+
|
| 623 |
+
languages = "Vietnamese" if languages == "VN" else "English"
|
| 624 |
+
|
| 625 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 626 |
+
if check is None:
|
| 627 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MySQL")
|
| 628 |
+
|
| 629 |
+
check_history_id = UserRepository.getChatHistory(user_id,chat_history_id)
|
| 630 |
+
if check_history_id is None:
|
| 631 |
+
raise HTTPException(status_code=400, detail="Chat not found or has been deleted in MySQL")
|
| 632 |
+
|
| 633 |
+
user = User.objects(user_id=user_id).first()
|
| 634 |
+
if not user:
|
| 635 |
+
return {"error": "User not found or has been deleted in MongoDB"}
|
| 636 |
+
|
| 637 |
+
chat_history = None
|
| 638 |
+
if chat_history_id:
|
| 639 |
+
try:
|
| 640 |
+
chat_history_obj_id = ObjectId(chat_history_id) # Chuyển đổi sang ObjectId
|
| 641 |
+
chat_history = ChatHistory.objects(_id=chat_history_obj_id, user=user).first()
|
| 642 |
+
except Exception as e:
|
| 643 |
+
|
| 644 |
+
print(f"⚠️ Invalid chat_history_id: {e}")
|
| 645 |
+
if not chat_history:
|
| 646 |
+
raise HTTPException(status_code=400, detail="Chat history not found or has been deleted in MongoDB")
|
| 647 |
+
# filtered_input = filter_sql_injection_1.filter_sql_injection(user_input)
|
| 648 |
+
# filtered_role_input = filter_role_1.filter_role(filtered_input)
|
| 649 |
+
# result = await execute_query_user(filtered_role_input, user_id, languages, role)
|
| 650 |
+
# result_final = query_result_1.query_result(user_input, result)
|
| 651 |
+
if chat_history:
|
| 652 |
+
last_chat = (
|
| 653 |
+
DetailChat.objects(chat_history=chat_history, is_deleted=False)
|
| 654 |
+
.order_by("-timestamp")
|
| 655 |
+
.first()
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
# if last_chat:
|
| 659 |
+
# print(f"Last chat - You: {last_chat.you_message}, AI: {last_chat.ai_message}")
|
| 660 |
+
# else:
|
| 661 |
+
# print("⚠️ No chat details found for this history.")
|
| 662 |
+
result_final = await pipeline_agent.multi_query_user(user_question_new,user_id,role,languages,chat_history_id)
|
| 663 |
+
last_chat.update(set__you_message=user_question_new, set__ai_message=result_final, set__timestamp = datetime.now(pytz.UTC))
|
| 664 |
+
|
| 665 |
+
last_chat_result = (
|
| 666 |
+
DetailChat.objects(chat_history=chat_history, is_deleted=False)
|
| 667 |
+
.order_by("-timestamp")
|
| 668 |
+
.first()
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
# detail_chat = DetailChat(
|
| 672 |
+
# id=ObjectId(),
|
| 673 |
+
# chat_history=chat_history,
|
| 674 |
+
# you_message=user_input,
|
| 675 |
+
# ai_message=result_final,
|
| 676 |
+
# timestamp=datetime.now(pytz.UTC)
|
| 677 |
+
# )
|
| 678 |
+
# detail_chat.save()
|
| 679 |
+
chat_history_messages = DetailChat.objects(chat_history=chat_history).order_by('timestamp')
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def convert_to_vn_time(timestamp):
|
| 683 |
+
return (timestamp + timedelta(hours=7)).strftime('%Y-%m-%dT%H:%M:%S')
|
| 684 |
+
|
| 685 |
+
sorted_messages = sorted(chat_history_messages, key=lambda msg: msg.timestamp, reverse=True)
|
| 686 |
+
|
| 687 |
+
formatted_messages = [
|
| 688 |
+
{
|
| 689 |
+
"index": i + 1, # Đánh số từ 1
|
| 690 |
+
"id": str(msg.id),
|
| 691 |
+
"you_message": msg.you_message,
|
| 692 |
+
"ai_message": msg.ai_message,
|
| 693 |
+
"timestamp": convert_to_vn_time(msg.timestamp)
|
| 694 |
+
}
|
| 695 |
+
for i, msg in enumerate(sorted_messages)
|
| 696 |
+
]
|
| 697 |
+
|
| 698 |
+
return jsonable_encoder({
|
| 699 |
+
"new_message": {
|
| 700 |
+
"id": str(last_chat_result.id),
|
| 701 |
+
"you_message": last_chat_result.you_message,
|
| 702 |
+
"ai_message": last_chat_result.ai_message,
|
| 703 |
+
"timestamp": convert_to_vn_time(last_chat_result.timestamp)
|
| 704 |
+
},
|
| 705 |
+
"previous_messages": formatted_messages
|
| 706 |
+
})
|
| 707 |
+
|
| 708 |
+
from bson import ObjectId
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
async def get_user_chat_history(user_id: int):
|
| 712 |
+
"""
|
| 713 |
+
API lấy danh sách tất cả các đoạn chat của một user_id.
|
| 714 |
+
"""
|
| 715 |
+
check = UserRepository.getUserByUserId(user_id)
|
| 716 |
+
if check is None:
|
| 717 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MySQL")
|
| 718 |
+
user = User.objects(user_id=user_id, is_deleted=False).first()
|
| 719 |
+
if not user:
|
| 720 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MongoDB")
|
| 721 |
+
chat_histories = ChatHistory.objects(user=user, is_deleted=False)
|
| 722 |
+
chat_list = [
|
| 723 |
+
res_chat.ChatResponse(
|
| 724 |
+
chat_id=str(chat.id),
|
| 725 |
+
chat_name=chat.name_chat,
|
| 726 |
+
timestamp=chat.date_deleted if chat.is_deleted else chat.id.generation_time
|
| 727 |
+
)
|
| 728 |
+
for chat in chat_histories
|
| 729 |
+
]
|
| 730 |
+
|
| 731 |
+
return res_chat.UserChatHistoryResponse(
|
| 732 |
+
user_id=user.user_id,
|
| 733 |
+
user_name=user.user_name,
|
| 734 |
+
chat_list=chat_list
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
from bson import ObjectId
|
| 739 |
+
|
| 740 |
+
async def get_chat_details_text(chat_id: str, user_id: int):
|
| 741 |
+
"""
|
| 742 |
+
Trích xuất tất cả các chi tiết chat của một chat_id, gom thành một đoạn văn bản.
|
| 743 |
+
"""
|
| 744 |
+
# Kiểm tra xem user có tồn tại không
|
| 745 |
+
user = User.objects(user_id=user_id, is_deleted=False).first()
|
| 746 |
+
if not user:
|
| 747 |
+
raise HTTPException(status_code=400, detail="User not found or has been deleted in MongoDB")
|
| 748 |
+
|
| 749 |
+
# Kiểm tra xem chat history có tồn tại không
|
| 750 |
+
chat = ChatHistory.objects(_id=ObjectId(chat_id), user=user, is_deleted=False).first()
|
| 751 |
+
if not chat:
|
| 752 |
+
raise HTTPException(status_code=400, detail="Chat not found or has been deleted in MongoDB")
|
| 753 |
+
|
| 754 |
+
# Lấy tất cả các chi tiết chat liên quan
|
| 755 |
+
chat_details = DetailChat.objects(chat_history=chat, is_deleted=False).order_by('timestamp')
|
| 756 |
+
|
| 757 |
+
if not chat_details:
|
| 758 |
+
return list()
|
| 759 |
+
|
| 760 |
+
# Gom tất cả các câu hỏi và câu trả lời vào danh sách
|
| 761 |
+
chat_text_list = []
|
| 762 |
+
for index, detail in enumerate(chat_details,start=1):
|
| 763 |
+
chat_text_list.append({
|
| 764 |
+
"order":str(index),
|
| 765 |
+
"timestamp": detail.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
|
| 766 |
+
"you_message": detail.you_message,
|
| 767 |
+
"ai_message": detail.ai_message
|
| 768 |
+
})
|
| 769 |
+
|
| 770 |
+
return chat_text_list
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
import asyncio
|
| 774 |
+
import os
|
| 775 |
+
import subprocess
|
| 776 |
+
from datetime import datetime
|
| 777 |
+
from pathlib import Path
|
| 778 |
+
from function.analyze import main
|
| 779 |
+
import asyncio
|
| 780 |
+
from models.Database_Entity import StopSignal
|
| 781 |
+
from function.analyze.gemini import result_analyze
|
| 782 |
+
async def check_should_stop(chat_id: str, stop_event: object = None):
|
| 783 |
+
# Trường hợp dừng qua RAM (in-memory)
|
| 784 |
+
await asyncio.sleep(0.1)
|
| 785 |
+
if stop_event and stop_event.is_set():
|
| 786 |
+
print("🛑 Dừng qua stop_event.")
|
| 787 |
+
return {"status": "cancelled"}
|
| 788 |
+
|
| 789 |
+
# Trường hợp dừng qua MongoDB
|
| 790 |
+
await asyncio.sleep(0.1)
|
| 791 |
+
if StopSignal.objects(chat_history=chat_id, is_stopped=True).first():
|
| 792 |
+
print("🛑 Dừng vì có StopSignal trong DB.")
|
| 793 |
+
return {"status": "cancelled"}
|
| 794 |
+
|
| 795 |
+
return None
|
| 796 |
+
|
| 797 |
+
from typing import Optional
|
| 798 |
+
async def generate_and_save_code(question: str, user_id: int, role, languages: str,stop_event: Optional[asyncio.Event], filename: str = "analyze_result.py",chat_id: str = ""):
|
| 799 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 800 |
+
if result_check:
|
| 801 |
+
return result_check
|
| 802 |
+
code_test, folder_name = await main.analyze(
|
| 803 |
+
question,
|
| 804 |
+
user_id,
|
| 805 |
+
languages,
|
| 806 |
+
role,
|
| 807 |
+
chat_id,
|
| 808 |
+
stop_event
|
| 809 |
+
)
|
| 810 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 811 |
+
if result_check:
|
| 812 |
+
return result_check
|
| 813 |
+
code_clean = code_test.strip()
|
| 814 |
+
if code_clean.startswith("```python"):
|
| 815 |
+
code_clean = code_clean[9:].strip()
|
| 816 |
+
if code_clean.endswith("```"):
|
| 817 |
+
code_clean = code_clean[:-3].strip()
|
| 818 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 819 |
+
if result_check:
|
| 820 |
+
return result_check
|
| 821 |
+
# code_clean = code_clean.replace("else:", "").strip()
|
| 822 |
+
code_clean = code_clean.replace("os_path:", "os.path").strip()
|
| 823 |
+
encoding_fix = 'import sys\nsys.stdout.reconfigure(encoding="utf-8")\n\n'
|
| 824 |
+
encoding_fix1= 'import numpy as np\n\n'
|
| 825 |
+
code_clean = encoding_fix + encoding_fix1 + code_clean
|
| 826 |
+
|
| 827 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 828 |
+
output_dir = Path(f"./Temp/{folder_name}_{timestamp}")
|
| 829 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 830 |
+
|
| 831 |
+
file_path = output_dir / filename
|
| 832 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 833 |
+
f.write(code_clean)
|
| 834 |
+
|
| 835 |
+
|
| 836 |
+
env = os.environ.copy()
|
| 837 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 838 |
+
if result_check:
|
| 839 |
+
return result_check
|
| 840 |
+
env["OUTPUT_DIR"] = str(output_dir)
|
| 841 |
+
result = subprocess.run(
|
| 842 |
+
["python", filename],
|
| 843 |
+
capture_output=True,
|
| 844 |
+
text=True,
|
| 845 |
+
env=env,
|
| 846 |
+
cwd=output_dir,
|
| 847 |
+
encoding="utf-8",
|
| 848 |
+
errors="replace"
|
| 849 |
+
)
|
| 850 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 851 |
+
if result_check:
|
| 852 |
+
return result_check
|
| 853 |
+
output_folder = str(output_dir)
|
| 854 |
+
absolute_path = os.path.abspath(output_folder)
|
| 855 |
+
final_path = os.path.join(absolute_path, "test5")
|
| 856 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 857 |
+
if result_check:
|
| 858 |
+
return result_check
|
| 859 |
+
result_final = result_analyze.generate(image_folder=final_path,question=question)
|
| 860 |
+
result_check = await check_should_stop(chat_id, stop_event)
|
| 861 |
+
if result_check:
|
| 862 |
+
return result_check
|
| 863 |
+
return result_final, final_path
|