Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify, send_file | |
| from flask_cors import CORS | |
| from fpdf import FPDF | |
| from docx import Document | |
| import openai | |
| import os | |
| import uuid | |
| app = Flask(__name__) | |
| CORS(app) | |
| client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) | |
| def generate(): | |
| try: | |
| data = request.json | |
| subject = data.get("category", "") | |
| citation = data.get("citationStyle", "") | |
| case_study = data.get("caseStudy", "") | |
| questions = data.get("questions", "") | |
| prompt = ( | |
| f"You are an academic writing assistant for university students. " | |
| f"Respond in Times New Roman, using university-level detail. Use the following:\n" | |
| f"- Subject: {subject}\n" | |
| f"- Citation Style: {citation}\n" | |
| f"- Case Study: {case_study}\n" | |
| f"- Questions: {questions}\n" | |
| f"Respond with a clear, structured academic answer using {citation} citation style. " | |
| f"Use credible university-grade sources with proper citations. " | |
| f"Do NOT add a conclusion unless asked. Only answer the questions." | |
| ) | |
| chat_response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=3000, | |
| temperature=0.7 | |
| ) | |
| result = chat_response.choices[0].message.content | |
| return jsonify({"response": result}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def export_pdf(): | |
| try: | |
| content = request.json.get("content", "") | |
| filename = f"/tmp/{uuid.uuid4().hex}.pdf" | |
| pdf = FPDF() | |
| pdf.add_page() | |
| pdf.set_auto_page_break(auto=True, margin=15) | |
| pdf.set_font("Times", size=12) | |
| for line in content.split("\n"): | |
| pdf.multi_cell(0, 10, line) | |
| pdf.output(filename) | |
| return send_file(filename, as_attachment=True) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def export_word(): | |
| try: | |
| content = request.json.get("content", "") | |
| filename = f"/tmp/{uuid.uuid4().hex}.docx" | |
| doc = Document() | |
| doc.styles["Normal"].font.name = "Times New Roman" | |
| for line in content.split("\n"): | |
| doc.add_paragraph(line) | |
| doc.save(filename) | |
| return send_file(filename, as_attachment=True) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def index(): | |
| return "✅ UniSolve backend is running. Visit via the proper frontend." | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) | |