def capitalize_sentence(sentence: str) -> str:
"""Capitalize first letter of each word."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions with argument quotes."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
return re.sub(r'\b(capitalize|duplicates)\s*(\s*([^)]+)\s*)', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Check inverse trig function domain validity."""
for func, arg in re.findall(r"(\b\w+\b)\s*(\s*([^)]+)\s*)", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
Assistant
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate expression and format result."""
try:
result = eval(expression, {"builtins": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
result = f"{result:.2e}" if use_e_notation else round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
To integrate MathJax into your PySide6 calculator application for rendering mathematical notations, you'll need to embed a web view that can interpret and render MathJax's LaTeX-like syntax. MathJax is a powerful JavaScript library for displaying mathematical notations in web browsers, and integrating it with PySide6 will significantly enhance the display capabilities of your calculator, especially in the history section.
Below are the detailed steps and the modified code to achieve this integration:
Install Required Modules:
Ensure that you have PySide6 and PySide6.QtWebEngine installed. You can install them using pip:
bash
pip install PySide6 PySide6-QtWebEngine
Import QWebEngineView:
Import the QWebEngineView from PySide6.QtWebEngineWidgets to embed a web browser within your application.
Modify the History Display:
Replace the existing QTextEdit for history with QWebEngineView. This will allow you to render HTML content with MathJax support.
Create an HTML Template with MathJax:
Prepare an HTML template that includes MathJax. This template will be used to render the history of calculations with proper mathematical formatting.
Update History Management:
Modify the methods that handle history entries to store expressions and results, and re-render the HTML content whenever a new entry is added.
Ensure Proper Communication:
Since QWebEngineView loads content asynchronously, ensure that the rendering is updated correctly after loading new entries.
Below is the revised code with detailed comments explaining each change:
python
import math
import re
from typing import Any, Union, Callable
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLineEdit, QPushButton, QLabel, QFrame, QGridLayout
)
from PySide6.QtGui import QFont
from PySide6.QtCore import Qt
# Import QWebEngineView for rendering HTML content with MathJax
from PySide6.QtWebEngineWidgets import QWebEngineView
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float:
"""Apply trig function with optional degree conversion."""
return func(math.radians(x) if use_degrees else x)
def kilograms_to_pounds(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def pounds_to_kilograms(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
def celsius_to_kelvin(c: float) -> float:
"""Convert Celsius to Kelvin."""
return c + 273.15
def kelvin_to_celsius(k: float) -> float:
"""Convert Kelvin to Celsius."""
return k - 273.15
def celsius_to_fahrenheit(c: float) -> float:
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
def fahrenheit_to_celsius(f: float) -> float:
"""Convert Fahrenheit to Celsius."""
return (f - 32) * 5 / 9
def capitalize_sentence(sentence: str) -> str:
"""Capitalize first letter of each word."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str:
"""Remove duplicate words and empty lines."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
def get_safe_globals(use_degrees: bool, variables: dict) -> dict:
"""Provide safe globals for expression evaluation."""
trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'}
safe_globals = {
"sqrt": math.sqrt,
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kilograms_to_pounds,
"kg": pounds_to_kilograms,
"C": kelvin_to_celsius,
"K": celsius_to_kelvin,
"F": celsius_to_fahrenheit,
"CF": fahrenheit_to_celsius,
"capitalize": capitalize_sentence,
"duplicates": remove_duplicates,
}
for func in trig_funcs:
safe_globals[func] = lambda x, f=func: convert_angle(getattr(math, f), x, use_degrees)
safe_globals.update(variables)
return safe_globals
def preprocess_text_functions(expression: str) -> str:
"""Preprocess text functions with argument quotes."""
def add_quotes(match):
func, args = match.groups()
return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0)
return re.sub(r'\b(capitalize|duplicates)\s*\(\s*([^)]+)\s*\)', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]:
"""Check inverse trig function domain validity."""
for func, arg in re.findall(r"(\b\w+\b)\s*\(\s*([^)]+)\s*\)", expression):
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_globals)
if abs(value) > 1:
return f"Error: {func}(x) is undefined for |x| > 1"
except Exception as e:
return f"Error: {e}"
return None
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]:
"""Safely evaluate expression and format result."""
try:
result = eval(expression, {"__builtins__": None}, safe_globals)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
if isinstance(result, (int, float)):
result = f"{result:.2e}" if use_e_notation else round(result, 2)
return result
except Exception as e:
return f"Error: {e}"
def evaluate_expression(expression: str, variables: dict, use_degrees: bool = False, use_e_notation: bool = False) -> Union[float, str]:
"""Evaluate math expression considering modes."""
assignment_match = re.match(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$', expression)
if assignment_match:
var_name, var_expr = assignment_match.groups()
safe_globals = get_safe_globals(use_degrees, variables)
var_value = safe_evaluate(var_expr, safe_globals, use_e_notation)
if isinstance(var_value, (int, float)):
variables[var_name] = var_value
return f"{var_name} = {var_value}"
return var_value
else:
safe_globals = get_safe_globals(use_degrees, variables)
expression = expression.replace("^", "**")
expression = preprocess_text_functions(expression)
error = validate_inverse_trig(expression, safe_globals)
if error:
return error
return safe_evaluate(expression, safe_globals, use_e_notation)
class CalculatorGUI(QMainWindow):
"""PySide6-based calculator application."""
def __init__(self):
super().__init__()
self.use_degrees = False
self.use_e_notation = False
self.variables = {}
self.history_entries = []
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.connect_signals()
def setup_window(self) -> None:
"""Set main window properties."""
self.setWindowTitle("Calculator with MathJax")
self.setGeometry(100, 100, 1280, 720)
def create_widgets(self) -> None:
"""Initialize GUI components."""
font = QFont()
font.setPointSize(12)
font.setFamily('Literata')
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.setPlaceholderText('Enter expression (use LaTeX syntax for math)')
self.entry.setClearButtonEnabled(True)
self.entry.returnPressed.connect(self.calculate)
# Replace QTextEdit with QWebEngineView for history
self.history_view = QWebEngineView()
self.history_view.setHtml(self.get_initial_html())
# Initialize HTML content
self.update_history_html()
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg", "K", "C", "F", "CF"],
"Text": ["capitalize", "duplicates"],
"Constants": ["pi", "e"],
"Settings": []
}
self.function_frame = QFrame()
self.create_function_buttons(font)
# Optional: Add a search functionality (Not implemented here for simplicity)
def create_function_buttons(self, font: QFont) -> None:
"""Create buttons for calculator functions."""
layout = QGridLayout()
categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)]
starting_col = 0
for category, col_span in categories:
label = QLabel(category)
label.setFont(font)
layout.addWidget(label, 0, starting_col, 1, col_span, Qt.AlignCenter)
buttons = self.function_buttons.get(category, [])
if category == "Functions":
for i, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
button.clicked.connect(lambda _, f=func: self.insert_function(f, False))
layout.addWidget(button, (i // 3) + 1, starting_col + (i % 3))
elif category == "Settings":
self.mode_button = QPushButton("Radians")
self.mode_button.setFont(font)
self.mode_button.clicked.connect(self.toggle_mode)
layout.addWidget(self.mode_button, 1, starting_col, 1, 1)
self.e_notation_button = QPushButton("E Notation: Off")
self.e_notation_button.setFont(font)
self.e_notation_button.clicked.connect(self.toggle_e_notation)
layout.addWidget(self.e_notation_button, 2, starting_col, 1, 1)
elif category == "Conversions":
for idx, func in enumerate(buttons):
display_text = {
"lb": "lb(kg)", "kg": "kg(lb)", "K": "K(°C)",
"C": "°C(K)", "F": "F(°C)", "CF": "°C(F)"
}.get(func, func)
button = QPushButton(display_text)
button.setFont(font)
button.clicked.connect(lambda _, f=func: self.insert_function(f, False))
row, col = 1 + idx // 2, starting_col + idx % 2
layout.addWidget(button, row, col)
else:
num_buttons = len(buttons)
num_rows = math.ceil(num_buttons / col_span)
for idx, func in enumerate(buttons):
button = QPushButton(func)
button.setFont(font)
button.clicked.connect(lambda _, f=func, c=(category == "Constants"): self.insert_function(f, c))
row, col = 1 + idx // col_span, starting_col + idx % col_span
layout.addWidget(button, row, col)
for extra in range(col_span * num_rows - num_buttons):
layout.addWidget(QLabel(""), 1 + extra // col_span, starting_col + extra % col_span)
starting_col += col_span
self.function_frame.setLayout(layout)
def layout_widgets(self) -> None:
"""Arrange widgets in the main window."""
central_widget = QWidget()
main_layout = QVBoxLayout()
main_layout.addWidget(self.entry)
history_layout = QHBoxLayout()
history_layout.addWidget(self.history_view)
main_layout.addLayout(history_layout)
main_layout.addWidget(self.function_frame)
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def connect_signals(self) -> None:
"""Connect widget signals."""
QApplication.instance().focusChanged.connect(self.on_focus_changed)
def toggle_mode(self) -> None:
"""Toggle between degrees and radians."""
self.use_degrees = not self.use_degrees
self.mode_button.setText("Degrees" if self.use_degrees else "Radians")
def toggle_e_notation(self) -> None:
"""Toggle scientific notation for results."""
self.use_e_notation = not self.use_e_notation
self.e_notation_button.setText(f"E Notation: {'On' if self.use_e_notation else 'Off'}")
def insert_function(self, function: str, is_constant: bool = False) -> None:
"""Insert function or constant in entry."""
current_text = self.entry.text()
cursor_position = self.entry.cursorPosition()
if is_constant:
new_text = f"{current_text[:cursor_position]}{function}"
new_cursor_position = cursor_position + len(function)
else:
new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}"
new_cursor_position = cursor_position + len(function) + 1
self.entry.setText(new_text)
self.entry.setCursorPosition(new_cursor_position)
self.entry.setFocus()
def calculate(self) -> None:
"""Evaluate entered expression."""
expression = self.entry.text().strip()
if expression:
result = evaluate_expression(
expression, self.variables, use_degrees=self.use_degrees, use_e_notation=self.use_e_notation
)
self.display_result(expression, result)
self.entry.clear()
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Show result in history with MathJax rendering."""
mode = "D" if self.use_degrees else "R"
if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression):
history_entry = f"[{mode}] {result}"
else:
# Convert expression and result to LaTeX format
# Assuming the user can input LaTeX-like syntax
history_entry = f"[{mode}] ${expression}$ = ${result}$"
self.history_entries.append(history_entry)
self.update_history_html()
def get_initial_html(self) -> str:
"""Return initial HTML with MathJax setup."""
# Using MathJax CDN
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator History</title>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
body { font-family: Arial, sans-serif; padding: 10px; }
.entry { margin-bottom: 10px; }
</style>
</head>
<body>
<div id="history">
<!-- History entries will be injected here -->
</div>
</body>
</html>
"""
def update_history_html(self) -> None:
"""Update the HTML content of the history view with current entries."""
html_start = """
<div id="history">
"""
html_entries = ""
for entry in self.history_entries:
# Each entry is wrapped in a div for styling
html_entries += f"<div class='entry'>{entry}</div>\n"
html_end = """
</div>
<script>
MathJax.typeset();
</script>
"""
full_html = html_start + html_entries + html_end
self.history_view.setHtml(full_html)
def on_focus_changed(self, old: QWidget, new: QWidget) -> None:
"""Handle focus changes if needed."""
pass # Implement if additional behavior is required
def showEvent(self, event) -> None:
"""Handle the event when the window is shown."""
super().showEvent(event)
self.update_history_html()
def main() -> None:
"""Start the calculator application."""
app = QApplication([])
calculator = CalculatorGUI()
calculator.show()
app.exec()
if __name__ == "__main__":
main()
Explanation of Changes:
Embedding QWebEngineView:
Import Statement:
python
from PySide6.QtWebEngineWidgets import QWebEngineView
Added to utilize the web engine for rendering HTML content with MathJax.
Replaced the QTextEdit with QWebEngineView to display HTML content.
HTML Template with MathJax:
get_initial_html Method:
python
def get_initial_html(self) -> str:
"""Return initial HTML with MathJax setup."""
# Using MathJax CDN
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator History</title>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
body { font-family: Arial, sans-serif; padding: 10px; }
.entry { margin-bottom: 10px; }
</style>
</head>
<body>
<div id="history">
<!-- History entries will be injected here -->
</div>
</body>
</html>
"""
This method returns the initial HTML structure with MathJax loaded via CDN.
Updating History with MathJax:
display_result Method:
python
Usage Notes:
LaTeX Syntax:
To utilize MathJax effectively, users should input expressions using LaTeX syntax. For example:
To display the sine function: \sin(\pi/2)
To write fractions: \frac{1}{2}
MathJax Loading:
The current setup loads MathJax from a CDN. If your application needs to work offline, consider downloading MathJax and serving it locally.
Performance Considerations:
Using QWebEngineView can be resource-intensive for large applications. Ensure that the number of history entries does not degrade performance.
Security Considerations:
Since QWebEngineView can execute JavaScript, ensure that the content being loaded is sanitized and does not expose vulnerabilities.
Optional Enhancements:
Search Functionality:
Reintroduce a search bar by embedding it within the HTML template and using JavaScript to filter history entries.
Dynamic Styling:
Enhance the CSS to improve the visual appeal of the history entries, such as adding colors, fonts, or layout adjustments.
Local MathJax Hosting:
Host MathJax locally to improve load times and enable offline usage.
Advanced Math Rendering:
Utilize more advanced features of MathJax, such as equation numbering or custom macros, to enhance the mathematical expressions.
By following the above modifications, your calculator application will now render mathematical notations beautifully using MathJax, providing a more intuitive and visually appealing user experience.
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Show result in history with MathJax rendering."""
mode = "D" if self.use_degrees else "R"
if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression):
history_entry = f"[{mode}] {result}"
else:
# Convert expression and result to LaTeX format
# Assuming the user can input LaTeX-like syntax
history_entry = f"[{mode}] ${expression}$ = ${result}$"
self.history_entries.append(history_entry)
self.update_history_html()
Here, expressions and results are wrapped with $ to denote LaTeX math mode, which MathJax will render.
update_history_html Method:
python
def update_history_html(self) -> None:
"""Update the HTML content of the history view with current entries."""
html_start = """
<div id="history">
"""
html_entries = ""
for entry in self.history_entries:
# Each entry is wrapped in a div for styling
html_entries += f"<div class='entry'>{entry}</div>\n"
html_end = """
</div>
<script>
MathJax.typeset();
</script>
"""
full_html = html_start + html_entries + html_end
self.history_view.setHtml(full_html)
This method constructs the full HTML content by iterating over history_entries, injecting them into the HTML, and then invoking MathJax.typeset() to render the mathematical notations.
Styling:
Basic CSS is added within the HTML template to style the history entries.
Removing Unused Widgets:
The search functionality using QTextEdit, QScrollBar, and related widgets has been removed for simplicity. If you wish to retain search functionality, additional adjustments are needed to work with QWebEngineView.