File size: 6,217 Bytes
910e364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script to verify HTML rendering and LaTeX parsing locally
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import generate_content_with_progress, process_content_with_images, convert_math_to_html
import gradio as gr

def test_math_conversion():
    """Test the convert_math_to_html function with various LaTeX expressions"""
    print("πŸ§ͺ Testing LaTeX to HTML conversion...")
    
    test_cases = [
        # LaTeX delimiters
        r"\[ m = d \times v \]",
        r"\( d \) = density",
        r"\( v \) = volume",
        
        # Fractions
        r"\frac{Distance}{Time}",
        r"\frac{120}{2}",
        r"Speed = \frac{Distance}{Time}",
        
        # Simple fractions
        "120/2",
        "5/10",
        
        # Superscripts and subscripts
        r"H_2O",
        r"2H_2 + O_2",
        r"x^2 + y^2",
        
        # Math symbols
        r"\pi \times r^2",
        r"\sqrt{25}",
        r"x \leq y",
        r"a \neq b"
    ]
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n{i}. Input: {test_case}")
        result = convert_math_to_html(test_case)
        print(f"   Output: {result}")
        print(f"   Length: {len(result)} chars")

def test_content_generation():
    """Test content generation with the same parameters as the user's example"""
    print("\n🎯 Testing content generation with user parameters...")
    
    # Same parameters as user's example
    topic = "algebra"
    subject = "Science"
    grade_level = "6-8"
    difficulty = "Intermediate"
    content_type = "Worksheets"
    content_length = "Medium (3-5 pages)"
    
    print(f"Parameters:")
    print(f"  Topic: {topic}")
    print(f"  Subject: {subject}")
    print(f"  Grade Level: {grade_level}")
    print(f"  Difficulty: {difficulty}")
    print(f"  Content Type: {content_type}")
    print(f"  Length: {content_length}")
    
    try:
        # Generate content
        print("\nπŸ“ Generating content...")
        content_generator = generate_content_with_progress(topic, subject, grade_level, difficulty, content_type, content_length)
        
        # Convert generator to string
        content = ""
        for chunk in content_generator:
            if isinstance(chunk, str):
                content += chunk
            elif isinstance(chunk, tuple) and len(chunk) >= 2:
                content += chunk[0]  # First element is usually the content
        
        print(f"βœ… Content generated successfully!")
        print(f"πŸ“Š Content length: {len(content)} characters")
        
        # Process content with images and math conversion
        print("\nπŸ”§ Processing content with math conversion...")
        processed_content = process_content_with_images(content, topic, content_type)
        
        print(f"βœ… Content processed successfully!")
        print(f"πŸ“Š Processed length: {len(processed_content)} characters")
        
        # Save to file for inspection
        with open("test_output.html", "w", encoding="utf-8") as f:
            f.write(processed_content)
        print(f"πŸ’Ύ Content saved to test_output.html")
        
        # Show a sample of the content
        print(f"\nπŸ“„ Sample of generated content (first 500 chars):")
        print("-" * 50)
        print(processed_content[:500])
        print("-" * 50)
        
        # Check for specific LaTeX patterns
        print(f"\nπŸ” Checking for LaTeX patterns:")
        patterns_to_check = [
            (r"\\\[", "Display math delimiters"),
            (r"\\\(", "Inline math delimiters"),
            (r"\\frac", "LaTeX fractions"),
            (r"\d+/\d+", "Simple fractions"),
            (r"<div.*style.*border-bottom", "HTML fractions"),
            (r"<sup>", "Superscripts"),
            (r"<sub>", "Subscripts")
        ]
        
        for pattern, description in patterns_to_check:
            import re
            matches = re.findall(pattern, processed_content)
            print(f"  {description}: {len(matches)} matches")
            if matches and len(matches) <= 3:  # Show first few matches
                print(f"    Examples: {matches[:3]}")
        
        return processed_content
        
    except Exception as e:
        print(f"❌ Error during content generation: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_gradio_rendering():
    """Test how the content would render in Gradio"""
    print("\n🎨 Testing Gradio HTML rendering...")
    
    # Create a simple Gradio interface to test rendering
    def test_render(content):
        return content
    
    # Test with sample content
    test_content = """
    <h2>Test Math Content</h2>
    <p>Display math: \[ m = d \times v \]</p>
    <p>Inline math: The density \( d \) is calculated as \( d = \frac{m}{v} \).</p>
    <p>Simple fraction: Speed = 120/2 = 60 km/h</p>
    <p>LaTeX fraction: \frac{Distance}{Time}</p>
    <p>Chemical equation: 2H_2 + O_2 β†’ 2H_2O</p>
    """
    
    print("Original test content:")
    print(test_content)
    
    # Convert math expressions
    converted_content = convert_math_to_html(test_content)
    print("\nConverted content:")
    print(converted_content)
    
    # Save converted content
    with open("test_gradio_output.html", "w", encoding="utf-8") as f:
        f.write(converted_content)
    print("πŸ’Ύ Converted content saved to test_gradio_output.html")

def main():
    """Main test function"""
    print("πŸš€ Starting HTML rendering tests...")
    print("=" * 60)
    
    # Test 1: Math conversion function
    test_math_conversion()
    
    print("\n" + "=" * 60)
    
    # Test 2: Content generation
    content = test_content_generation()
    
    print("\n" + "=" * 60)
    
    # Test 3: Gradio rendering
    test_gradio_rendering()
    
    print("\n" + "=" * 60)
    print("βœ… All tests completed!")
    print("\nπŸ“ Check these files:")
    print("  - test_output.html (full generated content)")
    print("  - test_gradio_output.html (converted test content)")
    print("\n🌐 Open these files in a web browser to see the rendered output!")

if __name__ == "__main__":
    main()