Skip to content

Commit b7fa14c

Browse files
committed
added colab test utility and expanded dummy data
1 parent 836a0ba commit b7fa14c

2 files changed

Lines changed: 161 additions & 29 deletions

File tree

colab_test.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import os
2+
import json
3+
import torch
4+
from src.inference.engine import InferenceEngine
5+
from src.evaluation.evaluator import Evaluator
6+
7+
def check_env():
8+
print("--- Environment Check ---")
9+
if torch.cuda.is_available():
10+
print(f"✅ GPU detected: {torch.cuda.get_device_name(0)}")
11+
print(f"VRAM available: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB")
12+
else:
13+
print("❌ No GPU detected. Mistral-7B will likely crash or be extremely slow.")
14+
print("-------------------------\n")
15+
16+
def run_sample_inference():
17+
print("--- Running Sample Inference ---")
18+
engine = InferenceEngine(adapter_path=None) # Zero-shot by default
19+
20+
test_prompts = [
21+
"How do I reset my password?",
22+
"My account is locked, what should I do?",
23+
"How can I update my billing info?"
24+
]
25+
26+
for prompt in test_prompts:
27+
print(f"\nPrompt: {prompt}")
28+
result = engine.generate(prompt)
29+
print(f"Response: {result['response']}")
30+
print(f"Latency: {result['latency']:.2f}s")
31+
print("\n-------------------------------\n")
32+
33+
def run_colab_evaluation(num_samples=20):
34+
print(f"--- Running Evaluation ({num_samples} samples) ---")
35+
evaluator = Evaluator(adapter_path=None)
36+
test_data_path = "data/processed/validation.jsonl"
37+
38+
if not os.path.exists(test_data_path):
39+
print(f"❌ Validation data not found at {test_data_path}. Run preprocessing first.")
40+
return
41+
42+
results, rouge, bleu = evaluator.run_comparison(test_data_path, num_samples=num_samples)
43+
44+
report = {
45+
"metrics": {
46+
"rouge": rouge,
47+
"bleu": bleu
48+
},
49+
"samples": results
50+
}
51+
52+
output_path = "colab_evaluation_report.json"
53+
with open(output_path, "w") as f:
54+
json.dump(report, f, indent=4)
55+
56+
print(f"\n✅ Evaluation complete. Report saved to: {output_path}")
57+
print("------------------------------------------\n")
58+
59+
if __name__ == "__main__":
60+
check_env()
61+
62+
print("What would you like to do in Colab?")
63+
print("1. Run sample inference (3 prompts)")
64+
print("2. Run full evaluation and save JSON")
65+
print("3. Both")
66+
67+
choice = input("Enter choice (1/2/3): ")
68+
69+
if choice in ['1', '3']:
70+
run_sample_inference()
71+
if choice in ['2', '3']:
72+
run_colab_evaluation(num_samples=20)

scripts/generate_dummy_data.py

Lines changed: 89 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,102 @@
11
import json
22
import random
3+
import os
34

4-
def generate_dummy_data(output_path: str, num_samples: int = 100):
5-
scenarios = [
6-
{
7-
"instruction": "How do I reset my password?",
8-
"response": "To reset your password, click on the 'Forgot Password' link on the login page. You will receive an email with instructions to create a new password. Make sure to check your spam folder if you don't see the email within a few minutes."
9-
},
10-
{
11-
"instruction": "My account is locked. What should I do?",
12-
"response": "If your account is locked due to multiple failed login attempts, it will automatically unlock after 30 minutes. Alternatively, you can contact our support team at support@example.com to request an immediate unlock after verifying your identity."
13-
},
14-
{
15-
"instruction": "How can I update my billing information?",
16-
"response": "You can update your billing information by navigating to the 'Settings' section of your dashboard and selecting 'Billing'. From there, you can add or remove credit cards and update your billing address."
17-
},
18-
{
19-
"instruction": "What is your refund policy?",
20-
"response": "We offer a full refund within 30 days of purchase for any reason. To request a refund, please submit a ticket through our support portal with your order number and the reason for the request."
21-
},
22-
{
23-
"instruction": "How do I integrate the API into my Python project?",
24-
"response": "To integrate our API, first install the client library using `pip install example-sdk`. Then, initialize the client with your API key: `from example import Client; client = Client(api_key='your_key')`. You can then use the client to make requests."
25-
}
26-
]
5+
def generate_dummy_data(output_path: str, num_samples: int = 500):
6+
"""Generates a larger, more diverse dataset for better evaluation."""
277

8+
categories = {
9+
"technical": [
10+
("How do I fix error code {code}?", "Error code {code} usually indicates a {reason}. Please try {fix} or restart the service."),
11+
("The API is returning a {status} error.", "A {status} error happens when {explanation}. Check your {check} and try again."),
12+
("My {component} is not responding.", "If the {component} is frozen, try clearing the cache in {folder} or re-installing the driver."),
13+
("How to install the {sdk} SDK?", "You can install the {sdk} SDK via {manager} using the command `{command}`."),
14+
("Where can I find my API keys?", "Your API keys are located in the 'Developer' tab of your dashboard under 'Security Settings'.")
15+
],
16+
"billing": [
17+
("I was overcharged for my {plan} subscription.", "Sorry for the trouble! Please email billing@example.com with your invoice number. We will process a refund for the {plan} difference."),
18+
("How do I cancel my {plan} plan?", "To cancel your {plan} plan, go to Settings > Billing and click 'Cancel Subscription' at the bottom of the page."),
19+
("Can I get a refund for the last {month}?", "Refunds for {month} are available if requested within 30 days. Please submit a request through the portal."),
20+
("Do you accept {method}?", "Yes, we accept {method} along with all major credit cards and PayPal.")
21+
],
22+
"account": [
23+
("I forgot my password for account {user}.", "No problem! Go to the login page and click 'Forgot Password' for {user}. We'll send a reset link to your email."),
24+
("How to enable 2FA?", "2FA can be enabled in your Profile Settings under 'Security'. We recommend using an app like Authy or Google Authenticator."),
25+
("Can I change my username to {new_name}?", "Usernames can be changed once every 6 months. To change yours to {new_name}, visit your Profile settings."),
26+
("My account {user} was hacked.", "Please immediately use the 'Secure My Account' link in your email or contact emergency-support@example.com.")
27+
]
28+
}
29+
30+
# Fillers for templates
31+
placeholders = {
32+
"code": ["E101", "E404", "E500", "E202", "X-99"],
33+
"reason": ["connection timeout", "database mismatch", "permission error", "config corruption"],
34+
"fix": ["flushing the DNS", "checking your firewall", "updating the library", "verifying your credentials"],
35+
"status": ["401 Unauthorized", "503 Service Unavailable", "429 Too Many Requests", "403 Forbidden"],
36+
"explanation": ["your token has expired", "the server is under heavy load", "you have exceeded your rate limit", "the resource is restricted"],
37+
"check": ["auth headers", "server status page", "request payload", "API quota"],
38+
"component": ["dashboard", "mobile app", "cli tool", "background worker"],
39+
"folder": ["/var/log", "/tmp/cache", "AppData/Local", "usr/local/bin"],
40+
"sdk": ["Python", "Node.js", "Ruby", "Go", "Java"],
41+
"manager": ["pip", "npm", "gem", "go get", "maven"],
42+
"command": ["pip install sdk", "npm install sdk", "bundle add sdk", "go get sdk/v2"],
43+
"plan": ["Pro", "Enterprise", "Starter", "Legacy"],
44+
"month": ["April", "last month", "current cycle"],
45+
"method": ["Apple Pay", "Google Pay", "Bitcoin", "Wire Transfer"],
46+
"user": ["user_123", "admin_test", "dev_account"],
47+
"new_name": ["SuperDev", "CloudNinja", "LogicMaster"]
48+
}
49+
50+
instruction_templates = [
51+
"{instr}",
52+
"I have a question: {instr}",
53+
"Help! {instr}",
54+
"Could you tell me {instr}?",
55+
"Please help me with this: {instr}",
56+
"Hey, {instr}",
57+
"{instr} Any ideas?"
58+
]
59+
2860
data = []
61+
62+
# Ensure we cover all templates at least once
63+
all_templates = []
64+
for cat in categories.values():
65+
all_templates.extend(cat)
66+
2967
for _ in range(num_samples):
30-
item = random.choice(scenarios)
31-
# Add some variation
32-
data.append(item)
68+
# Pick a random template from a random category
69+
cat_name = random.choice(list(categories.keys()))
70+
instr_tpl, resp_tpl = random.choice(categories[cat_name])
71+
72+
# Fill placeholders
73+
local_data = {k: random.choice(v) for k, v in placeholders.items()}
74+
75+
instr = instr_tpl.format(**local_data)
76+
resp = resp_tpl.format(**local_data)
77+
78+
# Apply instruction variety
79+
if random.random() > 0.3: # 70% chance to use a wrapper template
80+
final_instr = random.choice(instruction_templates).format(instr=instr.lower().strip('?'))
81+
if not final_instr.endswith('?'):
82+
final_instr += '?'
83+
else:
84+
final_instr = instr
85+
86+
data.append({
87+
"instruction": final_instr,
88+
"response": resp
89+
})
90+
91+
# Shuffle to mix categories
92+
random.shuffle(data)
3393

3494
with open(output_path, 'w') as f:
3595
for entry in data:
3696
f.write(json.dumps(entry) + '\n')
3797

3898
if __name__ == "__main__":
39-
import os
4099
os.makedirs("data/raw", exist_ok=True)
41-
generate_dummy_data("data/raw/raw_support_data.jsonl", 200)
42-
print("Generated dummy raw data.")
100+
count = 500
101+
generate_dummy_data("data/raw/raw_support_data.jsonl", count)
102+
print(f"Generated {count} diverse dummy samples in data/raw/raw_support_data.jsonl")

0 commit comments

Comments
 (0)