Spaces:
Running
on
Zero
Running
on
Zero
File size: 19,871 Bytes
6009f96 79b9403 6c98d85 79b9403 6028814 79b9403 78d35f7 f7906ff 6009f96 3ead256 6009f96 79b9403 6028814 79b9403 eda2a9c 79b9403 eda2a9c |
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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
import gradio as gr
import torch
import spaces
from transformers import AutoTokenizer, AutoModelForCausalLM
def get_csharp_validator_template():
return """You are a C# code generation expert specialized in creating validator classes.
Your task is to generate a new C# validator class strictly following the architectural template provided below.
Return ONLY the raw C# code for the validator class and its associated enum(s) and helper classes (like ServiceType if needed).
Do NOT include any extra text, explanations, comments outside of the generated code, or markdown formatting (```csharp / ```).
--- Validator Template Architecture ---
This is an example of the desired C# validator architecture. Replicate its structure, patterns, and conventions precisely for the new validator you are asked to generate.
// Example Enum defining validation states
public enum ServiceValidatorStates
{
IsFound = 6200,
IsFull,
HasName,
HasAbsolutePath,
IsCreateSpace,
IsDashboard,
HasToken,
HasValidModelAi,
HasMethods,
HasRequests,
IsLinkedToUsers,
HasId,
HasModelAi,
HasLinkedUsers,
IsServiceModel,
IsServiceIdsEmpty,
IsInUserClaims,
IsIn,
}
// Example Helper class for constant values used in validation attributes
public class ServiceType
{
public const string Dash = ""dashboard"";
public const string Space = ""createspace"";
public const string Service = ""service"";
}
// The main Validator class structure to follow
// It inherits from ValidatorContext<TModel, TState> and implements ITValidator
// It uses [RegisterConditionValidator] attributes to link states to methods
// It includes a private caching field (_service) and overrides GetModel
public class ServiceValidator : ValidatorContext<Service, ServiceValidatorStates>
{
private Service? _service;
public ServiceValidator(IConditionChecker checker) : base(checker)
{
}
protected override void InitializeConditions()
{
}
// --- Validation Function Signature and DataFilter Explanation ---
// ALL validation methods MUST follow this exact signature pattern:
// private async Task<ConditionResult> MethodName(DataFilter<TProp, TModel> f)
// Explanation of the DataFilter<TProp, TModel> parameter (conventionally named 'f'):
// This object carries all necessary context into a validation method.
// - TProp: The TYPE of the SPECIFIC piece of data or comparison value relevant to THIS validation method.
// For example:
// - For checking a 'string Name', TProp is 'string'.
// - For checking a 'bool IsActive', TProp is 'bool'.
// - For checking if a collection 'ICollection<Item>' is not empty, TProp might be 'object'.
// - For checking if a property equals a specific list of strings, TProp is 'List<string>'.
// - TModel: The TYPE of the ENTIRE model object being validated (e.g., Service, User, Product). This is consistent for all validation methods within one ValidatorContext class.
// Key properties of the 'f' (DataFilter) object:
// - f.Share (Type: TModel?): This is the MOST IMPORTANT property. It provides access to the FULL INSTANCE of the model object currently being validated. You use f.Share?.PropertyName to access the model's data.
// - f.Value (Type: TProp?): This holds an OPTIONAL comparison value passed INTO the validation method specifically for this rule. Its type matches TProp. Used when the validation isn't just a simple check on the property itself (like NotNullOrWhitespace) but involves comparing the property's value to something external.
// - f.Id (Type: string?): The ID associated with the validation request, often the ID of the model object.
// - f.Name (Type: string?): An optional name or key associated with the validation request context.
// Return Type: Validation methods MUST return Task<ConditionResult>.
// - ConditionResult.ToSuccessAsync(result): Use for successful validation, passing relevant data (often f.Share or the validated property value) in 'result'.
// - ConditionResult.ToFailureAsync(message) or ConditionResult.ToFailureAsync(result, message): Use for failed validation, providing an error message.
// Use of Framework Components:
// - await _checker.CheckAndResultAsync(...): Available via the base class. Use for performing CROSS-VALIDATION checks by triggering other states/validators.
// - _injector: If available via base class or DI, use to access application-specific services or context (like user claims or database context as seen in ServiceValidator examples).
// --- Example Validation Functions (from ServiceValidator) ---
// Replicate the structure, signatures, and parameter usage (f.Share, f.Value, f.Id, f.Name) as shown in these examples for the new validator.
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsFound, ""Service is not found"")]
private Task<ConditionResult> ValidateId(DataFilter<string, Service> f)
{
bool valid = !string.IsNullOrWhiteSpace(f.Share?.Id);
return valid ? ConditionResult.ToSuccessAsync(f.Share) : ConditionResult.ToFailureAsync(""Service is not found"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.HasName, ""Name is required"")]
private Task<ConditionResult> ValidateName(DataFilter<string, Service> f)
{
bool valid = !string.IsNullOrWhiteSpace(f.Share?.Name);
return valid ? ConditionResult.ToSuccessAsync(f.Share?.Name) : ConditionResult.ToFailureAsync(f.Share?.Name, ""Name is required"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.HasValidUrl, ""URL is invalid or missing"")]
private Task<ConditionResult> ValidateAbsolutePath(DataFilter<string, Service> f)
{
bool valid = Uri.IsWellFormedUriString(f.Share?.AbsolutePath, UriKind.Absolute);
return valid ? ConditionResult.ToSuccessAsync(f.Share?.AbsolutePath) : ConditionResult.ToFailureAsync(f.Share?.AbsolutePath, ""AbsolutePath is invalid"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.HasToken, ""Token cannot be empty if provided"")]
private Task<ConditionResult> ValidateToken(DataFilter<string?, Service> f)
{
var token = f.Share?.Token;
bool valid = token == null || !string.IsNullOrWhiteSpace(token);
return valid ? ConditionResult.ToSuccessAsync(token) : ConditionResult.ToFailureAsync(""Token cannot be empty if provided"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.HasModelAi, ""Model AI is missing"")]
private async Task<ConditionResult> ValidateModelAi(DataFilter<string, Service> f)
{
if (f.Share == null) return ConditionResult.ToFailure(null, ""Model AI is missing (Model is null)"");
var res = await _checker.CheckAndResultAsync(ModelValidatorStates.HasService, f.Share.ModelAiId);
if (res.Success == true)
{
return ConditionResult.ToSuccess(f.Share);
}
return ConditionResult.ToFailure(f.Share, res.Message ?? ""Related ModelAi check failed."");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.HasMethods, ""No methods defined for service"")]
private Task<ConditionResult> ValidateMethods(DataFilter<string, Service> f)
{
bool valid = f.Share?.ServiceMethods != null && f.Share.ServiceMethods.Any();
return valid ? ConditionResult.ToSuccessAsync(f.Share?.ServiceMethods) : ConditionResult.ToFailureAsync(f.Share?.ServiceMethods, ""No methods defined for service"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsInUserClaims, ""Service is not in user claims"")]
private Task<ConditionResult> ValidateServiceInUserClaims(DataFilter<string, Service> f)
{
bool valid = f.Share?.Id == f.Id;
return valid ? ConditionResult.ToSuccessAsync(f.Id) : ConditionResult.ToFailureAsync(f.Id, ""Service is not in user claims"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsServiceIdsEmpty, ""User has no services"")]
private Task<ConditionResult> ValidateServiceIdsEmpty(DataFilter<bool> f)
{
bool isEmpty = false;
return isEmpty ? ConditionResult.ToSuccessAsync(isEmpty) : ConditionResult.ToFailureAsync(isEmpty, ""User has services"");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsServiceModel, ""Not a valid service model"")]
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsDashboard, ""Not a valid service model"", Value = ServiceType.Dash)]
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsCreateSpace, ""Not a valid service model"", Value = ServiceType.Space)]
private Task<ConditionResult> ValidateIsServiceType(DataFilter<string, Service> f)
{
if (f.Share == null && f.Value == null && f.Name == null) return Task.FromResult(ConditionResult.ToError(""Both Name and Value are null""));
if (f.Share != null) return Task.FromResult(new ConditionResult(f.Share.AbsolutePath.Equals(f.Name ?? f.Value, StringComparison.OrdinalIgnoreCase), f.Share, $""No service found for {f.Name ?? f.Value}.""));
bool valid = false;
return valid ? ConditionResult.ToSuccessAsync(f.Share) : ConditionResult.ToErrorAsync($""No service found for {f.Name ?? f.Value}."");
}
[RegisterConditionValidator(typeof(ServiceValidatorStates), ServiceValidatorStates.IsIn, ""Not a valid service model"")]
private Task<ConditionResult> IsServiceType(DataFilter<List<string>, Service> f)
{
if (f.Share == null && f.Value == null) return Task.FromResult(ConditionResult.ToError(""Both Name and Value are null""));
if (f.Share != null) return Task.FromResult(new ConditionResult(f.Value?.Contains(f.Share.AbsolutePath) ?? false, f.Share, $""No service found for {f.Value}.""));
bool valid = false;
return valid ? ConditionResult.ToSuccessAsync(f.Share) : ConditionResult.ToErrorAsync($""No service found for {f.Value}."");
}
protected override async Task<Service?> GetModel(string? id)
{
if (_service != null && _service.Id == id)
return _service;
_service = await base.GetModel(id);
return _service;
}
}
"""
def generate_validator_prompt(model_name, model_structure, template_instructions):
csharp_template_string = get_csharp_validator_template()
prompt = f"""
Generate a C# Validator class for the model '{model_name}' with the following structure:
Model Name: {model_name}
Model Structure (C# Class Definition):
{model_structure}
Validator Template Pattern Requirements:
- The class must be named '{model_name}ValidatorContext'.
- It must inherit from 'ValidatorContext<{model_name}, {model_name}ValidatorStates>'.
- It must implement 'ITValidator'.
- It needs a constructor taking 'IConditionChecker checker'.
- Generate a public enum named '{model_name}ValidatorStates'. This enum should contain a state entry for EACH PUBLIC PROPERTY in the model structure (e.g., 'HasPropertyName').
- For EACH PUBLIC PROPERTY in the Model Structure, create a corresponding private method to perform validation.
- The method signature should be 'private Task<ConditionResult> ValidatePropertyName(DataFilter<PropertyType, {model_name}> f)'. Use the actual PropertyType from the Model Structure.
- Use 'async' only if 'await' is used inside the function body.
- If the function uses 'async', the return reference must be either ConditionResult.ToFailureAsync or ToSuccessAsync.
- If the function does NOT use 'async', the return reference must be ConditionResult.ToFailure or ToSuccess (use Task.FromResult(...) where necessary if not async).
- Each validation method must use the '[RegisterConditionValidator(typeof({model_name}ValidatorStates), {model_name}ValidatorStates.HasPropertyName, ""Error message"")]' attribute.
- Implement the 'GetModel' protected async method, ensuring it correctly handles caching if needed, similar to the provided template example.
- dont remove any usespaces in code
- If you use the res.Success condition and it is of type bool? the condition must be as follows (res.Success == true)
- Apply the following specific validation rules based on property types, as detailed in Template Instructions. Reference the pattern shown in the architecture below:
--- START C# VALIDATOR TEMPLATE ARCHITECTURE REFERENCE ---
{csharp_template_string}
--- END C# VALIDATOR TEMPLATE ARCHITECTURE REFERENCE ---
Your response MUST be ONLY the raw C# code for the '{model_name}ValidatorContext' class, including the enum, using statements (if necessary based on common patterns like AutoGenerator.Conditions), constructors, methods, and attributes. Do NOT include any surrounding text, explanations, or markdown. Ensure the output is just the C# code block.
Example Validation Logic Based on Common Types (Guideline for AI):
- string properties: Check for null or whitespace.
- string properties (potential URLs): Use Uri.TryCreate.
- bool properties: Often just check if the property exists or is default.
- Collection properties (like ICollection<Item>): Check if the collection is null or empty if required, or validate each item within the collection based on specific instructions.
Ensure all generated code adheres to the specified template pattern and the Template Instructions provided below.
Template Instructions:
{template_instructions}
"""
return prompt
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ุชุญู
ูู ุงููู
ูุฐุฌ ูุงูู
ุญูู
model_id = "wasmdashai/Seed-Coder-8B-Instruct-V1"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
@spaces.GPU
def process_validator_request(model_name, model_structure, template_instructions):
if not model_name or not model_structure:
return "Error: Model Name and Model Structure are required."
try:
generated_prompt = generate_validator_prompt(model_name, model_structure, template_instructions)
messages = [{"role": "user", "content": generated_prompt}]
input_ids = tokenizer.apply_chat_template(
messages,
tokenize=True,
return_tensors="pt",
add_generation_prompt=True,
).to(model.device)
with torch.no_grad():
outputs = model.generate(
input_ids,
max_new_tokens=4096,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id,
do_sample=True,
temperature=0.7,
top_p=0.95,
)
response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
response = response.strip()
if response.startswith("```csharp"):
response = response[len("```csharp"):].strip()
if response.endswith("```"):
response = response[:-len("```")].strip()
return response
except Exception as e:
print(f"An error occurred: {e}")
return f"An error occurred during generation: {e}"
# with gr.Blocks(title="C# Validator Generator") as demo:
# gr.Markdown("""
# # C# Validator Code Generator
# Use this tool to generate a C# validator class based on your model structure and template instructions,
# following a specific architectural pattern.
# """)
# with gr.Row():
# with gr.Column():
# model_name_input = gr.Textbox(label="Model Name (e.g., Role)", placeholder="Enter the model name (must be a valid C# identifier)...", interactive=True)
# model_structure_input = gr.Textbox(label="Model Structure (C# Class Definition)", placeholder="Paste your C# class definition here (including public properties)...", lines=15, interactive=True)
# template_instructions_input = gr.Textbox(label="Specific Template Instructions (Optional)", placeholder="Add any specific validation rules (e.g., 'Validate Id as GUID', 'Check if list is not null and not empty')...", lines=5, interactive=True)
# generate_button = gr.Button("Generate Validator Code")
# with gr.Column():
# code_output = gr.Code(label="Generated C# Validator Code",lines=25, interactive=False)
# generate_button.click(
# fn=process_validator_request,
# inputs=[model_name_input, model_structure_input, template_instructions_input],
# outputs=[code_output]
# )
# demo.launch()
import gradio as gr
@spaces.GPU
def process_multiple_validators(model_names_str, model_structure, template_instructions):
model_names = [name.strip() for name in model_names_str.split(",") if name.strip()]
files_output = {}
for model_name in model_names:
result = process_validator_request(model_name, model_structure, template_instructions)
files_output[model_name] = result
return files_output
with gr.Blocks(title="C# Validator Generator") as demo:
gr.Markdown("## ๐ง C# Validator Code Generator")
with gr.Tabs():
# Tab 1: Single Model
with gr.Tab("Single Validator"):
with gr.Row():
with gr.Column():
model_name_input = gr.Textbox(label="Model Name")
model_structure_input = gr.Textbox(label="Model Structure", lines=15)
template_input = gr.Textbox(label="Template Instructions (Optional)", lines=4)
generate_btn = gr.Button("Generate Validator")
with gr.Column():
single_code_output = gr.Code(label="Generated Code", language="csharp", lines=25)
generate_btn.click(
fn=process_validator_request,
inputs=[model_name_input, model_structure_input, template_input],
outputs=[single_code_output],
)
# Tab 2: Batch Mode
with gr.Tab("Batch Validators"):
with gr.Row():
with gr.Column():
model_names_input = gr.Textbox(
label="Model Names (comma-separated)",
placeholder="e.g., User, Role, Customer"
)
shared_model_structure_input = gr.Textbox(label="Shared Model Structure", lines=10)
shared_template_input = gr.Textbox(label="Shared Template Instructions (Optional)", lines=3)
batch_generate_btn = gr.Button("Generate All")
with gr.Column():
generated_editors = gr.Accordion("Generated Files", open=True)
editors_output = gr.Group()
def render_outputs(files_dict):
outputs = []
for name, code in files_dict.items():
editor = gr.Code(value=code, label=f"{name}.Validator.cs", language="csharp", lines=20)
outputs.append(editor)
return outputs
batch_generate_btn.click(
fn=process_multiple_validators,
inputs=[model_names_input, shared_model_structure_input, shared_template_input],
outputs=editors_output,
preprocess=False,
postprocess=True,
show_progress=True
)
generated_editors.children.append(editors_output)
demo.launch()
|