|
import pickle |
|
import numpy as np |
|
from sentence_transformers import SentenceTransformer |
|
from scipy.spatial.distance import cosine |
|
import gradio as gr |
|
from openai import OpenAI |
|
client=OpenAI() |
|
model = SentenceTransformer("quanthome/paraphrase-multilingual-MiniLM-L12-v2") |
|
|
|
def find_similar(text, vector_map, model, top_n=5): |
|
query_embedding = model.encode([text])[0] |
|
similarities = [] |
|
|
|
for key, embedding in vector_map.items(): |
|
similarity = 1 - cosine(query_embedding, embedding) |
|
similarities.append((key, similarity)) |
|
|
|
|
|
similarities = sorted(similarities, key=lambda x: x[1], reverse=True) |
|
|
|
return similarities[:top_n] |
|
|
|
|
|
|
|
with open('vector_map.pkl', 'rb') as f: |
|
vector_map = pickle.load(f) |
|
|
|
|
|
def szukaj(query_text): |
|
top_n_results = find_similar(query_text, vector_map, model, top_n=5) |
|
context='' |
|
for text, similarity in top_n_results: |
|
context=context+text |
|
jaczat=client.chat.completions.create( |
|
model='gpt-4o', |
|
temperature=0.2, |
|
max_tokens=512, |
|
messages=[ |
|
{'role': 'system', |
|
'content': 'Nazywasz się Jacek i jesteś ekspertem cyfrowej dostępności. Odpowiadasz konkretnie i krótko na pytania na podstawie kontekstu podanego przez użytkownika.'}, |
|
{'role': 'user', |
|
'content': query_text+context} |
|
] |
|
) |
|
return jaczat.choices[0].message.content |
|
demo=gr.Interface( |
|
fn=szukaj, |
|
inputs=gr.Text(label='Pytanie'), |
|
outputs=gr.Markdown(), |
|
theme=gr.themes.Glass(font='OpenSans'), |
|
title='JaCzat', |
|
description='Tu możesz zapytać o wszystko dotyczące cyfrowej dostępności, w tym przede wszystkim WCAG. Jeżeli odpowiedź jest Twoim zdaniem błędna lub niesatysfakcjonująca, kliknij na flagę "Źle". A jeżeli odpowiedź jest prawidłowa - kliknij "Dobrze". To pomoże mi rozwijać pomocnika na przyszłość. Nie zbieram żadnych danych osobowych i proszę Cię, żeby ich tu nie wpisywać. Potem będę miał problem z ich usuwaniem.', |
|
submit_btn='Zapytaj', |
|
clear_btn='Wyczyść', |
|
allow_flagging='manual', |
|
show_progress='minimal', |
|
flagging_dir='jaczat.csv', |
|
flagging_options=['Dobrze', 'Źle'] |
|
).launch(inbrowser=True, show_api=False) |