frontend_test / app /main.py
ariansyahdedy's picture
Initial Commit
f10d8ff
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio
import json
import io
import base64
import matplotlib.pyplot as plt
import pandas as pd
app = FastAPI()
def build_text_stream():
"""
Create the full text stream for the text-only endpoint.
The text is broken into words, with each word sent as a separate event.
"""
# Full text as provided (simulate with the complete sample, add newlines for clarity)
text = (
"To be an outstanding front-end engineer, you'll need a combination of technical skills, "
"soft skills, and a passion for continuous learning. Here are the key areas to focus on: "
"**Technical Skills:** 1. **HTML/CSS**: A solid understanding of HTML5, CSS3, and their respective best practices "
"is essential for building robust and maintainable front-end applications. 2. **JavaScript**: Proficiency in JavaScript, "
"including its various frameworks and libraries such as React, Angular, or Vue.js, is crucial for creating dynamic and interactive user interfaces. "
"3. **Front-end frameworks and libraries**: Familiarity with popular front-end frameworks and libraries like Bootstrap, Material-UI, or Tailwind CSS "
"can help you build responsive and visually appealing interfaces. 4. **State management**: Understanding state management techniques, such as Redux or MobX, "
"is essential for managing complex application state and ensuring a seamless user experience. 5. **Performance optimization**: Knowledge of performance optimization techniques, "
"including code splitting, lazy loading, and caching, is vital for delivering fast and efficient applications. 6. **Accessibility**: Understanding web accessibility guidelines and "
"implementing them in your code is crucial for ensuring that your application is usable by everyone, regardless of abilities. 7. **Version control**: Familiarity with version control systems like Git "
"is essential for managing code changes, collaborating with team members, and maintaining a clean and organized codebase. "
"**Soft Skills:** 1. **Communication**: Effective communication is critical for collaborating with designers, back-end engineers, and other stakeholders to ensure that everyone is on the same page. "
"2. **Problem-solving**: Strong problem-solving skills are essential for debugging complex issues, identifying root causes, and implementing effective solutions. "
"3. **Adaptability**: The ability to adapt to changing requirements, new technologies, and evolving project needs is crucial for staying ahead of the curve and delivering high-quality results. "
"4. **Time management**: Effective time management is essential for meeting deadlines, prioritizing tasks, and delivering projects on time. "
"5. **Continuous learning**: A passion for continuous learning is vital for staying up-to-date with the latest front-end technologies, frameworks, and best practices. "
"**Best Practices:** 1. **Write clean and maintainable code**: Follow coding standards, use meaningful variable names, and keep your code organized and modular. "
"2. **Use version control**: Use Git or other version control systems to manage code changes, collaborate with team members, and maintain a clean and organized codebase. "
"3. **Test and debug**: Write unit tests, integration tests, and end-to-end tests to ensure that your code is working as expected and catch bugs early. "
"4. **Follow accessibility guidelines**: Implement web accessibility guidelines to ensure that your application is usable by everyone, regardless of abilities. "
"5. **Stay up-to-date with industry trends**: Participate in online communities, attend conferences, and read industry blogs to stay informed about the latest front-end technologies and best practices. "
"Examples of Outstanding Front-end Engineers: * **Linus Borg**: A renowned front-end engineer and speaker, known for his expertise in React, Redux, and performance optimization. "
"* **Addy Osmani**: A Google developer advocate and front-end engineer, recognized for his work on web performance, accessibility, and modern web development. "
"* **Max Stoiber**: A front-end engineer and speaker, known for his expertise in React, Redux, and state management. "
"By focusing on these technical skills, soft skills, and best practices, you can become an outstanding front-end engineer and deliver high-quality applications that meet the needs of your users."
)
# Break the text into individual words and newlines (if desired, you can also add empty lines as in your sample)
return text.split(" ")
async def text_stream_generator():
"""
Generator that streams the complete text word by word.
"""
words = build_text_stream()
for word in words:
yield f"data: {word}\n\n"
await asyncio.sleep(0.2) # Adjust the delay as needed
@app.post("/v1/test_text")
async def test_text():
return StreamingResponse(text_stream_generator(), media_type="text/event-stream")
def generate_chart():
"""
Generate a Base64-encoded bar chart.
"""
data = {
"territory": ["EMEA", "NA", "APAC", "Japan"],
"total_sales": [4979272.41, 3852061.39, 746121.83, 455173.22]
}
df = pd.DataFrame(data)
plt.figure(figsize=(6, 4))
plt.bar(df["territory"], df["total_sales"], color=["blue", "green", "red", "orange"])
plt.xlabel("Market Territory")
plt.ylabel("Total Sales")
plt.title("Total Sales by Market Territory")
img_buffer = io.BytesIO()
plt.savefig(img_buffer, format="png")
plt.close()
img_buffer.seek(0)
return base64.b64encode(img_buffer.getvalue()).decode("utf-8")
async def chart_text_generator():
"""
Generator that streams both a Base64-encoded chart and text word by word.
"""
# Prepare chart data with extra configuration if needed
chart_payload = {
"chartType": "BarChart",
"data": [
{"territory": "EMEA", "total_sales": 4979272.41},
{"territory": "NA", "total_sales": 3852061.39},
{"territory": "APAC", "total_sales": 746121.83},
{"territory": "Japan", "total_sales": 455173.22}
],
"config": {
"xKey": "territory",
"xAxisLabel": "Market Territory",
"yAxisLabel": "Total Sales",
"yAxis": {
"label": {"value": "Total Sales", "angle": -90, "position": "insideLeft", "offset": -60, "dy": 10},
"tick": {"fontSize": 12},
"padding": {"top": 10, "bottom": 10}
},
"series": [
{"dataKey": "total_sales", "color": "#8884d8", "name": "Total Sales"}
],
"dataPointCount": 4,
"tooltipFormatterType": "usd",
"tooltipLabelFormatterType": None,
"yAxisTickFormatterType": "shortNumber",
"margin": {"top": 20, "right": 30, "left": 60, "bottom": 60}
},
"chartTitle": "Total Sales by Market Territory",
"chartImage": generate_chart()
}
# First send the complete chart JSON as one event
yield f"data: {json.dumps(chart_payload)}\n\n"
await asyncio.sleep(1) # Brief pause before streaming the text
# Now stream the text details word-by-word
full_text = (
"The current sales data for different regions is as follows: "
"EMEA (Europe, Middle East, and Africa): $4,979,272.41, "
"NA (North America): $3,852,061.39, "
"APAC (Asia Pacific): $746,121.83, "
"and Japan: $455,173.22. "
"These figures represent the total sales for each region, providing a snapshot of the current sales performance across different geographic areas."
)
words = full_text.split(" ")
for word in words:
yield f"data: {word}\n\n"
await asyncio.sleep(0.2)
@app.post("/v1/test_chart")
async def test_chart():
return StreamingResponse(chart_text_generator(), media_type="text/event-stream")