Skip to content

Commit accc636

Browse files
committed
Merge branch 'main' of https://github.com/codeflash-ai/codeflash into windows-fixes
2 parents 3a03d40 + abde333 commit accc636

23 files changed

+2331
-223
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from code_to_optimize.bubble_sort_in_class import BubbleSortClass
2+
3+
4+
def sort_classmethod(x):
5+
y = BubbleSortClass()
6+
return y.sorter(x)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from code_to_optimize.bubble_sort_in_nested_class import WrapperClass
2+
3+
4+
def sort_classmethod(x):
5+
y = WrapperClass.BubbleSortClass()
6+
return y.sorter(x)

code_to_optimize/code_directories/simple_tracer_e2e/workload.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from concurrent.futures import ThreadPoolExecutor
2+
3+
24
def funcA(number):
35
k = 0
46
for i in range(number * 100):
@@ -9,6 +11,7 @@ def funcA(number):
911
# Use a generator expression directly in join for more efficiency
1012
return " ".join(str(i) for i in range(number))
1113

14+
1215
def test_threadpool() -> None:
1316
pool = ThreadPoolExecutor(max_workers=3)
1417
args = list(range(10, 31, 10))
@@ -19,4 +22,4 @@ def test_threadpool() -> None:
1922

2023

2124
if __name__ == "__main__":
22-
test_threadpool()
25+
test_threadpool()

codeflash/api/aiservice.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,76 @@ def optimize_python_code(
135135
console.rule()
136136
return []
137137

138+
def optimize_python_code_line_profiler(
139+
self,
140+
source_code: str,
141+
dependency_code: str,
142+
trace_id: str,
143+
line_profiler_results: str,
144+
num_candidates: int = 10,
145+
experiment_metadata: ExperimentMetadata | None = None,
146+
) -> list[OptimizedCandidate]:
147+
"""Optimize the given python code for performance by making a request to the Django endpoint.
148+
149+
Parameters
150+
----------
151+
- source_code (str): The python code to optimize.
152+
- dependency_code (str): The dependency code used as read-only context for the optimization
153+
- trace_id (str): Trace id of optimization run
154+
- num_candidates (int): Number of optimization variants to generate. Default is 10.
155+
- experiment_metadata (Optional[ExperimentalMetadata, None]): Any available experiment metadata for this optimization
156+
157+
Returns
158+
-------
159+
- List[OptimizationCandidate]: A list of Optimization Candidates.
160+
161+
"""
162+
payload = {
163+
"source_code": source_code,
164+
"dependency_code": dependency_code,
165+
"num_variants": num_candidates,
166+
"line_profiler_results": line_profiler_results,
167+
"trace_id": trace_id,
168+
"python_version": platform.python_version(),
169+
"experiment_metadata": experiment_metadata,
170+
"codeflash_version": codeflash_version,
171+
}
172+
173+
logger.info("Generating optimized candidates…")
174+
console.rule()
175+
if line_profiler_results=="":
176+
logger.info("No LineProfiler results were provided, Skipping optimization.")
177+
console.rule()
178+
return []
179+
try:
180+
response = self.make_ai_service_request("/optimize-line-profiler", payload=payload, timeout=600)
181+
except requests.exceptions.RequestException as e:
182+
logger.exception(f"Error generating optimized candidates: {e}")
183+
ph("cli-optimize-error-caught", {"error": str(e)})
184+
return []
185+
186+
if response.status_code == 200:
187+
optimizations_json = response.json()["optimizations"]
188+
logger.info(f"Generated {len(optimizations_json)} candidates.")
189+
console.rule()
190+
return [
191+
OptimizedCandidate(
192+
source_code=opt["source_code"],
193+
explanation=opt["explanation"],
194+
optimization_id=opt["optimization_id"],
195+
)
196+
for opt in optimizations_json
197+
]
198+
try:
199+
error = response.json()["error"]
200+
except Exception:
201+
error = response.text
202+
logger.error(f"Error generating optimized candidates: {response.status_code} - {error}")
203+
ph("cli-optimize-error-response", {"response_status_code": response.status_code, "error": error})
204+
console.rule()
205+
return []
206+
207+
138208
def log_results(
139209
self,
140210
function_trace_id: str,

codeflash/cli_cmds/console.py

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,16 @@
77

88
from rich.console import Console
99
from rich.logging import RichHandler
10-
from rich.progress import Progress, SpinnerColumn, TimeElapsedColumn
10+
from rich.progress import (
11+
BarColumn,
12+
MofNCompleteColumn,
13+
Progress,
14+
SpinnerColumn,
15+
TaskProgressColumn,
16+
TextColumn,
17+
TimeElapsedColumn,
18+
TimeRemainingColumn,
19+
)
1120

1221
from codeflash.cli_cmds.console_constants import SPINNER_TYPES
1322
from codeflash.cli_cmds.logging_config import BARE_LOGGING_FORMAT
@@ -22,7 +31,15 @@
2231
console = Console()
2332
logging.basicConfig(
2433
level=logging.INFO,
25-
handlers=[RichHandler(rich_tracebacks=True, markup=False, console=console, show_path=False, show_time=False)],
34+
handlers=[
35+
RichHandler(
36+
rich_tracebacks=True,
37+
markup=False,
38+
console=console,
39+
show_path=False,
40+
show_time=False,
41+
)
42+
],
2643
format=BARE_LOGGING_FORMAT,
2744
)
2845

@@ -31,7 +48,9 @@
3148

3249

3350
def paneled_text(
34-
text: str, panel_args: dict[str, str | bool] | None = None, text_args: dict[str, str] | None = None
51+
text: str,
52+
panel_args: dict[str, str | bool] | None = None,
53+
text_args: dict[str, str] | None = None,
3554
) -> None:
3655
"""Print text in a panel."""
3756
from rich.panel import Panel
@@ -58,7 +77,9 @@ def code_print(code_str: str) -> None:
5877

5978

6079
@contextmanager
61-
def progress_bar(message: str, *, transient: bool = False) -> Generator[TaskID, None, None]:
80+
def progress_bar(
81+
message: str, *, transient: bool = False
82+
) -> Generator[TaskID, None, None]:
6283
"""Display a progress bar with a spinner and elapsed time."""
6384
progress = Progress(
6485
SpinnerColumn(next(spinners)),
@@ -70,3 +91,25 @@ def progress_bar(message: str, *, transient: bool = False) -> Generator[TaskID,
7091
task = progress.add_task(message, total=None)
7192
with progress:
7293
yield task
94+
95+
96+
@contextmanager
97+
def test_files_progress_bar(
98+
total: int, description: str
99+
) -> Generator[tuple[Progress, TaskID], None, None]:
100+
"""Progress bar for test files."""
101+
with Progress(
102+
SpinnerColumn(next(spinners)),
103+
TextColumn("[progress.description]{task.description}"),
104+
BarColumn(
105+
complete_style="cyan",
106+
finished_style="green",
107+
pulse_style="yellow",
108+
),
109+
MofNCompleteColumn(),
110+
TimeElapsedColumn(),
111+
TimeRemainingColumn(),
112+
transient=True,
113+
) as progress:
114+
task_id = progress.add_task(description, total=total)
115+
yield progress, task_id

0 commit comments

Comments
 (0)