import os import re import json import torch from sentence_transformers import SentenceTransformer, util from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # ========================================== # STEP 1: Load Training Data Safely # ========================================== def load_training_data(data_folder): data = [] missing_code = 0 missing_query = 0 for file in os.listdir(data_folder): if file.endswith(".json"): path = os.path.join(data_folder, file) with open(path, "r", encoding="utf-8") as f: try: entries = json.load(f) for e in entries: if not e.get("pandas_code"): missing_code += 1 continue if not (e.get("english") or e.get("query")): missing_query += 1 continue data.append(e) except Exception as e: print(f"โš ๏ธ Skipped {file}: {e}") print(f"๐Ÿ“š Loaded {len(data)} valid queryโ€“code pairs from {data_folder}") print(f"โš ๏ธ Skipped {missing_code} missing-code and {missing_query} missing-query entries.") return data # ========================================== # STEP 2: Enhanced Retriever # ========================================== class EnhancedRetriever: def __init__(self, data): self.model = SentenceTransformer("all-MiniLM-L6-v2") valid_data = [ item for item in data if (item.get("pandas_code") and (item.get("english") or item.get("query"))) ] if not valid_data: raise ValueError("No valid queryโ€“code pairs found in dataset!") self.queries = [ item.get("english") or item.get("query") for item in valid_data ] self.codes = [item["pandas_code"] for item in valid_data] print(f"โœ… Using {len(valid_data)} valid items for retrieval.") print("๐Ÿง  Encoding queries for retrieval...") self.query_embeddings = self.model.encode(self.queries, convert_to_tensor=True) def retrieve_best_match(self, user_query, top_k=3): user_emb = self.model.encode(user_query, convert_to_tensor=True) similarity = util.pytorch_cos_sim(user_emb, self.query_embeddings)[0] top_results = torch.topk(similarity, k=top_k) results = [] for i in range(top_k): results.append({ "query": self.queries[top_results.indices[i]], "pandas_code": self.codes[top_results.indices[i]], "similarity": float(top_results.values[i]) }) return results # ========================================== # STEP 3: Generator (CodeT5 / fine-tuned model) # ========================================== class Generator: def __init__(self, model_dir="./text2code_model"): if not os.path.exists(model_dir): print("โš™๏ธ No fine-tuned model found โ€” using base CodeT5.") model_dir = "Salesforce/codet5-small" self.tokenizer = AutoTokenizer.from_pretrained(model_dir) self.model = AutoModelForSeq2SeqLM.from_pretrained(model_dir) def generate(self, query): prompt = f"Generate Pandas code for: {query}" inputs = self.tokenizer(prompt, return_tensors="pt") outputs = self.model.generate(**inputs, max_length=128) return self.tokenizer.decode(outputs[0], skip_special_tokens=True) # ========================================== # STEP 4: Adaptation Utilities # ========================================== def extract_column_names(text): """Extract potential column names from text""" words = re.findall(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b', text) stopwords = { 'show', 'display', 'find', 'get', 'the', 'and', 'or', 'where', 'what', 'how', 'many', 'much', 'list', 'give', 'me', 'all', 'with', 'for', 'bottom', 'top', 'average', 'mean', 'sum', 'median', 'count', 'minimum', 'maximum', 'highest', 'lowest' } cols = [w for w in words if w.lower() not in stopwords and len(w) > 2] return [normalize_name(c) for c in cols] def extract_values(text): """Extract quoted values and numbers from text""" quoted = re.findall(r"'([^']*)'", text) numbers = re.findall(r'\b\d+\b', text) return quoted + numbers ##commented for only the testing it is working but not only normalize # def enhanced_adaptation(user_query, code, original_retrieved_query): # """More intelligent code adaptation""" # query_columns = extract_column_names(user_query) # original_columns = extract_column_names(original_retrieved_query) # query_values = extract_values(user_query) # original_values = extract_values(original_retrieved_query) # new_code = code # for orig_col, new_col in zip(original_columns, query_columns): # if orig_col and new_col and orig_col.lower() != new_col.lower(): # for pattern in [rf"'{orig_col}'", rf'"{orig_col}"', rf"\b{orig_col}\b"]: # new_code = re.sub(pattern, new_col, new_code, flags=re.IGNORECASE) # for orig_val, new_val in zip(original_values, query_values): # if orig_val and new_val and orig_val != new_val: # new_code = re.sub(rf"'{re.escape(orig_val)}'", f"'{new_val}'", new_code) # new_code = re.sub(rf'"{re.escape(orig_val)}"', f'"{new_val}"', new_code) # new_code = re.sub(rf"\b{re.escape(orig_val)}\b", new_val, new_code) # new_code = adapt_operations_based_on_query(user_query, new_code) # new_code = adapt_filters_based_on_query(user_query, new_code) # return new_code def enhanced_adaptation(user_query, code, original_retrieved_query): """Smarter code adaptation with normalized column matching""" query_columns = extract_column_names(user_query) original_columns = extract_column_names(original_retrieved_query) query_values = extract_values(user_query) original_values = extract_values(original_retrieved_query) new_code = code # ๐Ÿ†• Replace columns based on normalized mapping for orig_col, new_col in zip(original_columns, query_columns): if orig_col and new_col and normalize_name(orig_col) != normalize_name(new_col): for pattern in [rf"'{orig_col}'", rf'"{orig_col}"', rf"\b{orig_col}\b"]: new_code = re.sub(pattern, new_col, new_code, flags=re.IGNORECASE) # ๐Ÿ†• Optional: map normalized query columns to known dataset columns if hasattr(bot, "col_map"): for norm_col in query_columns: if norm_col in bot.col_map: correct_name = bot.col_map[norm_col] new_code = re.sub(rf"\b{norm_col}\b", correct_name, new_code, flags=re.IGNORECASE) # Keep value and operation adaptation for orig_val, new_val in zip(original_values, query_values): if orig_val and new_val and orig_val != new_val: new_code = re.sub(rf"'{re.escape(orig_val)}'", f"'{new_val}'", new_code) new_code = re.sub(rf'"{re.escape(orig_val)}"', f'"{new_val}"', new_code) new_code = re.sub(rf"\b{re.escape(orig_val)}\b", new_val, new_code) new_code = adapt_operations_based_on_query(user_query, new_code) new_code = adapt_filters_based_on_query(user_query, new_code) return new_code def adapt_operations_based_on_query(query, code): q = query.lower() c = code if any(word in q for word in ["average", "mean", "avg"]): c = re.sub(r"\.(sum|min|max|count)\(\)", ".mean()", c) elif any(word in q for word in ["total", "sum", "add", "together"]): c = re.sub(r"\.(mean|min|max|count)\(\)", ".sum()", c) elif any(word in q for word in ["minimum", "min", "lowest", "smallest"]): c = re.sub(r"\.(mean|sum|max|count)\(\)", ".min()", c) elif any(word in q for word in ["maximum", "max", "highest", "largest"]): c = re.sub(r"\.(mean|sum|min|count)\(\)", ".max()", c) elif any(word in q for word in ["count", "number", "how many"]): c = re.sub(r"\.(mean|sum|min|max)\(\)", ".count()", c) return c def adapt_filters_based_on_query(query, code): q = query.lower() c = code if "status" in q and "rejected" in q: c = re.sub(r"df\[df\['\w+'\] == '[^']*'\]", "df[df['Status'] == 'rejected']", c) elif "status" in q and "approved" in q: c = re.sub(r"df\[df\['\w+'\] == '[^']*'\]", "df[df['Status'] == 'approved']", c) if "top" in q and "head" not in c: nums = re.findall(r'\d+', q) if nums: c = re.sub(r"\.tail\(\d+\)", f".head({nums[0]})", c) if "head" not in c and "sort_values" in c: c += f".head({nums[0]})" elif "bottom" in q and "tail" not in c: nums = re.findall(r'\d+', q) if nums: c = re.sub(r"\.head\(\d+\)", f".tail({nums[0]})", c) if "tail" not in c and "sort_values" in c: c += f".tail({nums[0]})" return c # ========================================== # STEP 5: Template Selection # ========================================== def select_best_template(retrieved_results, user_query): user_query_lower = user_query.lower() user_ops = [] if any(op in user_query_lower for op in ['average', 'mean', 'avg']): user_ops.append('mean') if any(op in user_query_lower for op in ['sum', 'total']): user_ops.append('sum') if any(op in user_query_lower for op in ['median']): user_ops.append('median') if any(op in user_query_lower for op in ['count', 'number']): user_ops.append('count') if any(op in user_query_lower for op in ['minimum', 'min', 'lowest']): user_ops.append('min') if any(op in user_query_lower for op in ['maximum', 'max', 'highest']): user_ops.append('max') if any(op in user_query_lower for op in ['group', 'grouped']): user_ops.append('groupby') if any(op in user_query_lower for op in ['filter', 'where', 'condition']): user_ops.append('filter') best_score = -1 best_result = retrieved_results[0] for result in retrieved_results: score = result["similarity"] code = result["pandas_code"].lower() for op in user_ops: if op in code: score += 0.1 if 'groupby' in user_ops and 'groupby' in code: score += 0.15 if 'filter' in user_ops and 'df[' in code and '==' in code: score += 0.15 if score > best_score: best_score = score best_result = result return best_result # ========================================== # STEP 6: Validation & Post-Processing # ========================================== def validate_code_against_query(code, user_query): query_lower = user_query.lower() code_lower = code.lower() issues = [] if any(w in query_lower for w in ['average', 'mean', 'avg']) and 'mean' not in code_lower: issues.append("Query asks for average but code doesn't use mean()") if any(w in query_lower for w in ['sum', 'total']) and 'sum' not in code_lower: issues.append("Query asks for sum but code doesn't use sum()") if 'median' in query_lower and 'median' not in code_lower: issues.append("Query asks for median but code doesn't use median()") if any(w in query_lower for w in ['group', 'grouped']) and 'groupby' not in code_lower: issues.append("Query asks for grouping but code doesn't use groupby()") if any(w in query_lower for w in ['filter', 'where']) and '==' not in code_lower: issues.append("Query asks for filtering but code doesn't have filter condition") return issues def post_process_code(code, user_query): code = re.sub(r'\.groupby\(\)\.groupby\(\)', '.groupby()', code) if 'df[' not in code and "df." not in code and "groupby" in code: code = f"df.{code}" if "=" not in code else f"df[{code}]" code = re.sub(r'\.\.', '.', code) return code def normalize_name(name): """Normalize column names for consistent comparison""" if not isinstance(name, str): return name # Lowercase, remove special chars and spaces return re.sub(r'[^a-z0-9]', '', name.lower()) # ========================================== # STEP 7: Main Hybrid System # ========================================== class RobustHybridText2Code: def __init__(self, data_folder="data", model_dir=r"D:\final_claimbotics\claimbotics_model\kaggle\working\codegen_model\final_model"): self.data = load_training_data(data_folder) self.retriever = EnhancedRetriever(self.data) self.generator = Generator(model_dir) all_cols = set() for item in self.data: code = item.get("pandas_code", "") # Extract column names from code strings cols = re.findall(r"df\[['\"]([^'\"]+)['\"]\]", code) all_cols.update(cols) self.col_map = {normalize_name(c): c for c in all_cols} def get_code(self, user_query): retrieved_results = self.retriever.retrieve_best_match(user_query, top_k=3) best = select_best_template(retrieved_results, user_query) print(f"๐Ÿ” [Best Match Similarity: {best['similarity']:.2f}]") print(f"๐Ÿ“ Original Query: {best['query']}") if best["similarity"] > 0.90: print("๐ŸŽฏ High similarity (โ‰ฅ 0.90) โ€” using code directly from data.") code = best["pandas_code"] elif best["similarity"] >= 0.75: print("๐Ÿ”„ Using retrieved code with enhanced adaptation...") code = enhanced_adaptation(user_query, best["pandas_code"], best["query"]) else: print("๐Ÿค– Low similarity โ€” generating new code...") code = self.generator.generate(user_query) code = post_process_code(code, user_query) issues = validate_code_against_query(code, user_query) if issues: print(f"โš ๏ธ Validation issues: {issues}") return code # ========================================== # STEP 8: Run Interactive Chat # ========================================== if __name__ == "__main__": print("๐Ÿ’ฌ Enhanced ClaimBotics Hybrid Textโ†’Code System Ready!\n") print("=" * 60) bot = RobustHybridText2Code( data_folder="data", model_dir=r"D:\final_claimbotics\claimbotics_model\kaggle\working\codegen_model\final_model" ) while True: user_input = input("\n๐Ÿง‘ You: ").strip() if user_input.lower() in ["exit", "quit", "bye"]: print("๐Ÿ‘‹ Goodbye!") break if not user_input: continue try: code = bot.get_code(user_input) print(f"\n๐Ÿค– Suggested Pandas Code:\n{code}") print("=" * 60) except Exception as e: print(f"โŒ Error: {e}") print("Please try again with a different query.")