Spaces:
Running
Running
Commit
·
7361300
1
Parent(s):
9a4568b
fdaxcnjk
Browse files- model/generate.py +68 -216
model/generate.py
CHANGED
|
@@ -5,7 +5,6 @@ import logging
|
|
| 5 |
import psutil
|
| 6 |
import re
|
| 7 |
import gc
|
| 8 |
-
from typing import List, Dict, Union, Tuple
|
| 9 |
|
| 10 |
# Initialize logger
|
| 11 |
logger = logging.getLogger(__name__)
|
|
@@ -22,76 +21,7 @@ MEMORY_OPTIMIZED_MODELS = [
|
|
| 22 |
# Singleton state
|
| 23 |
_generator_instance = None
|
| 24 |
|
| 25 |
-
|
| 26 |
-
KEYWORD_TEST_MAPPING = {
|
| 27 |
-
'login': [
|
| 28 |
-
{
|
| 29 |
-
"title": "Valid Credentials Login",
|
| 30 |
-
"steps": ["Navigate to login page", "Enter valid username", "Enter valid password", "Click login button"],
|
| 31 |
-
"expected": "User should be redirected to dashboard"
|
| 32 |
-
},
|
| 33 |
-
{
|
| 34 |
-
"title": "Invalid Password Login",
|
| 35 |
-
"steps": ["Navigate to login page", "Enter valid username", "Enter invalid password", "Click login button"],
|
| 36 |
-
"expected": "System should display 'Invalid credentials' error"
|
| 37 |
-
},
|
| 38 |
-
{
|
| 39 |
-
"title": "Empty Fields Login",
|
| 40 |
-
"steps": ["Navigate to login page", "Leave username empty", "Leave password empty", "Click login button"],
|
| 41 |
-
"expected": "System should display validation errors for both fields"
|
| 42 |
-
}
|
| 43 |
-
],
|
| 44 |
-
'authentication': [
|
| 45 |
-
{
|
| 46 |
-
"title": "Session Timeout Test",
|
| 47 |
-
"steps": ["Login successfully", "Wait for session timeout period", "Attempt to access protected resource"],
|
| 48 |
-
"expected": "System should redirect to login page"
|
| 49 |
-
},
|
| 50 |
-
{
|
| 51 |
-
"title": "Concurrent Sessions Test",
|
| 52 |
-
"steps": ["Login from device A", "Login from device B with same credentials", "Attempt actions on both devices"],
|
| 53 |
-
"expected": "System should handle concurrent sessions appropriately"
|
| 54 |
-
}
|
| 55 |
-
],
|
| 56 |
-
'database': [
|
| 57 |
-
{
|
| 58 |
-
"title": "Data Integrity Test",
|
| 59 |
-
"steps": ["Insert test data", "Retrieve same data", "Compare results"],
|
| 60 |
-
"expected": "Stored data should match retrieved data exactly"
|
| 61 |
-
},
|
| 62 |
-
{
|
| 63 |
-
"title": "Large Data Volume Test",
|
| 64 |
-
"steps": ["Insert 10,000 records", "Perform search operations", "Measure response times"],
|
| 65 |
-
"expected": "System should handle large data volumes within acceptable performance thresholds"
|
| 66 |
-
}
|
| 67 |
-
],
|
| 68 |
-
'api': [
|
| 69 |
-
{
|
| 70 |
-
"title": "API Authentication Test",
|
| 71 |
-
"steps": ["Make API request without authentication", "Make API request with valid credentials", "Make API request with invalid credentials"],
|
| 72 |
-
"expected": "Only authenticated requests should succeed"
|
| 73 |
-
},
|
| 74 |
-
{
|
| 75 |
-
"title": "API Input Validation Test",
|
| 76 |
-
"steps": ["Send malformed input to API", "Send extreme values to API", "Send valid input to API"],
|
| 77 |
-
"expected": "API should properly validate all inputs"
|
| 78 |
-
}
|
| 79 |
-
],
|
| 80 |
-
'default': [
|
| 81 |
-
{
|
| 82 |
-
"title": "Basic Functionality Smoke Test",
|
| 83 |
-
"steps": ["Access the system", "Perform core operation", "Verify results"],
|
| 84 |
-
"expected": "System should perform basic functions without errors"
|
| 85 |
-
},
|
| 86 |
-
{
|
| 87 |
-
"title": "Error Handling Test",
|
| 88 |
-
"steps": ["Force error condition", "Verify system response"],
|
| 89 |
-
"expected": "System should handle errors gracefully with appropriate messages"
|
| 90 |
-
}
|
| 91 |
-
]
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
def get_optimal_model_for_memory() -> Union[str, None]:
|
| 95 |
"""Select the best model based on available memory."""
|
| 96 |
available_memory = psutil.virtual_memory().available / (1024 * 1024) # MB
|
| 97 |
logger.info(f"Available memory: {available_memory:.1f}MB")
|
|
@@ -103,7 +33,7 @@ def get_optimal_model_for_memory() -> Union[str, None]:
|
|
| 103 |
else:
|
| 104 |
return "distilgpt2"
|
| 105 |
|
| 106 |
-
def load_model_with_memory_optimization(model_name
|
| 107 |
"""Load model with low memory settings."""
|
| 108 |
try:
|
| 109 |
logger.info(f"Loading {model_name} with memory optimizations...")
|
|
@@ -130,172 +60,116 @@ def load_model_with_memory_optimization(model_name: str) -> Tuple[Union[AutoToke
|
|
| 130 |
logger.error(f"❌ Failed to load model {model_name}: {e}")
|
| 131 |
return None, None
|
| 132 |
|
| 133 |
-
def extract_keywords(text
|
| 134 |
-
"""Extract relevant keywords from text for test case generation."""
|
| 135 |
common_keywords = [
|
| 136 |
'login', 'authentication', 'user', 'password', 'database', 'data',
|
| 137 |
'interface', 'api', 'function', 'feature', 'requirement', 'system',
|
| 138 |
-
'input', 'output', 'validation', 'error', 'security', 'performance'
|
| 139 |
-
'storage', 'retrieval', 'search', 'filter', 'export', 'import'
|
| 140 |
]
|
| 141 |
words = re.findall(r'\b\w+\b', text.lower())
|
| 142 |
return [word for word in words if word in common_keywords]
|
| 143 |
|
| 144 |
-
def generate_template_based_test_cases(srs_text
|
| 145 |
-
"""Generate test cases based on templates matching keywords in requirements."""
|
| 146 |
keywords = extract_keywords(srs_text)
|
| 147 |
test_cases = []
|
| 148 |
-
case_counter = 1
|
| 149 |
-
|
| 150 |
-
# Generate test cases for each matched keyword
|
| 151 |
-
for keyword, test_templates in KEYWORD_TEST_MAPPING.items():
|
| 152 |
-
if keyword in keywords:
|
| 153 |
-
for template in test_templates:
|
| 154 |
-
test_cases.append({
|
| 155 |
-
"id": f"TC_{case_counter:03d}",
|
| 156 |
-
"title": template["title"],
|
| 157 |
-
"description": f"Test for {keyword} functionality: {template['title']}",
|
| 158 |
-
"steps": template["steps"],
|
| 159 |
-
"expected": template["expected"]
|
| 160 |
-
})
|
| 161 |
-
case_counter += 1
|
| 162 |
-
|
| 163 |
-
# Add default test cases if no specific ones were generated
|
| 164 |
-
if not test_cases:
|
| 165 |
-
for template in KEYWORD_TEST_MAPPING['default']:
|
| 166 |
-
test_cases.append({
|
| 167 |
-
"id": f"TC_{case_counter:03d}",
|
| 168 |
-
"title": template["title"],
|
| 169 |
-
"description": template["title"],
|
| 170 |
-
"steps": template["steps"],
|
| 171 |
-
"expected": template["expected"]
|
| 172 |
-
})
|
| 173 |
-
case_counter += 1
|
| 174 |
|
| 175 |
-
|
| 176 |
-
if any(kw in keywords for kw in ['input', 'validation']):
|
| 177 |
test_cases.extend([
|
| 178 |
{
|
| 179 |
-
"id":
|
| 180 |
-
"title": "
|
| 181 |
-
"description": "Test
|
| 182 |
-
"steps": ["Enter
|
| 183 |
-
"expected": "
|
| 184 |
},
|
| 185 |
{
|
| 186 |
-
"id":
|
| 187 |
-
"title": "
|
| 188 |
-
"description": "Test with invalid
|
| 189 |
-
"steps": ["Enter
|
| 190 |
-
"expected": "
|
| 191 |
}
|
| 192 |
])
|
| 193 |
-
case_counter += 2
|
| 194 |
|
| 195 |
-
|
| 196 |
-
if any(kw in keywords for kw in ['security', 'authentication']):
|
| 197 |
test_cases.append({
|
| 198 |
-
"id":
|
| 199 |
-
"title": "
|
| 200 |
-
"description": "Test
|
| 201 |
-
"steps": ["Enter
|
| 202 |
-
"expected": "
|
| 203 |
})
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
return test_cases
|
| 207 |
|
| 208 |
-
def parse_generated_test_cases(generated_text
|
| 209 |
-
|
| 210 |
-
lines = [line.strip() for line in generated_text.split('\n') if line.strip()]
|
| 211 |
test_cases = []
|
| 212 |
current_case = {}
|
| 213 |
case_counter = 1
|
| 214 |
-
step_pattern = re.compile(r'^\d+\.|step\s?\d+:|steps?:', re.IGNORECASE)
|
| 215 |
-
expected_pattern = re.compile(r'expected:|result:', re.IGNORECASE)
|
| 216 |
|
| 217 |
for line in lines:
|
| 218 |
-
|
| 219 |
-
if
|
| 220 |
if current_case:
|
| 221 |
test_cases.append(current_case)
|
| 222 |
-
case_counter += 1
|
| 223 |
current_case = {
|
| 224 |
"id": f"TC_{case_counter:03d}",
|
| 225 |
"title": line,
|
| 226 |
"description": line,
|
| 227 |
-
"steps": [],
|
| 228 |
-
"expected": "
|
| 229 |
}
|
| 230 |
-
|
| 231 |
-
elif step_pattern.match(line):
|
| 232 |
-
step = re.sub(step_pattern, '', line).strip()
|
| 233 |
-
if step:
|
| 234 |
-
if 'steps' not in current_case:
|
| 235 |
-
current_case['steps'] = []
|
| 236 |
-
current_case['steps'].append(step)
|
| 237 |
-
# Detect expected results
|
| 238 |
-
elif expected_pattern.match(line):
|
| 239 |
-
expected = re.sub(expected_pattern, '', line).strip()
|
| 240 |
-
if expected:
|
| 241 |
-
current_case['expected'] = expected
|
| 242 |
|
| 243 |
if current_case:
|
| 244 |
-
# Ensure at least one step exists
|
| 245 |
-
if not current_case.get('steps'):
|
| 246 |
-
current_case['steps'] = ["Execute the test according to requirements"]
|
| 247 |
test_cases.append(current_case)
|
| 248 |
|
| 249 |
-
# Fallback if no test cases were parsed
|
| 250 |
if not test_cases:
|
| 251 |
return [{
|
| 252 |
"id": "TC_001",
|
| 253 |
-
"title": "
|
| 254 |
-
"description": "
|
| 255 |
-
"steps": [
|
| 256 |
-
|
| 257 |
-
"Execute core functionality tests",
|
| 258 |
-
"Verify all expected outcomes"
|
| 259 |
-
],
|
| 260 |
-
"expected": "System meets all specified requirements"
|
| 261 |
}]
|
| 262 |
|
| 263 |
return test_cases
|
| 264 |
|
| 265 |
-
def generate_with_ai_model(srs_text
|
| 266 |
-
|
| 267 |
-
max_input_length = 512 # Increased from 200 to capture more context
|
| 268 |
if len(srs_text) > max_input_length:
|
| 269 |
srs_text = srs_text[:max_input_length]
|
| 270 |
|
| 271 |
-
prompt = f"""Generate
|
| 272 |
-
1. Clear title describing the test scenario
|
| 273 |
-
2. Detailed steps to execute the test
|
| 274 |
-
3. Expected results
|
| 275 |
-
|
| 276 |
-
Requirements:
|
| 277 |
{srs_text}
|
| 278 |
|
| 279 |
Test Cases:
|
| 280 |
-
1.
|
| 281 |
-
Steps: 1. Access the system
|
| 282 |
-
2. Perform core operation
|
| 283 |
-
3. Verify results
|
| 284 |
-
Expected: System performs as specified in requirements
|
| 285 |
-
2."""
|
| 286 |
|
| 287 |
try:
|
| 288 |
inputs = tokenizer.encode(
|
| 289 |
prompt,
|
| 290 |
return_tensors="pt",
|
| 291 |
-
max_length=
|
| 292 |
truncation=True
|
| 293 |
)
|
| 294 |
|
| 295 |
with torch.no_grad():
|
| 296 |
outputs = model.generate(
|
| 297 |
inputs,
|
| 298 |
-
max_new_tokens=
|
| 299 |
num_return_sequences=1,
|
| 300 |
temperature=0.7,
|
| 301 |
do_sample=True,
|
|
@@ -312,8 +186,7 @@ Test Cases:
|
|
| 312 |
logger.error(f"❌ AI generation failed: {e}")
|
| 313 |
raise
|
| 314 |
|
| 315 |
-
def generate_with_fallback(srs_text
|
| 316 |
-
"""Generate test cases with AI or fallback to templates with enhanced logic."""
|
| 317 |
model_name = get_optimal_model_for_memory()
|
| 318 |
|
| 319 |
if model_name:
|
|
@@ -330,12 +203,11 @@ def generate_with_fallback(srs_text: str) -> Tuple[List[Dict[str, Union[str, Lis
|
|
| 330 |
test_cases = generate_template_based_test_cases(srs_text)
|
| 331 |
return test_cases, "Template-Based Generator", "rule-based", "Low memory - fallback to rule-based generation"
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
| 335 |
return generate_with_fallback(srs_text)[0]
|
| 336 |
|
| 337 |
def get_generator():
|
| 338 |
-
"""Get singleton generator instance with memory monitoring."""
|
| 339 |
global _generator_instance
|
| 340 |
if _generator_instance is None:
|
| 341 |
class Generator:
|
|
@@ -346,7 +218,7 @@ def get_generator():
|
|
| 346 |
if self.model_name:
|
| 347 |
self.tokenizer, self.model = load_model_with_memory_optimization(self.model_name)
|
| 348 |
|
| 349 |
-
def get_model_info(self)
|
| 350 |
mem = psutil.Process().memory_info().rss / 1024 / 1024
|
| 351 |
return {
|
| 352 |
"model_name": self.model_name if self.model_name else "Template-Based Generator",
|
|
@@ -360,15 +232,14 @@ def get_generator():
|
|
| 360 |
return _generator_instance
|
| 361 |
|
| 362 |
def monitor_memory():
|
| 363 |
-
"""Monitor and log memory usage with automatic cleanup."""
|
| 364 |
mem = psutil.Process().memory_info().rss / 1024 / 1024
|
| 365 |
logger.info(f"Memory usage: {mem:.1f}MB")
|
| 366 |
if mem > 450:
|
| 367 |
gc.collect()
|
| 368 |
logger.info("Memory cleanup triggered")
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
test_cases, model_name, algorithm_used, reason = generate_with_fallback(input_text)
|
| 373 |
return {
|
| 374 |
"model": model_name,
|
|
@@ -377,34 +248,15 @@ def generate_test_cases_and_info(input_text: str) -> Dict[str, Union[str, List[D
|
|
| 377 |
"test_cases": test_cases
|
| 378 |
}
|
| 379 |
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
sample_requirements = """
|
| 393 |
-
The system shall provide user authentication via username and password.
|
| 394 |
-
All user data must be stored securely in the database.
|
| 395 |
-
The API should validate all inputs before processing.
|
| 396 |
-
"""
|
| 397 |
-
|
| 398 |
-
print("Generating test cases...")
|
| 399 |
-
result = generate_test_cases_and_info(sample_requirements)
|
| 400 |
-
print(f"\nModel used: {result['model']}")
|
| 401 |
-
print(f"Algorithm: {result['algorithm']}")
|
| 402 |
-
print(f"Reason: {result['reason']}\n")
|
| 403 |
-
|
| 404 |
-
for tc in result["test_cases"]:
|
| 405 |
-
print(f"Test Case {tc['id']}: {tc['title']}")
|
| 406 |
-
print(f"Description: {tc['description']}")
|
| 407 |
-
print("Steps:")
|
| 408 |
-
for i, step in enumerate(tc['steps'], 1):
|
| 409 |
-
print(f" {i}. {step}")
|
| 410 |
-
print(f"Expected: {tc['expected']}\n")
|
|
|
|
| 5 |
import psutil
|
| 6 |
import re
|
| 7 |
import gc
|
|
|
|
| 8 |
|
| 9 |
# Initialize logger
|
| 10 |
logger = logging.getLogger(__name__)
|
|
|
|
| 21 |
# Singleton state
|
| 22 |
_generator_instance = None
|
| 23 |
|
| 24 |
+
def get_optimal_model_for_memory():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
"""Select the best model based on available memory."""
|
| 26 |
available_memory = psutil.virtual_memory().available / (1024 * 1024) # MB
|
| 27 |
logger.info(f"Available memory: {available_memory:.1f}MB")
|
|
|
|
| 33 |
else:
|
| 34 |
return "distilgpt2"
|
| 35 |
|
| 36 |
+
def load_model_with_memory_optimization(model_name):
|
| 37 |
"""Load model with low memory settings."""
|
| 38 |
try:
|
| 39 |
logger.info(f"Loading {model_name} with memory optimizations...")
|
|
|
|
| 60 |
logger.error(f"❌ Failed to load model {model_name}: {e}")
|
| 61 |
return None, None
|
| 62 |
|
| 63 |
+
def extract_keywords(text):
|
|
|
|
| 64 |
common_keywords = [
|
| 65 |
'login', 'authentication', 'user', 'password', 'database', 'data',
|
| 66 |
'interface', 'api', 'function', 'feature', 'requirement', 'system',
|
| 67 |
+
'input', 'output', 'validation', 'error', 'security', 'performance'
|
|
|
|
| 68 |
]
|
| 69 |
words = re.findall(r'\b\w+\b', text.lower())
|
| 70 |
return [word for word in words if word in common_keywords]
|
| 71 |
|
| 72 |
+
def generate_template_based_test_cases(srs_text):
|
|
|
|
| 73 |
keywords = extract_keywords(srs_text)
|
| 74 |
test_cases = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
if any(word in keywords for word in ['login', 'authentication', 'user', 'password']):
|
|
|
|
| 77 |
test_cases.extend([
|
| 78 |
{
|
| 79 |
+
"id": "TC_001",
|
| 80 |
+
"title": "Valid Login Test",
|
| 81 |
+
"description": "Test login with valid credentials",
|
| 82 |
+
"steps": ["Enter valid username", "Enter valid password", "Click login"],
|
| 83 |
+
"expected": "User should be logged in successfully"
|
| 84 |
},
|
| 85 |
{
|
| 86 |
+
"id": "TC_002",
|
| 87 |
+
"title": "Invalid Login Test",
|
| 88 |
+
"description": "Test login with invalid credentials",
|
| 89 |
+
"steps": ["Enter invalid username", "Enter invalid password", "Click login"],
|
| 90 |
+
"expected": "Error message should be displayed"
|
| 91 |
}
|
| 92 |
])
|
|
|
|
| 93 |
|
| 94 |
+
if any(word in keywords for word in ['database', 'data', 'store', 'save']):
|
|
|
|
| 95 |
test_cases.append({
|
| 96 |
+
"id": "TC_003",
|
| 97 |
+
"title": "Data Storage Test",
|
| 98 |
+
"description": "Test data storage functionality",
|
| 99 |
+
"steps": ["Enter data", "Save data", "Verify storage"],
|
| 100 |
+
"expected": "Data should be stored correctly"
|
| 101 |
})
|
| 102 |
+
|
| 103 |
+
if not test_cases:
|
| 104 |
+
test_cases = [
|
| 105 |
+
{
|
| 106 |
+
"id": "TC_001",
|
| 107 |
+
"title": "Basic Functionality Test",
|
| 108 |
+
"description": "Test basic system functionality",
|
| 109 |
+
"steps": ["Access the system", "Perform basic operations", "Verify results"],
|
| 110 |
+
"expected": "System should work as expected"
|
| 111 |
+
}
|
| 112 |
+
]
|
| 113 |
|
| 114 |
return test_cases
|
| 115 |
|
| 116 |
+
def parse_generated_test_cases(generated_text):
|
| 117 |
+
lines = generated_text.split('\n')
|
|
|
|
| 118 |
test_cases = []
|
| 119 |
current_case = {}
|
| 120 |
case_counter = 1
|
|
|
|
|
|
|
| 121 |
|
| 122 |
for line in lines:
|
| 123 |
+
line = line.strip()
|
| 124 |
+
if line.startswith(('1.', '2.', '3.', 'TC', 'Test')):
|
| 125 |
if current_case:
|
| 126 |
test_cases.append(current_case)
|
|
|
|
| 127 |
current_case = {
|
| 128 |
"id": f"TC_{case_counter:03d}",
|
| 129 |
"title": line,
|
| 130 |
"description": line,
|
| 131 |
+
"steps": ["Execute the test"],
|
| 132 |
+
"expected": "Test should pass"
|
| 133 |
}
|
| 134 |
+
case_counter += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
if current_case:
|
|
|
|
|
|
|
|
|
|
| 137 |
test_cases.append(current_case)
|
| 138 |
|
|
|
|
| 139 |
if not test_cases:
|
| 140 |
return [{
|
| 141 |
"id": "TC_001",
|
| 142 |
+
"title": "Generated Test Case",
|
| 143 |
+
"description": "Auto-generated test case based on requirements",
|
| 144 |
+
"steps": ["Review requirements", "Execute test", "Verify results"],
|
| 145 |
+
"expected": "Requirements should be met"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
}]
|
| 147 |
|
| 148 |
return test_cases
|
| 149 |
|
| 150 |
+
def generate_with_ai_model(srs_text, tokenizer, model):
|
| 151 |
+
max_input_length = 200
|
|
|
|
| 152 |
if len(srs_text) > max_input_length:
|
| 153 |
srs_text = srs_text[:max_input_length]
|
| 154 |
|
| 155 |
+
prompt = f"""Generate test cases for this software requirement:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
{srs_text}
|
| 157 |
|
| 158 |
Test Cases:
|
| 159 |
+
1."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
try:
|
| 162 |
inputs = tokenizer.encode(
|
| 163 |
prompt,
|
| 164 |
return_tensors="pt",
|
| 165 |
+
max_length=150,
|
| 166 |
truncation=True
|
| 167 |
)
|
| 168 |
|
| 169 |
with torch.no_grad():
|
| 170 |
outputs = model.generate(
|
| 171 |
inputs,
|
| 172 |
+
max_new_tokens=100,
|
| 173 |
num_return_sequences=1,
|
| 174 |
temperature=0.7,
|
| 175 |
do_sample=True,
|
|
|
|
| 186 |
logger.error(f"❌ AI generation failed: {e}")
|
| 187 |
raise
|
| 188 |
|
| 189 |
+
def generate_with_fallback(srs_text):
|
|
|
|
| 190 |
model_name = get_optimal_model_for_memory()
|
| 191 |
|
| 192 |
if model_name:
|
|
|
|
| 203 |
test_cases = generate_template_based_test_cases(srs_text)
|
| 204 |
return test_cases, "Template-Based Generator", "rule-based", "Low memory - fallback to rule-based generation"
|
| 205 |
|
| 206 |
+
# ✅ Function exposed to app.py
|
| 207 |
+
def generate_test_cases(srs_text):
|
| 208 |
return generate_with_fallback(srs_text)[0]
|
| 209 |
|
| 210 |
def get_generator():
|
|
|
|
| 211 |
global _generator_instance
|
| 212 |
if _generator_instance is None:
|
| 213 |
class Generator:
|
|
|
|
| 218 |
if self.model_name:
|
| 219 |
self.tokenizer, self.model = load_model_with_memory_optimization(self.model_name)
|
| 220 |
|
| 221 |
+
def get_model_info(self):
|
| 222 |
mem = psutil.Process().memory_info().rss / 1024 / 1024
|
| 223 |
return {
|
| 224 |
"model_name": self.model_name if self.model_name else "Template-Based Generator",
|
|
|
|
| 232 |
return _generator_instance
|
| 233 |
|
| 234 |
def monitor_memory():
|
|
|
|
| 235 |
mem = psutil.Process().memory_info().rss / 1024 / 1024
|
| 236 |
logger.info(f"Memory usage: {mem:.1f}MB")
|
| 237 |
if mem > 450:
|
| 238 |
gc.collect()
|
| 239 |
logger.info("Memory cleanup triggered")
|
| 240 |
|
| 241 |
+
# ✅ NEW FUNCTION for enhanced output: test cases + model info + reason
|
| 242 |
+
def generate_test_cases_and_info(input_text):
|
| 243 |
test_cases, model_name, algorithm_used, reason = generate_with_fallback(input_text)
|
| 244 |
return {
|
| 245 |
"model": model_name,
|
|
|
|
| 248 |
"test_cases": test_cases
|
| 249 |
}
|
| 250 |
|
| 251 |
+
# ✅ Explain why each algorithm is selected
|
| 252 |
+
def get_algorithm_reason(model_name):
|
| 253 |
+
if model_name == "microsoft/DialoGPT-small":
|
| 254 |
+
return "Selected due to low memory availability; DialoGPT-small provides conversational understanding in limited memory environments."
|
| 255 |
+
elif model_name == "distilgpt2":
|
| 256 |
+
return "Selected for its balance between performance and low memory usage. Ideal for small environments needing causal language modeling."
|
| 257 |
+
elif model_name == "gpt2":
|
| 258 |
+
return "Chosen for general-purpose text generation with moderate memory headroom."
|
| 259 |
+
elif model_name is None:
|
| 260 |
+
return "No model used due to insufficient memory. Rule-based template generation chosen instead."
|
| 261 |
+
else:
|
| 262 |
+
return "Model selected based on best tradeoff between memory usage and language generation capability."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|