#!/usr/bin/env python3 """ Test script for unlimited text analysis functionality. This script demonstrates the new line-by-line analysis capability. """ import requests import json import time import sys # Configuration API_BASE_URL = "http://localhost:8000" # Change this to your server URL TEST_ESSAY = """ The Impact of Climate Change on Global Agriculture Climate change represents one of the most significant challenges facing humanity in the 21st century. Its effects on global agriculture are particularly concerning, as food security is fundamental to human survival and economic stability. This essay examines the multifaceted impact of climate change on agricultural systems worldwide, exploring both the challenges and potential solutions. Rising temperatures have already begun to alter growing seasons and crop yields across different regions. In some areas, warmer temperatures may initially benefit certain crops by extending growing seasons. However, the overall trend suggests that most agricultural regions will face significant challenges. Heat stress can reduce crop productivity, while increased evaporation rates may lead to soil moisture deficits. These changes are particularly problematic for staple crops like wheat, rice, and maize, which form the foundation of global food security. Precipitation patterns are also shifting due to climate change, creating both droughts and floods in unexpected regions. Droughts can devastate crops and livestock, while excessive rainfall can lead to soil erosion and nutrient leaching. The unpredictability of weather patterns makes it difficult for farmers to plan planting and harvesting schedules, leading to reduced agricultural efficiency and increased economic uncertainty. Soil degradation is another critical issue exacerbated by climate change. Increased temperatures can accelerate the decomposition of organic matter in soil, reducing its fertility and water-holding capacity. Additionally, extreme weather events can cause soil erosion, further diminishing agricultural productivity. This degradation is particularly concerning in regions where soil quality is already poor. The impact of climate change on agriculture extends beyond crop production to include livestock and fisheries. Heat stress can reduce livestock productivity and increase mortality rates, while changing ocean temperatures and acidity levels can affect fish populations and marine ecosystems. These changes threaten both food security and the livelihoods of millions of people who depend on these industries. However, there are potential solutions and adaptation strategies that can help mitigate these impacts. Agricultural technology and innovation play a crucial role in developing climate-resilient crops and farming practices. Genetic modification and selective breeding can create crop varieties that are more tolerant to heat, drought, and other climate-related stresses. Precision agriculture techniques, including the use of sensors and data analytics, can help farmers optimize resource use and improve crop management. Sustainable farming practices, such as crop rotation, conservation tillage, and integrated pest management, can help maintain soil health and reduce the environmental impact of agriculture. These practices not only improve resilience to climate change but also contribute to carbon sequestration and biodiversity conservation. Investment in agricultural infrastructure, including irrigation systems and storage facilities, can help farmers adapt to changing weather patterns. Improved water management systems can help mitigate the effects of both droughts and floods, while better storage facilities can reduce post-harvest losses and improve food security. International cooperation and policy frameworks are essential for addressing the global nature of climate change impacts on agriculture. The Paris Agreement and other international initiatives provide frameworks for reducing greenhouse gas emissions and supporting adaptation efforts. However, more specific policies and funding mechanisms are needed to support agricultural adaptation and resilience. Education and capacity building are also crucial for helping farmers adapt to climate change. Training programs can teach farmers about new technologies and practices, while extension services can provide ongoing support and information. This knowledge transfer is particularly important in developing countries where agricultural communities may have limited access to resources and information. The role of research and development cannot be overstated in addressing climate change impacts on agriculture. Continued investment in agricultural research is essential for developing new technologies, crop varieties, and farming practices that can help ensure food security in a changing climate. This research should be interdisciplinary, involving not only agricultural scientists but also climate scientists, economists, and social scientists. In conclusion, climate change poses significant challenges to global agriculture, threatening food security and economic stability. However, through innovation, sustainable practices, and international cooperation, it is possible to adapt agricultural systems to these challenges. The key is to act quickly and decisively, implementing both mitigation and adaptation strategies to ensure a sustainable and secure food future for all. The success of these efforts will depend on the commitment of governments, businesses, and individuals to prioritize climate action and agricultural sustainability. By working together, we can build more resilient agricultural systems that can feed a growing global population while protecting the environment for future generations. """ def test_unlimited_analysis(): """Test the unlimited text analysis endpoint.""" print("๐Ÿงช Testing Unlimited Text Analysis System") print("=" * 50) # Test data test_data = { 'essay_text': TEST_ESSAY, 'question': 'Analyze the impact of climate change on global agriculture' } print(f"๐Ÿ“ Essay Statistics:") print(f" - Characters: {len(TEST_ESSAY)}") print(f" - Words: {len(TEST_ESSAY.split())}") print(f" - Lines: {len(TEST_ESSAY.split(chr(10)))}") print(f" - Paragraphs: {len(TEST_ESSAY.split(chr(10) + chr(10)))}") print() try: print("๐Ÿš€ Sending request to unlimited analysis endpoint...") start_time = time.time() response = requests.post( f"{API_BASE_URL}/api/essay-analysis-unlimited", data=test_data, timeout=300 # 5 minutes timeout for unlimited processing ) end_time = time.time() processing_time = end_time - start_time print(f"โฑ๏ธ Processing completed in {processing_time:.2f} seconds") print() if response.status_code == 200: result = response.json() print("โœ… Analysis Results:") print("-" * 30) # Processing info processing_info = result.get('processing_info', {}) print(f"๐Ÿ“Š Processing Information:") print(f" - Word Count: {processing_info.get('word_count', 'N/A')}") print(f" - Token Count: {processing_info.get('token_count', 'N/A')}") print(f" - Line Count: {processing_info.get('line_count', 'N/A')}") print(f" - Character Count: {processing_info.get('character_count', 'N/A')}") print(f" - Processing Mode: {processing_info.get('processing_mode', 'N/A')}") print(f" - Chunks Created: {processing_info.get('chunks_created', 'N/A')}") print(f" - Lines Processed: {processing_info.get('lines_processed', 'N/A')}") print() # Analysis results analysis = result.get('analysis', {}) # Overall analysis overall_analysis = analysis.get('overall_analysis', {}) if overall_analysis and 'error' not in overall_analysis: print(f"๐ŸŽฏ Overall Score: {overall_analysis.get('overall_score', 'N/A')}/100") print() # Category scores category_scores = overall_analysis.get('category_scores', {}) if category_scores: print("๐Ÿ“ˆ Category Scores:") for category, score in category_scores.items(): category_name = category.replace('_', ' ').title() print(f" - {category_name}: {score}/100") print() # Summary statistics summary_stats = analysis.get('summary_statistics', {}) if summary_stats and 'error' not in summary_stats: print("๐Ÿ“‹ Summary Statistics:") print(f" - Total Lines: {summary_stats.get('total_lines', 'N/A')}") print(f" - Non-empty Lines: {summary_stats.get('non_empty_lines', 'N/A')}") print(f" - Lines with Issues: {summary_stats.get('lines_with_issues', 'N/A')}") print(f" - Average Score: {summary_stats.get('average_score', 'N/A')}") print() # Line-by-line analysis line_analyses = analysis.get('line_by_line_analysis', []) if line_analyses: print(f"๐Ÿ“ Line-by-Line Analysis: {len(line_analyses)} lines analyzed") print() # Show first few line analyses print("๐Ÿ” Sample Line Analyses:") for i, line_analysis in enumerate(line_analyses[:5]): # Show first 5 lines line_number = line_analysis.get('line_number', 'N/A') line_content = line_analysis.get('line_content', '').strip() score = line_analysis.get('score', 'N/A') line_type = line_analysis.get('line_type', 'N/A') print(f" Line {line_number} ({line_type}) - Score: {score}/100") if line_content: content_preview = line_content[:100] + "..." if len(line_content) > 100 else line_content print(f" Content: {content_preview}") issues = line_analysis.get('issues', []) if issues: print(f" Issues: {len(issues)} found") print() # Recommendations recommendations = analysis.get('recommendations', []) if recommendations: print("๐Ÿ’ก Top Recommendations:") for i, recommendation in enumerate(recommendations[:5], 1): # Show first 5 print(f" {i}. {recommendation}") print() # PDF generation if 'pdf_path' in result: print(f"๐Ÿ“„ PDF Report: {result['pdf_path']}") elif 'pdf_error' in result: print(f"โš ๏ธ PDF Error: {result['pdf_error']}") print("โœ… Unlimited text analysis test completed successfully!") else: print(f"โŒ Error: {response.status_code}") print(f"Response: {response.text}") except requests.exceptions.Timeout: print("โฐ Timeout: The request took too long to complete") except requests.exceptions.ConnectionError: print("๐Ÿ”Œ Connection Error: Could not connect to the server") print(f"Make sure the server is running at {API_BASE_URL}") except Exception as e: print(f"โŒ Unexpected error: {str(e)}") def test_very_long_text(): """Test with a very long text to demonstrate unlimited processing.""" print("\n๐Ÿงช Testing with Very Long Text") print("=" * 40) # Create a very long text by repeating the essay very_long_text = TEST_ESSAY * 10 # 10x longer print(f"๐Ÿ“ Very Long Text Statistics:") print(f" - Characters: {len(very_long_text)}") print(f" - Words: {len(very_long_text.split())}") print(f" - Lines: {len(very_long_text.split(chr(10)))}") print() test_data = { 'essay_text': very_long_text, 'question': 'Comprehensive analysis of extended climate change essay' } try: print("๐Ÿš€ Sending very long text for unlimited analysis...") start_time = time.time() response = requests.post( f"{API_BASE_URL}/api/essay-analysis-unlimited", data=test_data, timeout=600 # 10 minutes timeout for very long text ) end_time = time.time() processing_time = end_time - start_time print(f"โฑ๏ธ Processing completed in {processing_time:.2f} seconds") if response.status_code == 200: result = response.json() processing_info = result.get('processing_info', {}) print("โœ… Very Long Text Analysis Results:") print(f" - Lines Processed: {processing_info.get('lines_processed', 'N/A')}") print(f" - Chunks Created: {processing_info.get('chunks_created', 'N/A')}") print(f" - Processing Mode: {processing_info.get('processing_mode', 'N/A')}") print("โœ… Unlimited processing capability confirmed!") else: print(f"โŒ Error: {response.status_code}") print(f"Response: {response.text}") except Exception as e: print(f"โŒ Error testing very long text: {str(e)}") if __name__ == "__main__": print("๐ŸŽ“ CSS Essay Grader - Unlimited Text Analysis Test") print("=" * 60) print() # Test basic unlimited analysis test_unlimited_analysis() # Test with very long text test_very_long_text() print("\n๐ŸŽ‰ All tests completed!") print("\nKey Features Demonstrated:") print("โœ… Unlimited text processing (no character limits)") print("โœ… Line-by-line analysis") print("โœ… Comprehensive feedback for each line") print("โœ… Detailed scoring and categorization") print("โœ… PDF report generation") print("โœ… Performance optimization with chunking")