mod
This commit is contained in:
parent
c1ba5ae5be
commit
51b505b6c1
108
gemma-faiss.py
108
gemma-faiss.py
|
|
@ -1,20 +1,23 @@
|
||||||
import os
|
import os
|
||||||
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import faiss
|
import faiss
|
||||||
import gradio as gr
|
import numpy as np
|
||||||
import torch
|
|
||||||
from sentence_transformers import SentenceTransformer
|
|
||||||
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
||||||
import ollama
|
import ollama
|
||||||
|
import gradio as gr
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
|
||||||
# 1️⃣ Inicjalizacja modelu do embeddingów
|
# === KONFIGURACJA ===
|
||||||
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
model_name = "gemma:2b" # Nazwa modelu Ollama
|
||||||
|
faiss_index_path = "faiss_index.idx" # Plik indeksu FAISS
|
||||||
|
kodeks_file = "kodeks_pracy.txt" # Plik z treścią kodeksu pracy
|
||||||
|
embedding_model = SentenceTransformer("all-MiniLM-L6-v2") # Model do embedowania tekstu
|
||||||
|
|
||||||
# 2️⃣ Dodanie dokumentów i embeddingów
|
# === KROK 1: WCZYTYWANIE KODEKSU PRACY ===
|
||||||
def read_documents_from_file(file_path):
|
def load_kodeks(filepath):
|
||||||
with open(file_path, 'r', encoding='utf-8') as file:
|
with open(filepath, 'r', encoding='utf-8') as file:
|
||||||
content = file.read()
|
content = file.read()
|
||||||
articles = content.split('\n\n')
|
articles = content.split('\n\n')
|
||||||
documents = []
|
documents = []
|
||||||
|
|
@ -22,44 +25,59 @@ def read_documents_from_file(file_path):
|
||||||
if article.strip().startswith('Art.'):
|
if article.strip().startswith('Art.'):
|
||||||
documents.append(article.strip())
|
documents.append(article.strip())
|
||||||
return documents
|
return documents
|
||||||
#documents = [
|
|
||||||
# "Jak założyć firmę w Polsce?",
|
|
||||||
# "Jak rozliczyć podatek VAT?",
|
|
||||||
# "Procedura składania reklamacji w e-sklepie.",
|
|
||||||
# "Jakie dokumenty są potrzebne do rejestracji działalności?"
|
|
||||||
#]
|
|
||||||
file_path = './docs/kodekspracy.txt' # Zmień na właściwą ścieżkę
|
|
||||||
documents = read_documents_from_file(file_path)
|
|
||||||
|
|
||||||
# 3️⃣ Wygenerowanie embeddingów
|
# === KROK 2: TWORZENIE INDEKSU FAISS ===
|
||||||
embeddings = embed_model.encode(documents)
|
def create_faiss_index(sections):
|
||||||
|
embeddings = embedding_model.encode(sections, convert_to_numpy=True) # Tworzenie wektorów
|
||||||
|
index = faiss.IndexFlatL2(embeddings.shape[1]) # Indeks FAISS
|
||||||
|
index.add(embeddings) # Dodanie wektorów do FAISS
|
||||||
|
faiss.write_index(index, faiss_index_path) # Zapis indeksu
|
||||||
|
return index, sections
|
||||||
|
|
||||||
# 4️⃣ Inicjalizacja FAISS
|
# === KROK 3: WYSZUKIWANIE NAJBLIŻSZEGO FRAGMENTU ===
|
||||||
dim = embeddings.shape[1] # Wymiar embeddingu
|
def search_faiss(query, index, sections):
|
||||||
index = faiss.IndexFlatL2(dim)
|
query_vector = embedding_model.encode([query], convert_to_numpy=True) # Wektor zapytania
|
||||||
index.add(np.array(embeddings, dtype=np.float32))
|
_, idx = index.search(query_vector, 1) # Szukamy 1 najbliższego sąsiada
|
||||||
|
return sections[idx[0][0]] # Zwracamy najbardziej pasujący fragment kodeksu
|
||||||
|
|
||||||
# 5️⃣ Wczytanie modelu Ollama (Gemma 2)
|
# === KROK 4: GENEROWANIE ODPOWIEDZI Z OLLAMA ===
|
||||||
model_name = "hse.ably.do:latest" # Ścieżka do modelu w systemie
|
def generate_response(user_query):
|
||||||
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")
|
if not os.path.exists(faiss_index_path):
|
||||||
|
return "Błąd: Indeks FAISS nie istnieje. Uruchom aplikację z opcją --rebuild-index, aby go wygenerować."
|
||||||
|
|
||||||
# 6️⃣ Funkcja wyszukiwania w FAISS
|
try:
|
||||||
def search(query, k=5):
|
index = faiss.read_index(faiss_index_path) # Wczytanie indeksu FAISS
|
||||||
query_embedding = embed_model.encode([query]) # Przekształć zapytanie w embedding
|
except Exception as e:
|
||||||
_, indices = index.search(np.array(query_embedding, dtype=np.float32), k) # Szukaj w indeksie FAISS
|
return f"Błąd: Nie można załadować indeksu FAISS. Spróbuj odbudować go za pomocą --rebuild-index. Szczegóły: {str(e)}"
|
||||||
return indices # Zwróć indeksy najbardziej podobnych dokumentów
|
|
||||||
|
|
||||||
# 7️⃣ Funkcja generowania odpowiedzi z Ollama
|
sections = load_kodeks(kodeks_file) # Wczytanie kodeksu
|
||||||
def generate_response(query):
|
best_match = search_faiss(user_query, index, sections) # Znalezienie najbliższego fragmentu
|
||||||
indices = search(query) # Znajdź najbardziej podobne dokumenty
|
|
||||||
relevant_documents = [documents[i] for i in indices[0]] # Pobierz dokumenty na podstawie wyników wyszukiwania
|
# Kontekst dla Ollama
|
||||||
|
prompt = f"Odpowiedz na pytanie na podstawie następującego tekstu:\n\n{best_match}\n\nPytanie: {user_query}"
|
||||||
|
|
||||||
|
response = ollama.chat(model=model_name, messages=[{"role": "user", "content": prompt}])
|
||||||
|
return response.get("message", "Błąd: Nie udało się wygenerować odpowiedzi.")
|
||||||
|
|
||||||
|
# === KROK 5: URUCHOMIENIE INTERFEJSU WEBOWEGO ===
|
||||||
|
iface = gr.Interface(
|
||||||
|
fn=generate_response,
|
||||||
|
inputs=gr.Textbox(label="Zadaj pytanie o kodeks pracy"),
|
||||||
|
outputs=gr.Textbox(label="Odpowiedź"),
|
||||||
|
title="Asystent Kodeksu Pracy",
|
||||||
|
description="Wpisz pytanie, a system zwróci odpowiedni fragment kodeksu pracy."
|
||||||
|
)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--rebuild-index", action="store_true", help="Wymuś odbudowanie indeksu FAISS")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.rebuild_index or not os.path.exists(faiss_index_path):
|
||||||
|
print("Tworzenie nowego indeksu FAISS...")
|
||||||
|
sections = load_kodeks(kodeks_file)
|
||||||
|
create_faiss_index(sections)
|
||||||
|
else:
|
||||||
|
print("Indeks FAISS już istnieje.")
|
||||||
|
|
||||||
prompt = " ".join(relevant_documents) + " " + query # Przygotuj prompt
|
iface.launch(share=True)
|
||||||
response = ollama.chat(model=model_name, messages=[{"role": "user", "content": prompt}]) # Generowanie odpowiedzi przez Ollama
|
|
||||||
|
|
||||||
return response["text"]
|
|
||||||
|
|
||||||
# 8️⃣ Interfejs Gradio (Open-WebUI)
|
|
||||||
iface = gr.Interface(fn=generate_response, inputs="text", outputs="text")
|
|
||||||
|
|
||||||
iface.launch(share=True) # Uruchom interfejs
|
|
||||||
Loading…
Reference in New Issue