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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
# from transformers import pipeline
|
| 3 |
+
# from transformers.utils import logging
|
| 4 |
+
from huggingface_hub import InferenceClient
|
| 5 |
+
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
|
| 6 |
+
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 7 |
+
from llama_index.core.vector_stores import (MetadataFilters, ExactMatchFilter, )
|
| 8 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 9 |
+
import torch
|
| 10 |
+
from llama_index.core import (
|
| 11 |
+
VectorStoreIndex,
|
| 12 |
+
Document,
|
| 13 |
+
Settings,
|
| 14 |
+
)
|
| 15 |
+
import requests
|
| 16 |
+
import json
|
| 17 |
+
from llama_index.llms.huggingface import (HuggingFaceLLM, )
|
| 18 |
+
from llama_index.llms.huggingface_api import (HuggingFaceInferenceAPI, )
|
| 19 |
+
from llama_index.core.base.llms.types import ChatMessage
|
| 20 |
+
from huggingface_hub import login
|
| 21 |
+
import chromadb as chromadb
|
| 22 |
+
from chromadb.utils import embedding_functions
|
| 23 |
+
import shutil
|
| 24 |
+
import os
|
| 25 |
+
from io import StringIO
|
| 26 |
+
from llama_index.core.memory import ChatMemoryBuffer
|
| 27 |
+
|
| 28 |
+
memory = ChatMemoryBuffer.from_defaults(token_limit=3072)
|
| 29 |
+
#
|
| 30 |
+
|
| 31 |
+
last = 0
|
| 32 |
+
CHROMA_DATA_PATH = "chroma_data/"
|
| 33 |
+
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2" # "BAAI/bge-m3"
|
| 34 |
+
#LLM_NAME = "mistralai/Mistral-Nemo-Instruct-2407"
|
| 35 |
+
#LLM_NAME = "sswiss-ai/apertus-70b-instruct" # provider: publicai
|
| 36 |
+
#LLM_NAME = "openai/gpt-oss-20b"
|
| 37 |
+
LLM_NAME = "swiss-ai/apertus-8b-instruct"
|
| 38 |
+
#LLM_NAME = "aisingapore/Gemma-SEA-LION-v4-27B-IT"
|
| 39 |
+
#LLM_NAME = "W4D/YugoGPT-7B-Instruct-GGUF"
|
| 40 |
+
CHUNK_SIZE = 800
|
| 41 |
+
CHUNK_OVERLAP = 50
|
| 42 |
+
max_results = 3
|
| 43 |
+
min_len = 40
|
| 44 |
+
min_distance = 0.35
|
| 45 |
+
max_distance = 0.6
|
| 46 |
+
temperature = 0.7
|
| 47 |
+
max_tokens=5100
|
| 48 |
+
top_p=0.85
|
| 49 |
+
top_k=1000
|
| 50 |
+
frequency_penalty=0.0
|
| 51 |
+
repetition_penalty=1.12
|
| 52 |
+
presence_penalty=0.15
|
| 53 |
+
cs = "s0"
|
| 54 |
+
sp_flag = True
|
| 55 |
+
|
| 56 |
+
system_sr = "Zoveš se U-Chat AI asistent i pomažeš odgovorima korisniku usluga UFO Cowboy. Korisnik postavlja pitanje ili problem na koji očekuje rešenje. "
|
| 57 |
+
# " Ako ne znaš odgovor, reci da ne znaš, ne izmišljaj ga."
|
| 58 |
+
system_sr += " UFO Cowboy je potpuno otvoren svet fiktivnih ljudi i drugih oblika života "
|
| 59 |
+
|
| 60 |
+
chroma_client = chromadb.PersistentClient(CHROMA_DATA_PATH)
|
| 61 |
+
embedding_func = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 62 |
+
model_name=EMBED_MODEL
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
collection = chroma_client.get_or_create_collection(
|
| 66 |
+
name="chroma_data",
|
| 67 |
+
embedding_function=embedding_func,
|
| 68 |
+
metadata={"hnsw:space": "cosine"},
|
| 69 |
+
)
|
| 70 |
+
last = collection.count()
|
| 71 |
+
|
| 72 |
+
#
|
| 73 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 74 |
+
API_SECRET = os.getenv("api_secret")
|
| 75 |
+
#
|
| 76 |
+
login(token=(HF_TOKEN))
|
| 77 |
+
|
| 78 |
+
#system_prompt = system_sr
|
| 79 |
+
|
| 80 |
+
client = InferenceClient(LLM_NAME)
|
| 81 |
+
|
| 82 |
+
# "facebook/blenderbot-400M-distill", facebook/blenderbot-400M-distill, stabilityai/stablelm-zephyr-3b, BAAI/bge-small-en-v1.5
|
| 83 |
+
Settings.llm = HuggingFaceInferenceAPI(model_name=LLM_NAME,
|
| 84 |
+
# device_map="auto",
|
| 85 |
+
# system_prompt = system_prompt,
|
| 86 |
+
context_window=6144,
|
| 87 |
+
max_new_tokens=3072,
|
| 88 |
+
# stopping_ids=[50278, 50279, 50277, 1, 0],
|
| 89 |
+
generate_kwargs={"temperature": temperature, "top_p":top_p, "repetition_penalty": repetition_penalty,
|
| 90 |
+
"presence_penalty": presence_penalty, "frequency_penalty": frequency_penalty,
|
| 91 |
+
"top_k": top_k, "do_sample": False },
|
| 92 |
+
# tokenizer_kwargs={"max_length": 4096},
|
| 93 |
+
tokenizer_name=LLM_NAME,
|
| 94 |
+
hf_token = HF_TOKEN,
|
| 95 |
+
src = "models",
|
| 96 |
+
provider="publicai",
|
| 97 |
+
)
|
| 98 |
+
# "BAAI/bge-m3"
|
| 99 |
+
Settings.embed_model = HuggingFaceEmbedding(model_name=EMBED_MODEL)
|
| 100 |
+
#documents = [Document(text="Content ..."),
|
| 101 |
+
# ]
|
| 102 |
+
#index = VectorStoreIndex.from_documents(
|
| 103 |
+
# documents,
|
| 104 |
+
#)
|
| 105 |
+
vector_store = ChromaVectorStore(chroma_collection=collection)
|
| 106 |
+
index = VectorStoreIndex.from_vector_store(vector_store, embed_model=Settings.embed_model)
|
| 107 |
+
chat_engine = index.as_chat_engine(chat_mode="condense_plus_context", memory=memory, verbose=True)
|
| 108 |
+
# best condense_question context condense_plus_context
|
| 109 |
+
#query_engine = index.as_query_engine(verbose=True)
|
| 110 |
+
|
| 111 |
+
def upload_file(filepath):
|
| 112 |
+
documents = SimpleDirectoryReader(filepath).load_data()
|
| 113 |
+
index = VectorStoreIndex.from_documents(documents)
|
| 114 |
+
#query_engine = index.as_query_engine()
|
| 115 |
+
#condense_question condense_plus_context
|
| 116 |
+
chat_engine = index.as_chat_engine(verbose=True)
|
| 117 |
+
return filepath
|
| 118 |
+
|
| 119 |
+
def resetChat():
|
| 120 |
+
chat_engine.reset()
|
| 121 |
+
print("Restarted!!!")
|
| 122 |
+
return True
|
| 123 |
+
|
| 124 |
+
def rag(input_text, history, jezik, request: gr.Request): # , file):
|
| 125 |
+
global sp_flag
|
| 126 |
+
# if (btn):
|
| 127 |
+
# resetChat()
|
| 128 |
+
# print(history, input_text)
|
| 129 |
+
## if (file):
|
| 130 |
+
documents = []
|
| 131 |
+
#!!! for f in file:
|
| 132 |
+
#!!! documents += SimpleDirectoryReader(f).load_data()
|
| 133 |
+
# f = file + "*.pdf"
|
| 134 |
+
## pathname = os.path.dirname
|
| 135 |
+
# shutil.copyfile(file.name, path)
|
| 136 |
+
## print("pathname=", pathname)
|
| 137 |
+
## print("basename=", os.path.basename(file))
|
| 138 |
+
## print("filename=", file.name)
|
| 139 |
+
## documents = SimpleDirectoryReader(file).load_data()
|
| 140 |
+
#!!! index2 = VectorStoreIndex.from_documents(documents)
|
| 141 |
+
## query_engine = index2.as_query_engine()
|
| 142 |
+
# return query_engine.query(input_text)
|
| 143 |
+
# return history.append({"role": "assistant", "content": query_engine.query(input_text)})
|
| 144 |
+
## return history + [[input_text, query_engine.query(input_text)]]
|
| 145 |
+
# collection.add(
|
| 146 |
+
# documents=documents,
|
| 147 |
+
# ids=[f"id{last+i}" for i in range(len(documents))],
|
| 148 |
+
# metadatas=[{"state": "s0", "next": "s0", "used": False, "source": 'None', "page": -1, "lang": jezik } for i in range(len(documents)) ]
|
| 149 |
+
# )
|
| 150 |
+
## else:
|
| 151 |
+
### query_results = collection.query(
|
| 152 |
+
#query_engine = index.as_query_engine(
|
| 153 |
+
# similarity_top_k=3,
|
| 154 |
+
# vector_store_query_mode="default",
|
| 155 |
+
# filters=MetadataFilters(
|
| 156 |
+
# filters=[
|
| 157 |
+
# ExactMatchFilter(key="lang", value=jezik),
|
| 158 |
+
# ]
|
| 159 |
+
# ),
|
| 160 |
+
# alpha=None,
|
| 161 |
+
# doc_ids=None,
|
| 162 |
+
#)
|
| 163 |
+
#query_results = index.query(
|
| 164 |
+
# query_texts = [ input_text ],
|
| 165 |
+
# n_results = max_results,
|
| 166 |
+
# where = { "lang": jezik },
|
| 167 |
+
# #where = { "$and": [ {"lang": jezik}, {"page": { "$nin": [ -1 ]}}]},
|
| 168 |
+
# #where = { "$and": [ {"$and": [ { "$or": [ {"state": self.cs }, { "page": { "$nin": [ -1 ] } } ] } , { "used": False } ] } ,
|
| 169 |
+
# # {"lang": jezik } ] },
|
| 170 |
+
#)
|
| 171 |
+
#jezik = "N/A"
|
| 172 |
+
system_prompt = ""
|
| 173 |
+
match jezik:
|
| 174 |
+
case 'hrvatski':
|
| 175 |
+
o_jezik = 'na hrvatskom jeziku, gramatički točno.'
|
| 176 |
+
system_prompt = system_sr + "Call centar telefon je 095 1000 444 za privatne i 095 1000 500 za poslovne korisnike. Stranica podrške je <https://tele mach.hr/podrska>." + "Odgovaraj isključivo " + o_jezik
|
| 177 |
+
case 'slovenski':
|
| 178 |
+
o_jezik = 'v slovenščini, slovnično pravilen.'
|
| 179 |
+
system_prompt = system_sr + "Call centar i pomoč za fizične uporabnike: 070 700 700.stran za podporo je <https://telemach.si/pomoc>. " + "Odgovor isključivo " + o_jezik
|
| 180 |
+
case 'srpski':
|
| 181 |
+
o_jezik = 'na srpskom jeziku, gramatički ispravno.'
|
| 182 |
+
system_prompt = system_sr + "Call centar telefon je 19900 za sve korisnike. Stranica podrške je <https://sbb.rs/podrska/>. " + "Odgovaraj isključivo " + o_jezik
|
| 183 |
+
case 'makedonski':
|
| 184 |
+
o_jezik = 'на македонски јазикот граматички точно.'
|
| 185 |
+
system_prompt = system_sr + "Stranica podrške je https://mn.nettvplus.com/me/podrska/ za NetTV. " + "Oдговори исклучиво " + o_jezik
|
| 186 |
+
case 'Eksperimentalna opcija':
|
| 187 |
+
o_jezik = 'N/A'
|
| 188 |
+
system_prompt = system_sr + "Call centar telefon je 12755 za Crnu Goru, 0800 31111 za BIH, 070 700 700 u Sloveniji, 19900 u Srbiji, 095 1000 444 za hrvatske korisnike. Odgovori na jeziku istom kao i u postavljenom pitanju ili problemu korisnika."
|
| 189 |
+
print("jezik: "+o_jezik)
|
| 190 |
+
system_prompt = system_prompt + " Sledi pitanje ili problem korisnika, sa kojim dalje komuniciraš: "
|
| 191 |
+
if sp_flag:
|
| 192 |
+
sp_flag = False
|
| 193 |
+
else:
|
| 194 |
+
system_prompt = ""
|
| 195 |
+
# if (o_jezik!='N/A'):
|
| 196 |
+
# input_text += " - odgovori " + o_jezik + "."
|
| 197 |
+
# Settings.llm.system_prompt = system_prompt
|
| 198 |
+
response = chat_engine.chat(str({"role": "user", "content": system_prompt + input_text})).response
|
| 199 |
+
# response = query_engine.query(input_text)
|
| 200 |
+
session_hash = request.session_hash
|
| 201 |
+
url = "https://houseofplaying.com/FBMod/public/api.php" # An example public API
|
| 202 |
+
payload = {
|
| 203 |
+
"session_hash": session_hash,
|
| 204 |
+
"input_query": input_text,
|
| 205 |
+
"response": response
|
| 206 |
+
}
|
| 207 |
+
headers = {
|
| 208 |
+
"Authorization": "Bearer " + API_SECRET,
|
| 209 |
+
"Content-Type": "application/json"
|
| 210 |
+
}
|
| 211 |
+
try:
|
| 212 |
+
api_response = requests.post(url, json=payload, headers=headers)
|
| 213 |
+
except:
|
| 214 |
+
print("POST error for "+session_hash)
|
| 215 |
+
return response
|
| 216 |
+
# gr.Textbox(label="Pitanje:", lines=6),
|
| 217 |
+
# outputs=[gr.Textbox(label="Odgovor:", lines=6)],
|
| 218 |
+
# ChatMessage(role="assistant", content="Kako Vam mogu pomoći?")
|
| 219 |
+
|
| 220 |
+
with gr.Blocks() as iface:
|
| 221 |
+
ichat = gr.ChatInterface(fn=rag,
|
| 222 |
+
title="UChat",
|
| 223 |
+
description="Postavite pitanje ili opišite problem koji imate - nakon promene jezika ili pre početka nove sesije sa agentom pritisnite dugme 'Briši sve - razgovor ispočetka'",
|
| 224 |
+
chatbot=gr.Chatbot(placeholder="Kako Vam mogu pomoći?", type="tuples", label="Agent podrške", height=350),
|
| 225 |
+
textbox=gr.Textbox(placeholder="Pitanje ili opis problema", container=False, scale=7),
|
| 226 |
+
autofocus = True,
|
| 227 |
+
theme="soft",
|
| 228 |
+
examples = [
|
| 229 |
+
["Ne radi mi internet", "srpski", ],
|
| 230 |
+
["Možete li mi popraviti kompjuter koji koristi internet?", "srpski", ],
|
| 231 |
+
["Ne radi mi daljinski upravljač, šta da radim?", "srpski", ],
|
| 232 |
+
["EON daljinski upravljalnik mi ne deluje, kaj naj naredim?", "slovenski", ],
|
| 233 |
+
["Мојот кабелски прием не работи, што треба да направам?", "makedonski", ],
|
| 234 |
+
],
|
| 235 |
+
cache_examples=False,
|
| 236 |
+
retry_btn=None,
|
| 237 |
+
undo_btn=None,
|
| 238 |
+
clear_btn="Briši sve - razgovor ispočetka",
|
| 239 |
+
additional_inputs = [gr.Dropdown(["slovenski", "hrvatski", "srpski", "makedonski", "Eksperimentalna opcija"], value="srpski", label="Jezik", info="komunikacije"),
|
| 240 |
+
# gr.File()
|
| 241 |
+
],
|
| 242 |
+
additional_inputs_accordion="Jezik i ostale opcije",
|
| 243 |
+
)
|
| 244 |
+
# login_button = gr.LoginButton("Hugging Face login", size="lg")
|
| 245 |
+
ichat.clear_btn.click(resetChat)
|
| 246 |
+
|
| 247 |
+
#with gr.Blocks() as iface:
|
| 248 |
+
# gr.Markdown("Uchat")
|
| 249 |
+
# file_out = gr.File()
|
| 250 |
+
# with gr.Row():
|
| 251 |
+
# with gr.Column(scale=1):
|
| 252 |
+
# inp = gr.Textbox(label="Pitanje:", lines=6)
|
| 253 |
+
# u = gr.UploadButton("Upload a file", file_count="single")
|
| 254 |
+
# with gr.Column(scale=1):
|
| 255 |
+
# out = gr.Textbox(label="Odgovor:", lines=6)
|
| 256 |
+
# sub = gr.Button("Pokreni")
|
| 257 |
+
#
|
| 258 |
+
# u.upload(upload_file, u, file_out)
|
| 259 |
+
# sub.click(rag, inp, out)
|
| 260 |
+
|
| 261 |
+
iface.launch(share=True)
|