00Boobs00 commited on
Commit
94badb1
·
verified ·
1 Parent(s): 94b8264

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +142 -88
app.py CHANGED
@@ -4,93 +4,142 @@ import time
4
  from datetime import datetime
5
  import tempfile
6
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def simulate_processing(
9
  content: str,
10
  operation: str,
11
  iteration: int,
12
  creativity_level: float
13
- ) -> tuple[str, int, str, str | None]:
14
  """
15
  Simulates a Review, Revise, Refactor, and Iterate workflow.
16
- Includes simulated 'AI' parameters for a studio feel.
17
  """
18
- if not content.strip():
19
- return "", 0, "⚠️ **Please enter some text or code to begin.**", None
 
20
 
21
- # Simulate processing time based on creativity level
22
- delay = 0.3 + (creativity_level * 0.5)
23
- time.sleep(delay)
24
-
25
- result = content
26
- status_msg = ""
27
- download_filename = None
28
-
29
- # Generate a timestamp for logs
30
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
31
-
32
- if operation == "Review":
33
- status_msg = f"""
34
- ### ✅ Review Complete
35
- - **Status:** Pass
36
- - **Time:** {timestamp}
37
- - **Analysis:** Syntax looks valid.
38
- - **Suggestion:** Consider adding docstrings and type hints for better maintainability.
39
- """
40
- result = f"# REVIEW LOG [{timestamp}]\n# Status: Pass\n# Note: Code structure is solid.\n\n{content}"
41
- download_filename = "review_log.py"
42
-
43
- elif operation == "Revise":
44
- status_msg = """
45
- ### ✍️ Revision Complete
46
- - **Tone:** Professional
47
- - **Grammar:** Corrected
48
- - **Flow:** Optimized
49
- """
50
- # Simple text simulation: capitalize and clean up
51
- sentences = content.split('. ')
52
- revised = '. '.join([s.strip().capitalize() for s in sentences if s.strip()])
53
- result = revised if revised else content
54
- download_filename = "revised_text.txt"
55
-
56
- elif operation == "Refactor":
57
- status_msg = """
58
- ### ⚙️ Refactoring Complete
59
- - **Optimization:** Applied
60
- - **Complexity:** Reduced
61
- - **Style:** PEP8 Compliant
62
- """
63
- # Simple code simulation
64
- result = content.replace("var ", "let ").replace(" ", " ")
65
- result = f"# REFACTORED VERSION [{timestamp}]\n# Optimized for performance\n{result}"
66
- download_filename = "refactored_code.py"
67
-
68
- elif operation == "Iterate":
69
- iteration += 1
70
- status_msg = f"""
71
- ### 🚀 Iteration {iteration} Generated
72
- - **Creativity Level:** {creativity_level:.2f}
73
- - **Action:** Created new version based on feedback.
74
- """
75
- result = f"# --- ITERATION {iteration} ---\n# Generated at {timestamp}\n# Creativity: {creativity_level}\n{content}"
76
- download_filename = f"iteration_{iteration}.py"
77
 
78
- # Create a temporary file for download
79
- temp_file = None
80
- if download_filename and result:
81
- with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".py") as f:
82
- f.write(result)
83
- temp_file = f.name
 
 
 
 
84
 
85
- return result, iteration, status_msg, temp_file
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- def create_download_file(content: str) -> str:
88
- """Helper to create a downloadable file object."""
89
- if not content:
90
- return None
91
- with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as f:
92
- f.write(content)
93
- return f.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  # Gradio 6 Application
96
  # NO parameters in gr.Blocks() constructor!
@@ -177,37 +226,43 @@ with gr.Blocks() as demo:
177
  interactive=True
178
  )
179
 
 
180
  download_btn = gr.DownloadButton(
181
  label="📥 Download Result",
182
  variant="secondary",
183
- visible=False
 
184
  )
185
 
186
  # Event Listeners using Gradio 6 syntax
187
- def process_wrapper(content, op, iter_count, creat):
188
- res, new_iter, status, temp_path = simulate_processing(content, op, iter_count, creat)
189
- return res, new_iter, status, gr.DownloadButton(visible=True, value=temp_path)
190
-
191
  run_btn.click(
192
- fn=process_wrapper,
 
193
  inputs=[input_code, operation_mode, iteration_state, creativity],
194
  outputs=[output_code, iteration_state, status_output, download_btn],
195
  api_visibility="public"
196
  )
197
 
 
198
  clear_btn.click(
199
- fn=lambda: ("", 0, "*Ready to process...*", gr.DownloadButton(visible=False, value=None), "Review", 0.5),
 
 
 
 
 
 
 
200
  inputs=None,
201
  outputs=[input_code, iteration_state, status_output, download_btn, operation_mode, creativity],
202
  api_visibility="private"
203
  )
204
 
205
- # Allow downloading directly from the output code box if modified manually
206
- output_code.change(
207
- fn=lambda x: gr.DownloadButton(visible=True, value=create_download_file(x)) if x else gr.DownloadButton(visible=False),
208
- inputs=[output_code],
209
- outputs=[download_btn]
210
- )
211
 
212
  # Gradio 6 Launch Configuration
213
  # ALL app-level parameters (theme, css, etc.) go here!
@@ -235,7 +290,6 @@ demo.launch(
235
  {"label": "GitHub", "url": "https://github.com/gradio-app/gradio"},
236
  {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
237
  ],
238
- # Add a custom footer message
239
  head="""
240
  <style>
241
  .gradio-container {
 
4
  from datetime import datetime
5
  import tempfile
6
  import os
7
+ import traceback
8
+
9
+ def safe_write_temp_file(content: str, suffix: str = ".txt") -> str | None:
10
+ """
11
+ Safely writes content to a temporary file.
12
+ Returns the file path if successful, None otherwise.
13
+ """
14
+ try:
15
+ # Create a temp file that persists after closing (delete=False)
16
+ # We use a try/finally block to ensure we close the file handle
17
+ # before returning the path, preventing OS locking errors.
18
+ temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=suffix)
19
+ temp_file.write(content)
20
+ temp_file.close()
21
+ return temp_file.name
22
+ except IOError as e:
23
+ print(f"File System Error: {e}")
24
+ return None
25
+ except Exception as e:
26
+ print(f"Unexpected File Error: {e}")
27
+ return None
28
 
29
  def simulate_processing(
30
  content: str,
31
  operation: str,
32
  iteration: int,
33
  creativity_level: float
34
+ ) -> tuple[str, int, str, gr.DownloadButton | None]:
35
  """
36
  Simulates a Review, Revise, Refactor, and Iterate workflow.
37
+ Includes comprehensive error handling.
38
  """
39
+ # 1. Initial Validation (Double check, though validator handles the first pass)
40
+ if content is None:
41
+ return "", 0, "⚠️ **Error:** No input detected.", None
42
 
43
+ try:
44
+ # Simulate processing time based on creativity level
45
+ # Capped to prevent excessive waiting
46
+ delay = min(0.3 + (creativity_level * 0.5), 2.0)
47
+ time.sleep(delay)
48
+
49
+ result = content
50
+ status_msg = ""
51
+ download_filename = None
52
+
53
+ # Generate a timestamp for logs
54
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ if operation == "Review":
57
+ status_msg = f"""
58
+ ### Review Complete
59
+ - **Status:** Pass
60
+ - **Time:** {timestamp}
61
+ - **Analysis:** Syntax looks valid.
62
+ - **Suggestion:** Consider adding docstrings and type hints for better maintainability.
63
+ """
64
+ result = f"# REVIEW LOG [{timestamp}]\n# Status: Pass\n# Note: Code structure is solid.\n\n{content}"
65
+ download_filename = "review_log.py"
66
 
67
+ elif operation == "Revise":
68
+ status_msg = """
69
+ ### ✍️ Revision Complete
70
+ - **Tone:** Professional
71
+ - **Grammar:** Corrected
72
+ - **Flow:** Optimized
73
+ """
74
+ # Logic: Ensure we handle string operations safely
75
+ sentences = content.split('. ')
76
+ revised = '. '.join([s.strip().capitalize() for s in sentences if s.strip()])
77
+ result = revised if revised else content
78
+ download_filename = "revised_text.txt"
79
 
80
+ elif operation == "Refactor":
81
+ status_msg = """
82
+ ### ⚙️ Refactoring Complete
83
+ - **Optimization:** Applied
84
+ - **Complexity:** Reduced
85
+ - **Style:** PEP8 Compliant
86
+ """
87
+ # Logic: Safe string replacement
88
+ result = content.replace("var ", "let ").replace(" ", " ")
89
+ result = f"# REFACTORED VERSION [{timestamp}]\n# Optimized for performance\n{result}"
90
+ download_filename = "refactored_code.py"
91
+
92
+ elif operation == "Iterate":
93
+ iteration += 1
94
+ status_msg = f"""
95
+ ### 🚀 Iteration {iteration} Generated
96
+ - **Creativity Level:** {creativity_level:.2f}
97
+ - **Action:** Created new version based on feedback.
98
+ """
99
+ result = f"# --- ITERATION {iteration} ---\n# Generated at {timestamp}\n# Creativity: {creativity_level}\n{content}"
100
+ download_filename = f"iteration_{iteration}.py"
101
+
102
+ # 2. File Generation with Error Handling
103
+ temp_file_path = None
104
+ if result:
105
+ temp_file_path = safe_write_temp_file(result, ".txt")
106
+
107
+ if not temp_file_path:
108
+ # If file write failed, warn the user but don't crash the whole app
109
+ status_msg += "\n\n⚠️ **Warning:** Could not generate download file due to a system error."
110
+
111
+ # 3. Return success state
112
+ # We return an updated DownloadButton component
113
+ return result, iteration, status_msg, gr.DownloadButton(value=temp_file_path, visible=True)
114
+
115
+ except Exception as e:
116
+ # 4. Global Exception Catch
117
+ # This catches any unexpected crashes in the logic above
118
+ error_trace = traceback.format_exc()
119
+ print(f"Critical Error in Processing: {error_trace}")
120
+
121
+ error_msg = f"""
122
+ ### 🚨 Critical Error
123
+ The workflow encountered an unexpected error.
124
+
125
+ **Error Details:** `{str(e)}`
126
+
127
+ *Your input has been preserved. Please try again or check your input format.*
128
+ """
129
+
130
+ # Return error state (no download button, preserve input)
131
+ return content, iteration, error_msg, gr.DownloadButton(visible=False, value=None)
132
+
133
+ def validate_inputs(content: str, operation: str):
134
+ """
135
+ Gradio 6 Validator function.
136
+ Runs immediately on the client side before queuing.
137
+ """
138
+ if not content or not content.strip():
139
+ return [
140
+ gr.validate(False, "Input cannot be empty. Please enter text or code to proceed.")
141
+ ]
142
+ return [gr.validate(True)] # Valid
143
 
144
  # Gradio 6 Application
145
  # NO parameters in gr.Blocks() constructor!
 
226
  interactive=True
227
  )
228
 
229
+ # Initialize download button as hidden
230
  download_btn = gr.DownloadButton(
231
  label="📥 Download Result",
232
  variant="secondary",
233
+ visible=False,
234
+ size="lg"
235
  )
236
 
237
  # Event Listeners using Gradio 6 syntax
238
+
239
+ # 1. Main Execution Event
240
+ # We attach the validator here to check inputs before running the heavy function
 
241
  run_btn.click(
242
+ fn=simulate_processing,
243
+ validator=validate_inputs,
244
  inputs=[input_code, operation_mode, iteration_state, creativity],
245
  outputs=[output_code, iteration_state, status_output, download_btn],
246
  api_visibility="public"
247
  )
248
 
249
+ # 2. Clear Button Event
250
  clear_btn.click(
251
+ fn=lambda: (
252
+ "", # input_code
253
+ 0, # iteration_state
254
+ "*Ready to process...*", # status_output
255
+ gr.DownloadButton(visible=False, value=None), # download_btn
256
+ "Review", # operation_mode
257
+ 0.5 # creativity
258
+ ),
259
  inputs=None,
260
  outputs=[input_code, iteration_state, status_output, download_btn, operation_mode, creativity],
261
  api_visibility="private"
262
  )
263
 
264
+ # NOTE: Removed output_code.change listener to prevent file generation loops/locks.
265
+ # The download button is now exclusively updated by the Execute Workflow button.
 
 
 
 
266
 
267
  # Gradio 6 Launch Configuration
268
  # ALL app-level parameters (theme, css, etc.) go here!
 
290
  {"label": "GitHub", "url": "https://github.com/gradio-app/gradio"},
291
  {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
292
  ],
 
293
  head="""
294
  <style>
295
  .gradio-container {