File size: 48,066 Bytes
33c0b9a abdc56e 0f3a5a7 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 ad16ec7 bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e bddd3f1 c99a26e ab67448 bddd3f1 3a4e9fd 301896c 3a4e9fd bddd3f1 7e22b89 bddd3f1 ab67448 |
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 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 613 614 615 616 617 618 619 620 621 622 623 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 717 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 777 778 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 812 813 814 815 816 817 818 819 820 821 822 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 858 859 860 861 862 863 864 865 866 867 868 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 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 |
# import gradio as gr
# import os
# from langchain_community.document_loaders import PyPDFLoader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.chains import RetrievalQA
# from langchain_community.llms import HuggingFacePipeline
# from transformers import pipeline
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# # Global variables to store the model components
# qa = None
# model_loaded = False
# def initialize_model():
# """Initialize the AI model components"""
# global qa, model_loaded
# if model_loaded:
# return "Model already loaded"
# try:
# # Step 1: Load PDF (you need to upload your PDF to the Hugging Face Space)
# pdf_path = "basava formulaity.pdf" # Make sure to upload this file to your space
# if not os.path.exists(pdf_path):
# return f"Error: PDF file not found at {pdf_path}. Please upload your PDF to the space."
# loader = PyPDFLoader(pdf_path)
# documents = loader.load()
# # Step 2: Split Text into Chunks
# text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
# chunks = text_splitter.split_documents(documents)
# # Step 3: Generate Embeddings and Store in FAISS
# embedding_model = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
# db = FAISS.from_documents(chunks, embedding_model)
# retriever = db.as_retriever()
# # Step 4: Load Local QA Model
# flan_pipeline = pipeline(
# "text2text-generation",
# model="NousResearch/Llama-3.2-1B",
# max_length=1024,
# do_sample=True,
# temperature=0.7,
# top_p=0.9,
# repetition_penalty=1.2
# )
# local_llm = HuggingFacePipeline(pipeline=flan_pipeline)
# # Step 5: Define custom prompt template
# prompt_template = PromptTemplate(
# input_variables=["context", "question"],
# template="""
# You are a helpful veterinary assistant. Based only on the following context, answer the question accurately, do not hallucinate try to keep your language simple and be as precise as possible dont use medical terminologies.
# Context:
# {context}
# Question:
# {question}
# Answer:"""
# )
# # Step 6: Load QA chain with the custom prompt
# qa_chain = load_qa_chain(llm=local_llm, chain_type="stuff", prompt=prompt_template)
# # Step 7: Build the RetrievalQA pipeline
# qa = RetrievalQA(
# combine_documents_chain=qa_chain,
# retriever=retriever,
# return_source_documents=False
# )
# model_loaded = True
# return "β
Model loaded successfully!"
# except Exception as e:
# return f"β Error loading model: {str(e)}"
# def analyze_cat_symptoms(query):
# """
# Analyze cat symptoms using the loaded AI model
# """
# global qa, model_loaded
# if not model_loaded:
# init_result = initialize_model()
# if "Error" in init_result or "β" in init_result:
# return init_result
# try:
# if not query.strip():
# return "Please provide cat symptoms and information for analysis."
# # Query the model
# result = qa({"query": query})
# # Extract the answer
# raw_output = result["result"]
# # Remove everything before "Answer:" and keep only the actual answer
# if "Answer:" in raw_output:
# final_answer = raw_output.split("Answer:", 1)[-1].strip()
# else:
# final_answer = raw_output.strip()
# # Add disclaimer
# disclaimer = "\n\nβ οΈ **Important Disclaimer:** This AI analysis is for informational purposes only and should not replace professional veterinary care. If your cat shows severe symptoms or you're concerned about their health, please consult a veterinarian immediately."
# return final_answer + disclaimer
# except Exception as e:
# return f"β Error analyzing symptoms: {str(e)}"
# # Create Gradio interface
# def create_interface():
# with gr.Blocks(title="Cat Health Analyzer", theme=gr.themes.Soft()) as interface:
# gr.Markdown("""
# # π± Cat Health AI Analyzer
# **AI-powered veterinary assistant for cat health analysis**
# Enter detailed information about your cat and their symptoms for analysis.
# """)
# with gr.Row():
# with gr.Column(scale=2):
# query_input = gr.Textbox(
# label="Cat Information & Symptoms",
# placeholder="""Example:
# Cat Information:
# - Name: Fluffy
# - Age: 3 years
# - Breed: Persian
# - Weight: 4.5 kg
# - Gender: Female
# Observed Symptoms: sneezing, watery eyes, loss of appetite
# Symptom Duration: 2-3 days
# Symptom Severity: Moderate
# Additional Notes: Cat has been hiding under the bed and not playing as usual.
# What could be wrong with my cat and what should I do?""",
# lines=15,
# max_lines=20
# )
# analyze_btn = gr.Button("π Analyze Symptoms", variant="primary", size="lg")
# with gr.Column(scale=2):
# output = gr.Textbox(
# label="AI Analysis & Recommendations",
# lines=15,
# max_lines=25,
# show_copy_button=True
# )
# # Add example queries
# gr.Markdown("### π Example Queries")
# examples = gr.Examples(
# examples=[
# ["My cat (Whiskers, 5 years old, male) has been vomiting for 2 days and won't eat. He's hiding under the bed. What could be wrong?"],
# ["My female cat (Luna, 2 years, Siamese, 3.5kg) has watery eyes, sneezing, and seems lethargic. Symptoms started 3 days ago. Should I be worried?"],
# ["My 8-year-old cat has been drinking more water than usual and urinating frequently. He's also lost some weight recently. What might this indicate?"]
# ],
# inputs=[query_input],
# outputs=[output],
# fn=analyze_cat_symptoms,
# cache_examples=False
# )
# analyze_btn.click(
# fn=analyze_cat_symptoms,
# inputs=[query_input],
# outputs=[output]
# )
# # Add footer
# gr.Markdown("""
# ---
# **Note:** This tool uses AI to provide general guidance based on veterinary knowledge.
# Always consult with a qualified veterinarian for proper diagnosis and treatment.
# """)
# return interface
# # Initialize model on startup
# print("π Starting Cat Health AI Analyzer...")
# print("π Loading AI model components...")
# # Create and launch the interface
# if __name__ == "__main__":
# interface = create_interface()
# interface.launch(
# server_name="0.0.0.0",
# server_port=7860,
# share=False
# )
#######################ALMOST PERFFF
# import gradio as gr
# import os
# from langchain_community.document_loaders import PyPDFLoader
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.vectorstores import FAISS
# from langchain.embeddings import HuggingFaceEmbeddings
# from langchain.chains import RetrievalQA
# from langchain_community.llms import HuggingFacePipeline
# from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# import torch
# # Global variables to store the model components
# qa = None
# model_loaded = False
# def initialize_model():
# """Initialize the AI model components"""
# global qa, model_loaded
# if model_loaded:
# return "Model already loaded"
# try:
# # Step 1: Load PDF
# pdf_path = "basava formulaity.pdf"
# if not os.path.exists(pdf_path):
# return f"Error: PDF file not found at {pdf_path}. Please upload your PDF to the space."
# loader = PyPDFLoader(pdf_path)
# documents = loader.load()
# # Step 2: Split Text into Chunks (optimized parameters)
# text_splitter = RecursiveCharacterTextSplitter(
# chunk_size=800,
# chunk_overlap=200,
# separators=["\n\n", "\n", ".", " ", ""]
# )
# chunks = text_splitter.split_documents(documents)
# # Step 3: Generate Embeddings and Store in FAISS (more efficient model)
# embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
# db = FAISS.from_documents(chunks, embedding_model)
# retriever = db.as_retriever(search_kwargs={"k": 4}) # Retrieve 4 relevant chunks
# # Step 4: Load TinyLlama model (more efficient than Llama-3.2-1B)
# model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
# tokenizer = AutoTokenizer.from_pretrained(model_id)
# # Check if GPU is available
# device = 0 if torch.cuda.is_available() else -1
# model = AutoModelForCausalLM.from_pretrained(
# model_id,
# torch_dtype=torch.float16 if device == 0 else torch.float32,
# device_map="auto" if device == 0 else None,
# low_cpu_mem_usage=True
# )
# # Create text generation pipeline
# text_gen_pipeline = pipeline(
# "text-generation",
# model=model,
# tokenizer=tokenizer,
# max_new_tokens=256,
# temperature=0.7,
# device=device
# )
# local_llm = HuggingFacePipeline(pipeline=text_gen_pipeline)
# # Step 5: Define improved prompt template
# prompt_template = PromptTemplate(
# input_variables=["context", "question"],
# template="""
# You are a helpful veterinary assistant. Use only the context to answer. Explain briefly.
# Context:
# {context}
# Question:
# {question}
# Answer:"""
# )
# # Step 6: Load QA chain with the custom prompt
# qa_chain = load_qa_chain(llm=local_llm, chain_type="stuff", prompt=prompt_template)
# # Step 7: Build the RetrievalQA pipeline
# qa = RetrievalQA(
# combine_documents_chain=qa_chain,
# retriever=retriever,
# return_source_documents=False
# )
# model_loaded = True
# return "β
Model loaded successfully!"
# except Exception as e:
# return f"β Error loading model: {str(e)}"
# def analyze_cat_symptoms(query):
# """
# Analyze cat symptoms using the loaded AI model
# """
# global qa, model_loaded
# if not model_loaded:
# init_result = initialize_model()
# if "Error" in init_result or "β" in init_result:
# return init_result
# try:
# if not query.strip():
# return "Please provide cat symptoms and information for analysis."
# # Query the model
# result = qa({"query": query})
# # Extract the answer
# raw_output = result["result"]
# # Clean up the output
# if "Answer:" in raw_output:
# final_answer = raw_output.split("Answer:", 1)[-1].strip()
# else:
# final_answer = raw_output.strip()
# # Add disclaimer
# disclaimer = "\n\nβ οΈ **Important Disclaimer:** This AI analysis is for informational purposes only and should not replace professional veterinary care. If your cat shows severe symptoms or you're concerned about their health, please consult a veterinarian immediately."
# return final_answer + disclaimer
# except Exception as e:
# return f"β Error analyzing symptoms: {str(e)}"
# # Create Gradio interface
# def create_interface():
# with gr.Blocks(title="Cat Health Analyzer", theme=gr.themes.Soft()) as interface:
# gr.Markdown("""
# # π± Cat Health AI Analyzer
# **AI-powered veterinary assistant for cat health analysis**
# Enter detailed information about your cat and their symptoms for analysis.
# """)
# with gr.Row():
# with gr.Column(scale=2):
# query_input = gr.Textbox(
# label="Cat Information & Symptoms",
# placeholder="""Example:
# Cat Information:
# - Name: Fluffy
# - Age: 3 years
# - Breed: Persian
# - Weight: 4.5 kg
# - Gender: Female
# Observed Symptoms: sneezing, watery eyes, loss of appetite
# Symptom Duration: 2-3 days
# Symptom Severity: Moderate
# Additional Notes: Cat has been hiding under the bed and not playing as usual.
# What could be wrong with my cat and what should I do?""",
# lines=15,
# max_lines=20
# )
# analyze_btn = gr.Button("π Analyze Symptoms", variant="primary", size="lg")
# with gr.Column(scale=2):
# output = gr.Textbox(
# label="AI Analysis & Recommendations",
# lines=15,
# max_lines=25,
# show_copy_button=True
# )
# # Add example queries
# gr.Markdown("### π Example Queries")
# examples = gr.Examples(
# examples=[
# ["My cat (Whiskers, 5 years old, male) has been vomiting for 2 days and won't eat. He's hiding under the bed. What could be wrong?"],
# ["My female cat (Luna, 2 years, Siamese, 3.5kg) has watery eyes, sneezing, and seems lethargic. Symptoms started 3 days ago. Should I be worried?"],
# ["My 8-year-old cat has been drinking more water than usual and urinating frequently. He's also lost some weight recently. What might this indicate?"]
# ],
# inputs=[query_input],
# outputs=[output],
# fn=analyze_cat_symptoms,
# cache_examples=False
# )
# analyze_btn.click(
# fn=analyze_cat_symptoms,
# inputs=[query_input],
# outputs=[output]
# )
# # Add footer
# gr.Markdown("""
# ---
# **Note:** This tool uses AI to provide general guidance based on veterinary knowledge.
# Always consult with a qualified veterinarian for proper diagnosis and treatment.
# """)
# return interface
# # Initialize model on startup
# print("π Starting Cat Health AI Analyzer...")
# print("π Loading AI model components...")
# # Preload the model during startup
# initialize_model()
# # Create and launch the interface
# if __name__ == "__main__":
# interface = create_interface()
# interface.launch(
# server_name="0.0.0.0",
# server_port=7860,
# share=False
# )
##################################ALMOST PERFFFFFF
############################## PRELOADED IMBEDDING fast but not quite it
# import gradio as gr
# import os
# from langchain_community.vectorstores import FAISS
# from langchain_community.embeddings import HuggingFaceEmbeddings
# from langchain.chains import RetrievalQA
# from langchain_community.llms import HuggingFacePipeline
# from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# import torch
# import threading
# import time
# # Global variables to store the model components
# qa = None
# model_loaded = False
# loading_status = "Not started"
# def load_model_async():
# """Load the model asynchronously in the background"""
# global qa, model_loaded, loading_status
# try:
# loading_status = "Loading embeddings..."
# # Step 1: Load pre-computed FAISS embeddings (fastest part)
# embedding_files = ["index.faiss", "index.pkl"]
# # Check if embedding files exist
# for file in embedding_files:
# if not os.path.exists(file):
# loading_status = f"Error: {file} not found"
# return
# # Initialize embedding model (lightweight)
# embedding_model = HuggingFaceEmbeddings(
# model_name="sentence-transformers/all-MiniLM-L6-v2",
# model_kwargs={'device': 'cpu'}, # Keep embeddings on CPU to save GPU memory
# encode_kwargs={'normalize_embeddings': True}
# )
# # Load the pre-computed FAISS vector store
# db = FAISS.load_local(".", embedding_model, allow_dangerous_deserialization=True)
# retriever = db.as_retriever(search_kwargs={"k": 3}) # Reduced from 4 to 3 for speed
# loading_status = "Loading language model..."
# # Step 2: Load a smaller, faster model for better performance
# model_id = "microsoft/DialoGPT-small" # Much faster than TinyLlama
# # Check device availability
# device = "cuda" if torch.cuda.is_available() else "cpu"
# # Load tokenizer
# tokenizer = AutoTokenizer.from_pretrained(model_id)
# if tokenizer.pad_token is None:
# tokenizer.pad_token = tokenizer.eos_token
# # Load model with optimizations
# model = AutoModelForCausalLM.from_pretrained(
# model_id,
# torch_dtype=torch.float16 if device == "cuda" else torch.float32,
# device_map="auto" if device == "cuda" else None,
# low_cpu_mem_usage=True,
# use_cache=True # Enable KV cache for faster inference
# )
# # Create optimized text generation pipeline
# text_gen_pipeline = pipeline(
# "text-generation",
# model=model,
# tokenizer=tokenizer,
# max_new_tokens=150, # Reduced for faster generation
# temperature=0.6,
# do_sample=True,
# pad_token_id=tokenizer.eos_token_id,
# device=0 if device == "cuda" else -1,
# batch_size=1 # Single batch for consistent performance
# )
# local_llm = HuggingFacePipeline(pipeline=text_gen_pipeline)
# loading_status = "Setting up QA chain..."
# # Step 3: Simplified prompt template for faster processing
# prompt_template = PromptTemplate(
# input_variables=["context", "question"],
# template="""Based on the veterinary information provided, give a brief answer.
# Context: {context}
# Question: {question}
# Answer:"""
# )
# # Step 4: Load QA chain
# qa_chain = load_qa_chain(
# llm=local_llm,
# chain_type="stuff",
# prompt=prompt_template,
# verbose=False # Disable verbose logging for speed
# )
# # Step 5: Build the RetrievalQA pipeline
# qa = RetrievalQA(
# combine_documents_chain=qa_chain,
# retriever=retriever,
# return_source_documents=False # Skip source docs for speed
# )
# model_loaded = True
# loading_status = "β
Ready! Model loaded successfully."
# except Exception as e:
# loading_status = f"β Error: {str(e)}"
# model_loaded = False
# def get_loading_status():
# """Get current loading status"""
# return loading_status
# def initialize_model():
# """Initialize or check model status"""
# global model_loaded
# if model_loaded:
# return "β
Model is ready!"
# return loading_status
# def analyze_cat_symptoms(query):
# """
# Analyze cat symptoms with optimized processing
# """
# global qa, model_loaded
# if not model_loaded:
# return f"β³ Model is still loading. Status: {loading_status}\n\nPlease wait a moment and try again."
# try:
# if not query.strip():
# return "Please provide cat symptoms and information for analysis."
# # Pre-process query for better results
# processed_query = f"Cat health question: {query}"
# # Query with timeout protection
# result = qa({"query": processed_query})
# # Extract and clean the answer
# raw_output = result["result"]
# # Clean up the output more aggressively
# lines = raw_output.split('\n')
# cleaned_lines = []
# for line in lines:
# line = line.strip()
# if line and not line.startswith('Context:') and not line.startswith('Question:'):
# if 'Answer:' in line:
# line = line.split('Answer:', 1)[-1].strip()
# cleaned_lines.append(line)
# final_answer = ' '.join(cleaned_lines).strip()
# # Fallback if answer is too short or empty
# if len(final_answer) < 20:
# final_answer = "Based on the symptoms you've described, I recommend consulting with a veterinarian for proper diagnosis and treatment. The symptoms could indicate various conditions that require professional evaluation."
# # Add disclaimer
# disclaimer = "\n\nβ οΈ **Important:** This is AI guidance only. Always consult a veterinarian for proper diagnosis and treatment."
# return final_answer + disclaimer
# except Exception as e:
# return f"β Analysis error: {str(e)}\n\nPlease try rephrasing your question."
# def check_embedding_status():
# """Check embedding files and model status"""
# embedding_files = ["index.faiss", "index.pkl"]
# status_lines = []
# for file in embedding_files:
# if os.path.exists(file):
# file_size = round(os.path.getsize(file) / (1024*1024), 2) # Size in MB
# status_lines.append(f"β
{file} ({file_size} MB)")
# else:
# status_lines.append(f"β {file} (missing)")
# status_lines.append(f"π€ Model Status: {loading_status}")
# return "\n".join(status_lines)
# # Create Gradio interface
# def create_interface():
# with gr.Blocks(title="Cat Health Analyzer - Ultra Fast", theme=gr.themes.Soft()) as interface:
# gr.Markdown("""
# # π± Cat Health AI Analyzer (Ultra-Fast Edition)
# **Optimized AI veterinary assistant with background model loading**
# β‘ The model loads automatically in the background for instant responses!
# """)
# # Status display that updates automatically
# with gr.Row():
# status_display = gr.Textbox(
# label="π System Status",
# value=check_embedding_status(),
# lines=4,
# interactive=False
# )
# with gr.Row():
# with gr.Column(scale=2):
# query_input = gr.Textbox(
# label="Cat Symptoms & Information",
# placeholder="""Quick example:
# My 3-year-old cat has been sneezing and has watery eyes for 2 days. Not eating much. What could this be?""",
# lines=8,
# max_lines=15
# )
# with gr.Row():
# analyze_btn = gr.Button("π Analyze Now", variant="primary", size="lg")
# refresh_btn = gr.Button("π Refresh Status", variant="secondary")
# with gr.Column(scale=2):
# output = gr.Textbox(
# label="AI Analysis",
# lines=12,
# max_lines=20,
# show_copy_button=True
# )
# # Quick examples for faster testing
# gr.Markdown("### π Quick Examples")
# examples = gr.Examples(
# examples=[
# ["My cat is vomiting and won't eat. What should I do?"],
# ["My cat has watery eyes and is sneezing. Is this serious?"],
# ["My older cat is drinking more water and urinating frequently."]
# ],
# inputs=[query_input],
# outputs=[output],
# fn=analyze_cat_symptoms,
# cache_examples=False
# )
# # Event handlers
# analyze_btn.click(
# fn=analyze_cat_symptoms,
# inputs=[query_input],
# outputs=[output]
# )
# refresh_btn.click(
# fn=check_embedding_status,
# inputs=[],
# outputs=[status_display]
# )
# # Auto-refresh status using a separate thread
# def auto_refresh_status():
# while True:
# time.sleep(3)
# if model_loaded:
# break
# # This is a simplified approach - in a real app you'd use
# # Gradio's built-in update mechanisms
# # Start the auto-refresh thread
# refresh_thread = threading.Thread(target=auto_refresh_status, daemon=True)
# refresh_thread.start()
# # Footer with performance info
# gr.Markdown("""
# ---
# **β‘ Performance Features:**
# - π Background model loading
# - π Pre-computed embeddings
# - π Optimized inference pipeline
# - πΎ Memory-efficient processing
# **Note:** This AI provides general guidance only. Always consult a veterinarian for medical decisions.
# """)
# return interface
# # Start background model loading immediately
# print("π Starting Ultra-Fast Cat Health AI Analyzer...")
# print("π Checking embedding files...")
# # Check files on startup
# embedding_status = check_embedding_status()
# print(embedding_status)
# if "β" in embedding_status:
# print("β οΈ Warning: Missing embedding files. Upload index.faiss and index.pkl files.")
# loading_status = "β Missing embedding files"
# else:
# print("β
Embedding files found! Starting background model loading...")
# # Start loading model in background thread
# loading_thread = threading.Thread(target=load_model_async, daemon=True)
# loading_thread.start()
# # Launch interface immediately
# if __name__ == "__main__":
# interface = create_interface()
# interface.launch(
# server_name="0.0.0.0",
# server_port=7860,
# share=False,
# show_error=True
# )
######################### IMBEDDING LATEST
# import gradio as gr
# import os
# from langchain_community.vectorstores import FAISS
# from langchain_community.embeddings import HuggingFaceEmbeddings
# from langchain.chains import RetrievalQA
# from langchain_community.llms import HuggingFacePipeline
# from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
# from langchain.chains.question_answering import load_qa_chain
# from langchain.prompts import PromptTemplate
# import torch
# import threading
# # Global variables to store the model components
# qa = None
# model_loaded = False
# loading_status = "Not started"
# def load_model_async():
# """Load the model asynchronously in the background"""
# global qa, model_loaded, loading_status
# try:
# loading_status = "Loading embeddings..."
# # Step 1: Load pre-computed FAISS embeddings (fastest part)
# embedding_files = ["index.faiss", "index.pkl"]
# # Check if embedding files exist
# for file in embedding_files:
# if not os.path.exists(file):
# loading_status = f"Error: {file} not found"
# return
# # Initialize embedding model (lightweight)
# embedding_model = HuggingFaceEmbeddings(
# model_name="sentence-transformers/all-MiniLM-L6-v2",
# model_kwargs={'device': 'cpu'}, # Keep embeddings on CPU to save GPU memory
# encode_kwargs={'normalize_embeddings': True}
# )
# # Load the pre-computed FAISS vector store
# db = FAISS.load_local(".", embedding_model, allow_dangerous_deserialization=True)
# retriever = db.as_retriever(search_kwargs={"k": 3}) # Reduced from 4 to 3 for speed
# loading_status = "Loading language model..."
# # Step 2: Load TinyLlama model as requested
# model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
# # Check device availability
# device = "cuda" if torch.cuda.is_available() else "cpu"
# # Load tokenizer
# tokenizer = AutoTokenizer.from_pretrained(model_id)
# if tokenizer.pad_token is None:
# tokenizer.pad_token = tokenizer.eos_token
# # Load model with optimizations
# model = AutoModelForCausalLM.from_pretrained(
# model_id,
# torch_dtype=torch.float16 if device == "cuda" else torch.float32,
# device_map="auto" if device == "cuda" else None,
# low_cpu_mem_usage=True,
# use_cache=True # Enable KV cache for faster inference
# )
# # Create optimized text generation pipeline
# text_gen_pipeline = pipeline(
# "text-generation",
# model=model,
# tokenizer=tokenizer,
# max_new_tokens=256, # Back to original value as requested
# temperature=0.7,
# do_sample=True,
# pad_token_id=tokenizer.eos_token_id,
# device=0 if device == "cuda" else -1,
# batch_size=1 # Single batch for consistent performance
# )
# local_llm = HuggingFacePipeline(pipeline=text_gen_pipeline)
# loading_status = "Setting up QA chain..."
# # Step 3: Simplified prompt template for faster processing
# prompt_template = PromptTemplate(
# input_variables=["context", "question"],
# template="""Based on the veterinary information provided, give a brief answer.
# Context: {context}
# Question: {question}
# Answer:"""
# )
# # Step 4: Load QA chain
# qa_chain = load_qa_chain(
# llm=local_llm,
# chain_type="stuff",
# prompt=prompt_template,
# verbose=False # Disable verbose logging for speed
# )
# # Step 5: Build the RetrievalQA pipeline
# qa = RetrievalQA(
# combine_documents_chain=qa_chain,
# retriever=retriever,
# return_source_documents=False # Skip source docs for speed
# )
# model_loaded = True
# loading_status = "β
Ready! Model loaded successfully."
# except Exception as e:
# loading_status = f"β Error: {str(e)}"
# model_loaded = False
# def get_loading_status():
# """Get current loading status"""
# return loading_status
# def initialize_model():
# """Initialize or check model status"""
# global model_loaded
# if model_loaded:
# return "β
Model is ready!"
# return loading_status
# def analyze_cat_symptoms(query):
# """
# Analyze cat symptoms with optimized processing
# """
# global qa, model_loaded
# if not model_loaded:
# return f"β³ Model is still loading. Status: {loading_status}\n\nPlease wait a moment and try again."
# try:
# if not query.strip():
# return "Please provide cat symptoms and information for analysis."
# # Pre-process query for better results
# processed_query = f"Cat health question: {query}"
# # Query with timeout protection
# result = qa({"query": processed_query})
# # Extract and clean the answer
# raw_output = result["result"]
# # Clean up the output more aggressively
# lines = raw_output.split('\n')
# cleaned_lines = []
# for line in lines:
# line = line.strip()
# if line and not line.startswith('Context:') and not line.startswith('Question:'):
# if 'Answer:' in line:
# line = line.split('Answer:', 1)[-1].strip()
# cleaned_lines.append(line)
# final_answer = ' '.join(cleaned_lines).strip()
# # Fallback if answer is too short or empty
# if len(final_answer) < 20:
# final_answer = "Based on the symptoms you've described, I recommend consulting with a veterinarian for proper diagnosis and treatment. The symptoms could indicate various conditions that require professional evaluation."
# # Add disclaimer
# disclaimer = "\n\nβ οΈ **Important:** This is AI guidance only. Always consult a veterinarian for proper diagnosis and treatment."
# return final_answer + disclaimer
# except Exception as e:
# return f"β Analysis error: {str(e)}\n\nPlease try rephrasing your question."
# def check_embedding_status():
# """Check embedding files and model status"""
# embedding_files = ["index.faiss", "index.pkl"]
# status_lines = []
# for file in embedding_files:
# if os.path.exists(file):
# file_size = round(os.path.getsize(file) / (1024*1024), 2) # Size in MB
# status_lines.append(f"β
{file} ({file_size} MB)")
# else:
# status_lines.append(f"β {file} (missing)")
# status_lines.append(f"π€ Model Status: {loading_status}")
# return "\n".join(status_lines)
# # Create Gradio interface
# def create_interface():
# with gr.Blocks(title="Cat Health Analyzer - Ultra Fast", theme=gr.themes.Soft()) as interface:
# gr.Markdown("""
# # π± Cat Health AI Analyzer (Ultra-Fast Edition)
# **Optimized AI veterinary assistant with background model loading**
# β‘ The model loads automatically in the background for instant responses!
# """)
# # Status display that updates automatically
# with gr.Row():
# status_display = gr.Textbox(
# label="π System Status",
# value=check_embedding_status(),
# lines=4,
# interactive=False
# )
# with gr.Row():
# with gr.Column(scale=2):
# query_input = gr.Textbox(
# label="Cat Symptoms & Information",
# placeholder="""Quick example:
# My 3-year-old cat has been sneezing and has watery eyes for 2 days. Not eating much. What could this be?""",
# lines=8,
# max_lines=15
# )
# with gr.Row():
# analyze_btn = gr.Button("π Analyze Now", variant="primary", size="lg")
# refresh_btn = gr.Button("π Refresh Status", variant="secondary")
# with gr.Column(scale=2):
# output = gr.Textbox(
# label="AI Analysis",
# lines=12,
# max_lines=20,
# show_copy_button=True
# )
# # Quick examples for faster testing
# gr.Markdown("### π Quick Examples")
# examples = gr.Examples(
# examples=[
# ["My cat is vomiting and won't eat. What should I do?"],
# ["My cat has watery eyes and is sneezing. Is this serious?"],
# ["My older cat is drinking more water and urinating frequently."]
# ],
# inputs=[query_input],
# outputs=[output],
# fn=analyze_cat_symptoms,
# cache_examples=False
# )
# # Event handlers
# analyze_btn.click(
# fn=analyze_cat_symptoms,
# inputs=[query_input],
# outputs=[output]
# )
# refresh_btn.click(
# fn=check_embedding_status,
# inputs=[],
# outputs=[status_display]
# )
# # Footer with performance info
# gr.Markdown("""
# ---
# **β‘ Performance Features:**
# - π Background model loading
# - π Pre-computed embeddings
# - π Optimized inference pipeline
# - πΎ Memory-efficient processing
# **Note:** This AI provides general guidance only. Always consult a veterinarian for medical decisions.
# """)
# return interface
# # Start background model loading immediately
# print("π Starting Ultra-Fast Cat Health AI Analyzer...")
# print("π Checking embedding files...")
# # Check files on startup
# embedding_status = check_embedding_status()
# print(embedding_status)
# if "β" in embedding_status:
# print("β οΈ Warning: Missing embedding files. Upload index.faiss and index.pkl files.")
# loading_status = "β Missing embedding files"
# else:
# print("β
Embedding files found! Starting background model loading...")
# # Start loading model in background thread
# loading_thread = threading.Thread(target=load_model_async, daemon=True)
# loading_thread.start()
# # Launch interface immediately
# if __name__ == "__main__":
# interface = create_interface()
# interface.launch(
# server_name="0.0.0.0",
# server_port=7860,
# share=False,
# show_error=True
# )
################################## MORE OPTIMIZATION and embedding optimization IRFANNN UnicodeError
import os
import shutil
import gradio as gr
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.chains import RetrievalQA
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from langchain_community.llms import HuggingFacePipeline
from transformers import pipeline
import torch
# -----------------------------
# Config (can be changed in Space "Variables & secrets")
# -----------------------------
EMBEDDINGS_MODEL = os.getenv("EMBEDDINGS_MODEL", "mixedbread-ai/mxbai-embed-large-v1")
GENERATION_MODEL = os.getenv("GENERATION_MODEL", "google/flan-t5-base")
MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "256"))
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.2"))
HF_TOKEN = os.getenv("HF_TOKEN", None)
# Where to save the FAISS index on disk
INDEX_DIR = os.getenv("INDEX_DIR", "faiss_index")
# -----------------------------
# Globals kept in memory
# -----------------------------
db_state = {"db": None, "retriever": None}
qa_state = {"qa": None}
embeddings_state = {"emb": None}
def get_embeddings():
if embeddings_state["emb"] is None:
embeddings_state["emb"] = HuggingFaceEmbeddings(model_name=EMBEDDINGS_MODEL)
return embeddings_state["emb"]
def try_load_index():
"""Try loading an existing FAISS index from disk on startup or when user opens the app."""
emb = get_embeddings()
if os.path.isdir(INDEX_DIR) and os.path.exists(os.path.join(INDEX_DIR, "index.faiss")):
try:
db = FAISS.load_local(INDEX_DIR, emb, allow_dangerous_deserialization=True)
db_state["db"] = db
db_state["retriever"] = db.as_retriever()
return f"β
Loaded saved FAISS index from disk.\n- index: `{INDEX_DIR}`\n- embeddings: `{EMBEDDINGS_MODEL}`"
except Exception as e:
return f"β οΈ Found an index on disk but failed to load it: {e}"
return f"βΉοΈ No saved index found yet. Upload a PDF and click **Build index**.\n- expected index dir: `{INDEX_DIR}`\n- embeddings: `{EMBEDDINGS_MODEL}`"
def build_index(pdf_path: str):
"""Load a PDF, split text, build FAISS index with HuggingFaceEmbeddings, then save to disk."""
if not pdf_path or not os.path.exists(pdf_path):
raise gr.Error("Please upload a valid PDF file.")
loader = PyPDFLoader(pdf_path)
documents = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
chunks = splitter.split_documents(documents)
emb = get_embeddings()
db = FAISS.from_documents(chunks, emb)
# save/overwrite local index
if os.path.isdir(INDEX_DIR):
shutil.rmtree(INDEX_DIR, ignore_errors=True)
db.save_local(INDEX_DIR)
db_state["db"] = db
db_state["retriever"] = db.as_retriever()
return f"β
FAISS index built and saved to disk.\n- index: `{INDEX_DIR}`\n- chunks: {len(chunks)}\n- embeddings: `{EMBEDDINGS_MODEL}`"
def make_llm():
"""Create a Transformers pipeline and wrap it as a LangChain LLM."""
device = 0 if torch.cuda.is_available() else -1
task = "text2text-generation" if "flan" in GENERATION_MODEL.lower() else "text-generation"
text_gen = pipeline(
task,
model=GENERATION_MODEL,
device=device,
token=HF_TOKEN,
max_new_tokens=MAX_NEW_TOKENS,
temperature=TEMPERATURE,
do_sample=TEMPERATURE > 0,
)
return HuggingFacePipeline(pipeline=text_gen)
def make_qa_chain():
"""Build the RetrievalQA chain with a custom prompt similar to your Kaggle notebook."""
if db_state["retriever"] is None:
# Try to load saved index if user forgot to click "Build index" after a restart
msg = try_load_index()
if db_state["retriever"] is None:
raise gr.Error("Please upload a PDF and click 'Build index' first. " + msg)
llm = make_llm()
prompt_template = PromptTemplate(
input_variables=["context", "question"],
template=(
"You are a helpful veterinary assistant. Answer the question using ONLY the information in the context below. "
"Explain the answer in **simple, clear language** that any pet owner can understand. "
"Avoid medical jargon unless absolutely necessary, and if you must use a term, explain it briefly. "
"Keep the answer short and easy to follow (2β4 sentences). '\n\n"
"Context:\n{context}\n\n"
"Question:\n{question}\n\n"
"Simple answer:"
),
)
qa_chain = load_qa_chain(llm=llm, chain_type="stuff", prompt=prompt_template)
qa = RetrievalQA(
combine_documents_chain=qa_chain,
retriever=db_state["retriever"],
return_source_documents=True, # keep sources for display
)
qa_state["qa"] = qa
return "β
LLM & QA chain are ready."
# ---------- helpers to display what the retriever returns ----------
def format_sources(docs_with_scores, show_text=True, max_chars=700):
"""
docs_with_scores: list[ (Document, score) ] as returned by similarity_search_with_score
"""
if not docs_with_scores:
return "_No retrieved chunks (check index + model match)._"
blocks = []
for i, (doc, score) in enumerate(docs_with_scores, 1):
meta = doc.metadata or {}
page = meta.get("page", "N/A")
src = meta.get("source", "")
text = (doc.page_content or "").strip().replace("\n", " ")
if show_text and len(text) > max_chars:
text = text[:max_chars] + "β¦"
blocks.append(
f"**Hit {i}** β score: `{score:.4f}` β page `{page}` \n"
f"`{src}`" + (f"\n> {text}" if show_text else "")
)
return "\n\n".join(blocks)
def ask_question(question: str, k: int, show_chunks: bool):
if not question or not question.strip():
return "Please type a question.", ""
if qa_state["qa"] is None:
raise gr.Error("Click 'Init model' after building/loading the index.")
# 1) Preview: what the index returns (same FAISS db behind the retriever)
# Note: lower score is better for some metrics; FAISS returns distance; we just display raw.
try:
docs_with_scores = db_state["db"].similarity_search_with_score(question, k=k)
except Exception as e:
docs_with_scores = []
preview = f"_Could not preview retrieved chunks: {e}_"
else:
preview = format_sources(docs_with_scores, show_text=show_chunks)
# 2) Run QA chain (this will also retrieve internally, but we already previewed)
result = qa_state["qa"]({"query": question})
raw = (result.get("result") or "").strip()
if "Answer:" in raw:
raw = raw.split("Answer:", 1)[-1].strip()
# Combine the final answer + what was retrieved
sources_header = f"### Retrieved from index `{INDEX_DIR}` (k={k}, embeddings=`{EMBEDDINGS_MODEL}`)\n\n"
return raw, sources_header + preview
def reset_states():
db_state["db"] = None
db_state["retriever"] = None
qa_state["qa"] = None
return "State cleared. Upload a PDF again or rely on the saved index.", "", 3, True
# ---------------------------------
# Gradio UI
# ---------------------------------
with gr.Blocks(title="RAG Khidmat") as demo:
gr.Markdown(
"""
# RAG Khidmat (PDF Q&A) β persistent index
This Space caches the FAISS index on disk so it survives app restarts.<br>
**Flow:** 1) Upload a PDF β 2) **Build index** (saves to disk) β 3) **Init model** β 4) Ask questions.
"""
)
with gr.Row():
pdf = gr.File(label="Upload PDF", file_types=[".pdf"], type="filepath")
with gr.Row():
build_btn = gr.Button("π¨ Build index (save)")
init_btn = gr.Button("βοΈ Init model")
load_btn = gr.Button("π¦ Load saved index")
clear_btn = gr.Button("β»οΈ Reset")
status = gr.Markdown(try_load_index())
with gr.Row():
question = gr.Textbox(label="Ask a question", placeholder="Type your question here...", scale=4)
topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Top-K")
show_chunks = gr.Checkbox(value=True, label="Show retrieved chunk text")
ask_btn = gr.Button("π€ Answer")
answer = gr.Markdown("")
sources = gr.Markdown("")
ask_btn.click(
fn=ask_question,
inputs=[question, topk, show_chunks],
outputs=[answer, sources],
api_name="/ask" # π Exposes API endpoint: /run/ask
)
build_btn.click(fn=build_index, inputs=[pdf], outputs=[status])
init_btn.click(fn=make_qa_chain, inputs=None, outputs=[status])
load_btn.click(fn=lambda: try_load_index(), inputs=None, outputs=[status])
# ask_btn.click(fn=ask_question, inputs=[question, topk, show_chunks], outputs=[answer, sources])
clear_btn.click(fn=reset_states, inputs=None, outputs=[status, answer, topk, show_chunks])
if __name__ == "__main__":
demo.queue().launch()
|