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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import openai
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
import sys
|
| 6 |
+
import io
|
| 7 |
+
from contextlib import redirect_stdout
|
| 8 |
+
|
| 9 |
+
# Use Together AI API (OpenAI-compatible) - Sign up at https://www.together.ai/ for free API key
|
| 10 |
+
# Models available: CodeLlama, StarCoder, etc. (lightweight, no local torch needed)
|
| 11 |
+
TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY") # Set in Hugging Face Spaces secrets
|
| 12 |
+
client = openai.OpenAI(
|
| 13 |
+
api_key=TOGETHER_API_KEY,
|
| 14 |
+
base_url="https://openrouter.ai/api/v1"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Model: A code-specialized model from Together AI (e.g., CodeLlama 7B Instruct - efficient and accurate for Python)
|
| 18 |
+
MODEL_NAME = "openai/gpt-oss-20b:free" # Alternative: "Salesforce/codegen-350M-mono" for lighter
|
| 19 |
+
|
| 20 |
+
def generate_code_with_together(instruction, file_paths):
|
| 21 |
+
"""
|
| 22 |
+
Generate Python code using Together AI API (OpenAI-compatible).
|
| 23 |
+
"""
|
| 24 |
+
prompt = f"""
|
| 25 |
+
You are a Python expert. The user has provided the instruction: "{instruction}"
|
| 26 |
+
And input files: {file_paths} (these paths are available in the current working directory).
|
| 27 |
+
|
| 28 |
+
Write a complete, self-contained Python script that:
|
| 29 |
+
1. Reads the input file(s) from the given paths.
|
| 30 |
+
2. Performs the requested operation (e.g., for "remove background from image", use rembg or similar).
|
| 31 |
+
3. Saves the output file(s) to a temporary directory (use tempfile.mkdtemp() for a temp dir).
|
| 32 |
+
4. At the very end of the script, print exactly one line: OUTPUT_FILE_PATH: /full/path/to/output/file.ext
|
| 33 |
+
(Replace with the actual full path to the generated output file. If multiple outputs, choose the main one.)
|
| 34 |
+
|
| 35 |
+
Use only safe, standard libraries or pre-installed ones like PIL (from pillow), rembg for image tasks, numpy, etc.
|
| 36 |
+
Do not use any network calls, file deletions outside temp, or unsafe operations.
|
| 37 |
+
Handle errors gracefully and assume the environment has the necessary libs (e.g., import rembg).
|
| 38 |
+
|
| 39 |
+
Example for background removal:
|
| 40 |
+
from rembg import remove
|
| 41 |
+
import os
|
| 42 |
+
import tempfile
|
| 43 |
+
input_path = '{file_paths[0]}'
|
| 44 |
+
temp_dir = tempfile.mkdtemp()
|
| 45 |
+
with open(input_path, 'rb') as i:
|
| 46 |
+
input_data = i.read()
|
| 47 |
+
output_data = remove(input_data)
|
| 48 |
+
output_path = os.path.join(temp_dir, 'output.png')
|
| 49 |
+
with open(output_path, 'wb') as o:
|
| 50 |
+
o.write(output_data)
|
| 51 |
+
print(f"OUTPUT_FILE_PATH: {{output_path}}")
|
| 52 |
+
|
| 53 |
+
Generate ONLY the Python code. Do not add explanations.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
response = client.chat.completions.create(
|
| 58 |
+
model=MODEL_NAME,
|
| 59 |
+
messages=[
|
| 60 |
+
{"role": "system", "content": "You are a helpful Python code generator. Respond only with clean, executable Python code."},
|
| 61 |
+
{"role": "user", "content": prompt}
|
| 62 |
+
],
|
| 63 |
+
max_tokens=1000,
|
| 64 |
+
temperature=0.2,
|
| 65 |
+
stop=["```"] # Stop at code block end if any
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
generated_code = response.choices[0].message.content.strip()
|
| 69 |
+
|
| 70 |
+
# Clean up: Remove any markdown code blocks (e.g., ```python ... ```)
|
| 71 |
+
if generated_code.startswith("```python"):
|
| 72 |
+
generated_code = generated_code[10:].strip()
|
| 73 |
+
if generated_code.endswith("```"):
|
| 74 |
+
generated_code = generated_code[:-3].strip()
|
| 75 |
+
|
| 76 |
+
return generated_code
|
| 77 |
+
|
| 78 |
+
except Exception as api_error:
|
| 79 |
+
raise api_error
|
| 80 |
+
|
| 81 |
+
def process_request(instruction, files):
|
| 82 |
+
if not files:
|
| 83 |
+
return "لطفاً حداقل یک فایل آپلود کنید.", None
|
| 84 |
+
|
| 85 |
+
file_paths = [file.name for file in files]
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
# Generate code using Together AI
|
| 89 |
+
generated_code = generate_code_with_together(instruction, file_paths)
|
| 90 |
+
|
| 91 |
+
if not generated_code or len(generated_code) < 50:
|
| 92 |
+
return f"کد مناسبی تولید نشد. پرامپت: {instruction}\nکد تولید شده:\n{generated_code}", None
|
| 93 |
+
|
| 94 |
+
# Create a temporary file for the generated code
|
| 95 |
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_code_file:
|
| 96 |
+
temp_code_file.write(generated_code)
|
| 97 |
+
code_file_path = temp_code_file.name
|
| 98 |
+
|
| 99 |
+
# Capture the output of executing the generated code
|
| 100 |
+
f = io.StringIO()
|
| 101 |
+
output_path = None
|
| 102 |
+
|
| 103 |
+
with redirect_stdout(f):
|
| 104 |
+
try:
|
| 105 |
+
# Execute the generated code in a restricted environment (for safety)
|
| 106 |
+
safe_globals = {
|
| 107 |
+
'__builtins__': {
|
| 108 |
+
'print': print,
|
| 109 |
+
'open': open,
|
| 110 |
+
'range': range,
|
| 111 |
+
'len': len,
|
| 112 |
+
'str': str,
|
| 113 |
+
'int': int,
|
| 114 |
+
'float': float,
|
| 115 |
+
'list': list,
|
| 116 |
+
'dict': dict,
|
| 117 |
+
'tuple': tuple,
|
| 118 |
+
'set': set,
|
| 119 |
+
'bool': bool,
|
| 120 |
+
'type': type,
|
| 121 |
+
'isinstance': isinstance,
|
| 122 |
+
'hasattr': hasattr,
|
| 123 |
+
'getattr': getattr,
|
| 124 |
+
'setattr': setattr,
|
| 125 |
+
'delattr': delattr,
|
| 126 |
+
'abs': abs,
|
| 127 |
+
'all': all,
|
| 128 |
+
'any': any,
|
| 129 |
+
'bin': bin,
|
| 130 |
+
'chr': chr,
|
| 131 |
+
'complex': complex,
|
| 132 |
+
'divmod': divmod,
|
| 133 |
+
'enumerate': enumerate,
|
| 134 |
+
'format': format,
|
| 135 |
+
'hash': hash,
|
| 136 |
+
'hex': hex,
|
| 137 |
+
'id': id,
|
| 138 |
+
'iter': iter,
|
| 139 |
+
'max': max,
|
| 140 |
+
'min': min,
|
| 141 |
+
'next': next,
|
| 142 |
+
'oct': oct,
|
| 143 |
+
'ord': ord,
|
| 144 |
+
'pow': pow,
|
| 145 |
+
'repr': repr,
|
| 146 |
+
'round': round,
|
| 147 |
+
'slice': slice,
|
| 148 |
+
'sorted': sorted,
|
| 149 |
+
'sum': sum,
|
| 150 |
+
'zip': zip,
|
| 151 |
+
'__import__': __import__,
|
| 152 |
+
},
|
| 153 |
+
'os': os,
|
| 154 |
+
'tempfile': tempfile,
|
| 155 |
+
'sys': sys,
|
| 156 |
+
'PIL': __import__('PIL', fromlist=['Image']),
|
| 157 |
+
'rembg': __import__('rembg', fromlist=['remove']),
|
| 158 |
+
# Add more safe imports as needed (e.g., 'numpy': __import__('numpy'))
|
| 159 |
+
}
|
| 160 |
+
safe_locals = {}
|
| 161 |
+
|
| 162 |
+
exec(generated_code, safe_globals, safe_locals)
|
| 163 |
+
|
| 164 |
+
# Capture the printed OUTPUT_FILE_PATH
|
| 165 |
+
stdout_output = f.getvalue()
|
| 166 |
+
if "OUTPUT_FILE_PATH:" in stdout_output:
|
| 167 |
+
output_path = stdout_output.split("OUTPUT_FILE_PATH:")[-1].strip()
|
| 168 |
+
output_path = output_path.split('\n')[0].strip()
|
| 169 |
+
|
| 170 |
+
if not output_path and 'output_path' in safe_locals:
|
| 171 |
+
output_path = safe_locals.get('output_path')
|
| 172 |
+
|
| 173 |
+
except Exception as exec_error:
|
| 174 |
+
return f"خطا در اجرای کد تولید شده: {str(exec_error)}\nکد تولید شده:\n{generated_code}", None
|
| 175 |
+
|
| 176 |
+
# Clean up
|
| 177 |
+
os.unlink(code_file_path)
|
| 178 |
+
|
| 179 |
+
if output_path and os.path.exists(output_path):
|
| 180 |
+
return f"عملیات با موفقیت انجام شد!\nکد تولید شده توسط Together AI:\n{generated_code}\n\nخروجی stdout:\n{stdout_output}", output_path
|
| 181 |
+
else:
|
| 182 |
+
return f"فایل خروجی یافت نشد. خروجی:\n{stdout_output}\nکد:\n{generated_code}", None
|
| 183 |
+
|
| 184 |
+
except Exception as gen_error:
|
| 185 |
+
return f"خطا در تولید کد (Together AI): {str(gen_error)}\nپرامپت:\n{instruction}", None
|
| 186 |
+
|
| 187 |
+
# Gradio Interface
|
| 188 |
+
with gr.Blocks(title="AI File Processor - Together AI") as demo:
|
| 189 |
+
gr.Markdown("# پردازشگر فایل با هوش مصنوعی (Together AI)\n\nدستور خود را وارد کنید و فایل(ها) را آپلود کنید. API Together AI (سازگار با OpenAI) کد پایتون مینویسد و اجرا میکند.\n\n**مدل استفاده شده:** CodeLlama-7B-Instruct\n**API Key:** در Secrets Hugging Face با نام TOGETHER_API_KEY ست کنید.")
|
| 190 |
+
|
| 191 |
+
with gr.Row():
|
| 192 |
+
instruction_input = gr.Textbox(label="دستور (مثال: بک گراند عکس را حذف کن)", placeholder="دستور خود را بنویسید...")
|
| 193 |
+
files_input = gr.File(file_count="multiple", label="فایل(ها)")
|
| 194 |
+
|
| 195 |
+
process_btn = gr.Button("پردازش با Together AI")
|
| 196 |
+
|
| 197 |
+
output_text = gr.Textbox(label="نتیجه و کد", lines=10)
|
| 198 |
+
output_file = gr.File(label="فایل خروجی (لینک دانلود)")
|
| 199 |
+
|
| 200 |
+
process_btn.click(
|
| 201 |
+
fn=process_request,
|
| 202 |
+
inputs=[instruction_input, files_input],
|
| 203 |
+
outputs=[output_text, output_file]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
+
demo.launch(share=True)
|