Spaces:
Runtime error
Runtime error
created main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from sentence_transformers import SentenceTransformer, util
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
|
| 11 |
+
class PlantChatbot:
|
| 12 |
+
def __init__(self, preprocessed_data_path: str):
|
| 13 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
print(f"Using device: {self.device}")
|
| 15 |
+
|
| 16 |
+
self.embedding_model = SentenceTransformer(
|
| 17 |
+
model_name_or_path="all-mpnet-base-v2",
|
| 18 |
+
device=self.device
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
self.load_data(preprocessed_data_path)
|
| 22 |
+
|
| 23 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 24 |
+
"Qwen/Qwen2.5-1.5B-Instruct",
|
| 25 |
+
trust_remote_code=True
|
| 26 |
+
)
|
| 27 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
"Qwen/Qwen2.5-1.5B-Instruct",
|
| 29 |
+
device_map="auto",
|
| 30 |
+
trust_remote_code=True,
|
| 31 |
+
torch_dtype=torch.float16
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def load_data(self, preprocessed_data_path: str):
|
| 35 |
+
df = pd.read_csv(preprocessed_data_path)
|
| 36 |
+
|
| 37 |
+
def parse_embedding(embedding_str):
|
| 38 |
+
try:
|
| 39 |
+
embedding_str = embedding_str.strip()
|
| 40 |
+
if embedding_str.startswith('[') and embedding_str.endswith(']'):
|
| 41 |
+
embedding_str = embedding_str[1:-1]
|
| 42 |
+
return np.fromstring(embedding_str, sep=',')
|
| 43 |
+
except:
|
| 44 |
+
print(f"Error parsing embedding: {embedding_str[:100]}...")
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
df["embedding"] = df["embedding"].apply(parse_embedding)
|
| 48 |
+
df = df.dropna(subset=['embedding'])
|
| 49 |
+
self.chunks_data = df.to_dict(orient="records")
|
| 50 |
+
|
| 51 |
+
embeddings_array = np.stack(df["embedding"].values)
|
| 52 |
+
self.embeddings = torch.tensor(embeddings_array, dtype=torch.float32).to(self.device)
|
| 53 |
+
|
| 54 |
+
def retrieve_relevant_chunks(self, query: str, n_chunks: int = 5) -> list[dict]:
|
| 55 |
+
query_embedding = self.embedding_model.encode(query, convert_to_tensor=True).to(self.device)
|
| 56 |
+
|
| 57 |
+
if len(query_embedding.shape) == 1:
|
| 58 |
+
query_embedding = query_embedding.unsqueeze(0)
|
| 59 |
+
|
| 60 |
+
scores = util.dot_score(query_embedding, self.embeddings)[0]
|
| 61 |
+
_, indices = torch.topk(scores, k=min(n_chunks, len(self.chunks_data)))
|
| 62 |
+
indices = indices.cpu().numpy()
|
| 63 |
+
|
| 64 |
+
return [
|
| 65 |
+
{
|
| 66 |
+
"sentence_chunk": self.chunks_data[i]["sentence_chunk"],
|
| 67 |
+
"Reference": self.chunks_data[i]["Reference"]
|
| 68 |
+
}
|
| 69 |
+
for i in indices
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
def generate_response(self, query: str):
|
| 73 |
+
try:
|
| 74 |
+
context_chunks = self.retrieve_relevant_chunks(query)
|
| 75 |
+
prompt = self.format_prompt(query, context_chunks)
|
| 76 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", padding=True)
|
| 77 |
+
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
| 78 |
+
|
| 79 |
+
generated_text = ""
|
| 80 |
+
max_new_tokens = 4096
|
| 81 |
+
chunk_size = 50
|
| 82 |
+
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
for _ in range(0, max_new_tokens, chunk_size):
|
| 85 |
+
outputs = self.model.generate(
|
| 86 |
+
**inputs,
|
| 87 |
+
max_new_tokens=chunk_size,
|
| 88 |
+
do_sample=True,
|
| 89 |
+
temperature=0.7,
|
| 90 |
+
top_p=0.8,
|
| 91 |
+
repetition_penalty=1.05,
|
| 92 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 93 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 94 |
+
)
|
| 95 |
+
new_tokens = outputs[0][inputs['input_ids'].shape[1]:]
|
| 96 |
+
new_text = self.tokenizer.decode(new_tokens, skip_special_tokens=True)
|
| 97 |
+
generated_text += new_text
|
| 98 |
+
yield new_text
|
| 99 |
+
|
| 100 |
+
inputs['input_ids'] = outputs
|
| 101 |
+
|
| 102 |
+
if outputs[0][-1] == self.tokenizer.eos_token_id:
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
context_info = json.dumps({"context_items": context_chunks})
|
| 106 |
+
yield f"\n<context>{context_info}</context>"
|
| 107 |
+
except Exception as e:
|
| 108 |
+
print(f"Error generating response: {str(e)}")
|
| 109 |
+
yield "Error in processing your query."
|
| 110 |
+
|
| 111 |
+
@app.route("/chat", methods=["POST"])
|
| 112 |
+
def chat():
|
| 113 |
+
query = request.json.get('query')
|
| 114 |
+
chatbot = PlantChatbot("plant_data_chunks_and_embeddings.csv")
|
| 115 |
+
response = chatbot.generate_response(query)
|
| 116 |
+
return jsonify({"response": next(response)})
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
app.run(host='0.0.0.0', port=5000)
|