Spaces:
Sleeping
Sleeping
| import os | |
| from flask import Flask, request, jsonify, render_template | |
| import PyPDF2 | |
| from openai import OpenAI | |
| # Crea la aplicaci贸n Flask, especificando la ruta de la carpeta de plantillas | |
| app = Flask(__name__, template_folder='.') | |
| # Lee la clave de API desde una variable de entorno | |
| client = OpenAI( | |
| api_key=os.environ.get("OPENAI_API_KEY"), | |
| ) | |
| def extract_text_from_file(file): | |
| # ... (tu c贸digo de la funci贸n extract_text_from_file) | |
| if file.filename.endswith('.pdf'): | |
| pdf_reader = PyPDF2.PdfReader(file) | |
| text = "" | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() | |
| return text | |
| elif file.filename.endswith('.txt'): | |
| return file.read().decode('utf-8') | |
| return "" | |
| def generate_summary_openai(text): | |
| # ... (tu c贸digo de la funci贸n generate_summary_openai) | |
| try: | |
| prompt_text = ( | |
| "Eres un asistente experto en resumir documentos. " | |
| "Genera un resumen del siguiente texto en 5 puntos clave, utilizando vi帽etas. " | |
| "Aseg煤rate de que cada punto sea conciso y capture una idea central." | |
| f"Texto: {text}" | |
| ) | |
| response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "system", "content": prompt_text} | |
| ], | |
| max_tokens=250, | |
| n=1, | |
| stop=None, | |
| temperature=0.7, | |
| ) | |
| summary_raw = response.choices[0].message.content.strip() | |
| summary_points = [line.strip() for line in summary_raw.split('\n') if line.strip()] | |
| return summary_points | |
| except Exception as e: | |
| print(f"Error al llamar a la API de OpenAI: {e}") | |
| return ["Error al generar el resumen. Por favor, verifica tu clave de API o intenta de nuevo."] | |
| def index(): | |
| return render_template('index.html') | |
| def summarize(): | |
| if 'file' not in request.files: | |
| return jsonify({'error': 'No se ha subido ning煤n archivo.'}), 400 | |
| file = request.files['file'] | |
| if file.filename == '': | |
| return jsonify({'error': 'No se ha seleccionado ning煤n archivo.'}), 400 | |
| try: | |
| raw_text = extract_text_from_file(file) | |
| if not raw_text: | |
| return jsonify({'error': 'No se pudo extraer texto del archivo.'}), 400 | |
| summary = generate_summary_openai(raw_text) | |
| return jsonify({'summary': summary}) | |
| except Exception as e: | |
| return jsonify({'error': str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(debug=True) |