Spaces:
Paused
Paused
Update app.py
Browse files489 unmodified lines490491492493494495496497148 unmodified lines646647648649650651652653489 unmodified lines# if __name__ == "__main__":# app.run(host='0.0.0.0', port=7860)from http.server import HTTPServer, SimpleHTTPRequestHandlerfrom pyngrok import ngrokimport osfrom mistralai.client import MistralClientfrom mistralai.models.chat_completion import ChatMessage148 unmodified linesself.send_error(404)if __name__ == '__main__':port = 7860server = HTTPServer(('', port), MyHandler)public_url = ngrok.connect(port).public_urlprint(f" * ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"")server.serve_forever()489 unmodified lines490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659148 unmodified lines808809810811812813814489 unmodified lines# if __name__ == "__main__":# app.run(host='0.0.0.0', port=7860)# from http.server import HTTPServer, SimpleHTTPRequestHandler# from pyngrok import ngrok# import os# from mistralai.client import MistralClient# from mistralai.models.chat_completion import ChatMessage# import json# # Mistral AI setup# api_key = os.getenv("MISTRAL_API_KEY")# if not api_key:# raise ValueError("MISTRAL_API_KEY environment variable not set")# model = "mistral-tiny"# client = MistralClient(api_key=api_key)# def generate_goals(input_var):# messages = [# ChatMessage(role="user", content=f"Generate 5 specific, industry relevant goals for {input_var} using Python and Pandas in exam data analysis. Each goal should include a brief name and a one-sentence description of the task or skill.")# ]# try:# response = client.chat(model=model, messages=messages)# return response.choices[0].message.content# except Exception as e:# return f"An error occurred: {str(e)}"# html_content = """# <!DOCTYPE html># <html lang="en"># <head># <meta charset="UTF-8"># <meta name="viewport" content="width=device-width, initial-scale=1.0"># <title>Exam Data Analysis Goals Generator</title># <script src="https://d3js.org/d3.v7.min.js"></script># <style># #visualization { width: 100%; height: 600px; border: 1px solid #ccc; }# #generatedGoals { margin-top: 20px; padding: 10px; border: 1px solid #ccc; }# </style># </head># <body># <h1>Exam Data Analysis Goals Generator</h1># <div id="visualization"></div># <div id="generatedGoals"></div># <script># const width = 1200;# const height = 800;# const goals = [# { id: 1, x: 100, y: 400, name: "Automate Data Import", description: "Develop scripts to automate exam data extraction from various sources (CSV, Excel, databases) using Pandas read_* functions." },# { id: 2, x: 200, y: 300, name: "Data Cleaning", description: "Implement robust data cleaning processes to handle missing values, outliers, and inconsistencies in exam data using Pandas methods like dropna(), fillna(), and apply()." },# { id: 3, x: 300, y: 200, name: "Data Transformation", description: "Utilize Pandas for complex data transformations such as pivoting exam results, melting question-wise scores, and creating derived features for analysis." },# { id: 4, x: 400, y: 300, name: "Statistical Analysis", description: "Develop functions to automate statistical analysis of exam results, including descriptive statistics, hypothesis testing, and correlation analysis using Pandas and SciPy." },# { id: 5, x: 500, y: 400, name: "Performance Metrics", description: "Create custom functions to calculate industry-standard exam performance metrics like item difficulty, discrimination index, and reliability coefficients using Pandas operations." },# // Add more goals here...# ];# const connections = [# { source: 1, target: 2 },# { source: 2, target: 3 },# { source: 3, target: 4 },# { source: 4, target: 5 },# // Add more connections here...# ];# const svg = d3.select("#visualization")# .append("svg")# .attr("width", width)# .attr("height", height);# const simulation = d3.forceSimulation(goals)# .force("link", d3.forceLink(connections).id(d => d.id))# .force("charge", d3.forceManyBody().strength(-400))# .force("center", d3.forceCenter(width / 2, height / 2));# const link = svg.append("g")# .selectAll("line")# .data(connections)# .enter().append("line")# .attr("stroke", "#999")# .attr("stroke-opacity", 0.6);# const node = svg.append("g")# .selectAll("circle")# .data(goals)# .enter().append("circle")# .attr("r", 10)# .attr("fill", d => d.color || "#69b3a2")# .call(d3.drag()# .on("start", dragstarted)# .on("drag", dragged)# .on("end", dragended));# const text = svg.append("g")# .selectAll("text")# .data(goals)# .enter().append("text")# .text(d => d.name)# .attr("font-size", "12px")# .attr("dx", 12)# .attr("dy", 4);# node.on("click", async function(event, d) {# const response = await fetch('/generate_goals', {# method: 'POST',# headers: { 'Content-Type': 'application/json' },# body: JSON.stringify({ input_var: d.name })# });# const data = await response.json();# document.getElementById("generatedGoals").innerHTML = `<h2>Generated Goals for ${d.name}</h2><pre>${data.goals}</pre>`;# });# simulation.on("tick", () => {# link# .attr("x1", d => d.source.x)# .attr("y1", d => d.source.y)# .attr("x2", d => d.target.x)# .attr("y2", d => d.target.y);# node# .attr("cx", d => d.x)# .attr("cy", d => d.y);# text# .attr("x", d => d.x)# .attr("y", d => d.y);# });# function dragstarted(event) {# if (!event.active) simulation.alphaTarget(0.3).restart();# event.subject.fx = event.subject.x;# event.subject.fy = event.subject.y;# }# function dragged(event) {# event.subject.fx = event.x;# event.subject.fy = event.y;# }# function dragended(event) {# if (!event.active) simulation.alphaTarget(0);# event.subject.fx = null;# event.subject.fy = null;# }# </script># </body># </html># """# class MyHandler(SimpleHTTPRequestHandler):# def do_GET(self):# self.send_response(200)# self.send_header('Content-type', 'text/html')# self.end_headers()# self.wfile.write(html_content.encode())# def do_POST(self):# if self.path == '/generate_goals':# content_length = int(self.headers['Content-Length'])# post_data = self.rfile.read(content_length)# data = json.loads(post_data.decode('utf-8'))# input_var = data['input_var']# goals = generate_goals(input_var)# self.send_response(200)# self.send_header('Content-type', 'application/json')# self.end_headers()# self.wfile.write(json.dumps({'goals': goals}).encode())# else:# self.send_error(404)# if __name__ == '__main__':# port = 7860# server = HTTPServer(('', port), MyHandler)# public_url = ngrok.connect(port).public_url# print(f" * ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"")# server.serve_forever()# herefrom http.server import HTTPServer, SimpleHTTPRequestHandlerimport osfrom mistralai.client import MistralClientfrom mistralai.models.chat_completion import ChatMessage148 unmodified linesself.send_error(404)if __name__ == '__main__':port = int(os.environ.get("PORT", 7860))server = HTTPServer(('0.0.0.0', port), MyHandler)print(f"Server running on port {port}")server.serve_forever()
app.py+166-5