File size: 5,289 Bytes
9f5c02d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json, re, os, pickle, numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoTokenizer as GenAutoTokenizer
import openai
from dotenv import load_dotenv

os.environ["TOKENIZERS_PARALLELISM"] = "false"
load_dotenv()

# Use the environment variable for the API key
openai.api_key = os.getenv("OPENAI_API_KEY")

####################################
# 1. Load and Clean JSON Data
####################################
DATA_PATH = "dbcontent.txt"
with open(DATA_PATH, "r") as f:
    raw = f.read()
cleaned = re.sub(r'ObjectId\("([^"]+)"\)', r'"\1"', raw)
data = json.loads(cleaned)
documents = [
    {
        "transcript": doc["transcribetext"],
        "coursename": doc.get("coursename", "Unknown Course"),
        "videoname": doc.get("videoname", "Unknown Video"),
        "videourl": doc.get("videourl", "No URL")
    }
    for doc in data if "transcribetext" in doc
]

####################################
# 2. Chunking the Documents
####################################
def chunk_text(text, tokenizer, max_tokens=512):
    tokens = tokenizer.encode(text)
    return [
        tokenizer.decode(tokens[i:i+max_tokens], skip_special_tokens=True)
        for i in range(0, len(tokens), max_tokens)
    ]

sbert_tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
all_chunks = []
for doc in documents:
    for chunk in chunk_text(doc["transcript"], sbert_tokenizer, max_tokens=512):
        all_chunks.append({
            "chunk": chunk,
            "coursename": doc["coursename"],
            "videoname": doc["videoname"],
            "videourl": doc["videourl"]
        })

####################################
# 3. Build a TF-IDF Index for Fast Retrieval with Caching
####################################
chunk_texts = [item["chunk"] for item in all_chunks]
vectorizer_cache = "vectorizer.pkl"
tfidf_cache = "tfidf_matrix.pkl"

if os.path.exists(vectorizer_cache) and os.path.exists(tfidf_cache):
    with open(vectorizer_cache, "rb") as f:
        vectorizer = pickle.load(f)
    with open(tfidf_cache, "rb") as f:
        tfidf_matrix = pickle.load(f)
else:
    vectorizer = TfidfVectorizer(stop_words='english')
    tfidf_matrix = vectorizer.fit_transform(chunk_texts)
    with open(vectorizer_cache, "wb") as f:
        pickle.dump(vectorizer, f)
    with open(tfidf_cache, "wb") as f:
        pickle.dump(tfidf_matrix, f)

def get_relevant_chunk(query):
    query_vec = vectorizer.transform([query])
    cosine_sim = cosine_similarity(query_vec, tfidf_matrix)
    idx = np.argmax(cosine_sim)
    return all_chunks[idx]

####################################
# 4. Set Up Generation Model (DialoGPT-medium)
####################################
gen_tokenizer = GenAutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
gen_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium")
def generate_answer(prompt):
    inputs = gen_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
    outputs = gen_model.generate(inputs["input_ids"], max_new_tokens=100, pad_token_id=gen_tokenizer.eos_token_id)
    return gen_tokenizer.decode(outputs[0], skip_special_tokens=True)

####################################
# 5. Refine the Answer Using GPT-3.5-turbo (ChatGPT)
####################################
def refine_answer(initial_answer, query, sources_text):
    refinement_prompt = (
        "You are an expert editor. Rewrite the answer below so that it is clear, grammatically correct, "
        "and directly addresses the question in under 100 words. Do not include citation information, "
        "course name, video name, or URL. Use only the provided information and do not include external data.\n\n"
        f"Question: {query}\n\n"
        f"Initial Answer: {initial_answer}\n\n"
        f"Sources: {sources_text}\n\n"
        "Refined Answer:"
    )
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a skilled editor."},
            {"role": "user", "content": refinement_prompt}
        ],
        temperature=0.7,
        max_tokens=150
    )
    return response.choices[0].message["content"]


####################################
# 6. Chatbot Response with Citation and Refinement
####################################
def chatbot_response(query):
    relevant = get_relevant_chunk(query)
    context = relevant["chunk"]
    # Format the sources as HTML anchor tag to ensure they display fully
    sources_text = f"Course: {relevant['coursename']}, Video: <a href='{relevant['videourl']}' target='_blank'>{relevant['videoname']}</a>"
    prompt = (
        "Using only the context below, generate a concise, direct answer in under 100 words that addresses the question. "
        "Summarize and rephrase the relevant information in your own words.\n\n"
        f"Context:\n{context}\n\n"
        f"Question: {query}\n\n"
        "Answer:"
    )
    initial_answer = generate_answer(prompt)
    refined = refine_answer(initial_answer, query, sources_text)
    # Return refined answer along with the source information
    return f"{refined}\n\nSources:\n{sources_text}"