kevinkal commited on
Commit
857a80e
·
verified ·
1 Parent(s): 5dc0dea

Update routers/powerpoint.py

Browse files
Files changed (1) hide show
  1. routers/powerpoint.py +0 -113
routers/powerpoint.py CHANGED
@@ -4,7 +4,6 @@ from pydantic import BaseModel
4
  from typing import Annotated, List, Literal, Optional, Union, Dict
5
  from google import genai
6
  from google.genai import types
7
- from mistralai import Mistral
8
  from auth import verify_token
9
  import os
10
  import tempfile
@@ -21,7 +20,6 @@ from collections import deque
21
  from threading import Lock
22
  import json
23
  from abc import ABC, abstractmethod
24
- import base64
25
 
26
  router = APIRouter(prefix="/powerpoint", tags=["powerpoint"])
27
 
@@ -29,10 +27,6 @@ router = APIRouter(prefix="/powerpoint", tags=["powerpoint"])
29
  gemini_key = os.environ.get('GEMINI_KEY', '')
30
  client = genai.Client(api_key=gemini_key)
31
 
32
- # Get Mistral client
33
- mistral_key = os.environ.get('MISTRAL_KEY', '')
34
- mistral_client = Mistral(api_key=mistral_key)
35
-
36
  class APIResponse(BaseModel):
37
  success: bool
38
  data: Optional[Union[Dict, List[Dict], str]] = None
@@ -49,10 +43,6 @@ class MultimodalModel(str, Enum):
49
  gemini_20_flash_lite = "gemini-2.0-flash-lite"
50
  gemini_25_pro = "gemini-2.5-pro"
51
 
52
- class MistralModel(str, Enum):
53
- mistral_small_latest = "mistral-small-latest"
54
- mistral_medium_latest = "mistral-medium-latest"
55
-
56
  class TemplateType(str, Enum):
57
  single_graph = "single_graph"
58
  two_column_graph = "two_column_graph"
@@ -562,109 +552,6 @@ async def image_to_pptx(
562
  except Exception as e:
563
  return APIResponse(success=False, error=f"Failed to generate presentation: {str(e)}")
564
 
565
- def get_mistral_json_schema(pydantic_model):
566
- """Convert Pydantic model to Mistral-compatible JSON schema"""
567
- schema = pydantic_model.model_json_schema()
568
-
569
- # Remove definitions and flatten the schema
570
- if "$defs" in schema:
571
- defs = schema.pop("$defs")
572
-
573
- def resolve_refs(obj):
574
- if isinstance(obj, dict):
575
- if "$ref" in obj:
576
- ref_path = obj["$ref"].split("/")[-1]
577
- if ref_path in defs:
578
- return resolve_refs(defs[ref_path])
579
- return obj
580
- else:
581
- return {k: resolve_refs(v) for k, v in obj.items()}
582
- elif isinstance(obj, list):
583
- return [resolve_refs(item) for item in obj]
584
- return obj
585
-
586
- schema = resolve_refs(schema)
587
-
588
- return schema
589
-
590
- @router.post("/mistral-image-to-pptx")
591
- async def mistral_image_to_pptx(
592
- token: Annotated[str, Depends(verify_token)],
593
- file: UploadFile = File(..., description="Image file to convert to PowerPoint"),
594
- template: TemplateType = Form(..., description="Template type to use for the presentation"),
595
- model: MistralModel = Form(..., description="Mistral model (mistral-small-latest or mistral-medium-latest)"),
596
- ):
597
- """
598
- Analyze an image with Mistral AI and generate a PowerPoint presentation based on the analysis using the selected template
599
- """
600
- try:
601
- # Get template generator
602
- template_generator = TEMPLATE_GENERATORS.get(template)
603
- if not template_generator:
604
- raise HTTPException(status_code=400, detail=f"Unsupported template: {template}")
605
-
606
- # Read uploaded file
607
- file_content = await file.read()
608
-
609
- # Convert image to base64 for Mistral
610
- image_base64 = base64.b64encode(file_content).decode('utf-8')
611
- image_url = f"data:{file.content_type};base64,{image_base64}"
612
-
613
- # Prepare messages for Mistral
614
- messages = [
615
- {
616
- "role": "user",
617
- "content": [
618
- {
619
- "type": "text",
620
- "text": template_generator.get_prompt()
621
- },
622
- {
623
- "type": "image_url",
624
- "image_url": image_url
625
- }
626
- ]
627
- }
628
- ]
629
-
630
- # Get JSON schema for response format
631
- response_schema = get_mistral_json_schema(template_generator.get_response_schema())
632
-
633
- # Send to Mistral
634
- response = mistral_client.chat.complete(
635
- model=model.value,
636
- messages=messages,
637
- response_format={
638
- "type": "json_object",
639
- "schema": response_schema
640
- }
641
- )
642
-
643
-
644
- # Display usage information
645
- if hasattr(response, 'usage'):
646
- print(f"Mistral usage: {response.usage}")
647
-
648
- # Parse the response
649
- response_text = response.choices[0].message.content
650
- print(response_text)
651
- presentation_data = template_generator.get_response_schema().model_validate(json.loads(response_text))
652
-
653
- # Generate PPTX file
654
- pptx_path = template_generator.generate_pptx(presentation_data)
655
-
656
- # Return file as download
657
- return FileResponse(
658
- path=pptx_path,
659
- filename=f"mistral_presentation_{template.value}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pptx",
660
- media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation"
661
- )
662
-
663
- except HTTPException:
664
- raise
665
- except Exception as e:
666
- return APIResponse(success=False, error=f"Failed to generate presentation with Mistral: {str(e)}")
667
-
668
  @router.get("/templates")
669
  async def get_available_templates(token: Annotated[str, Depends(verify_token)]):
670
  """Get list of available presentation templates"""
 
4
  from typing import Annotated, List, Literal, Optional, Union, Dict
5
  from google import genai
6
  from google.genai import types
 
7
  from auth import verify_token
8
  import os
9
  import tempfile
 
20
  from threading import Lock
21
  import json
22
  from abc import ABC, abstractmethod
 
23
 
24
  router = APIRouter(prefix="/powerpoint", tags=["powerpoint"])
25
 
 
27
  gemini_key = os.environ.get('GEMINI_KEY', '')
28
  client = genai.Client(api_key=gemini_key)
29
 
 
 
 
 
30
  class APIResponse(BaseModel):
31
  success: bool
32
  data: Optional[Union[Dict, List[Dict], str]] = None
 
43
  gemini_20_flash_lite = "gemini-2.0-flash-lite"
44
  gemini_25_pro = "gemini-2.5-pro"
45
 
 
 
 
 
46
  class TemplateType(str, Enum):
47
  single_graph = "single_graph"
48
  two_column_graph = "two_column_graph"
 
552
  except Exception as e:
553
  return APIResponse(success=False, error=f"Failed to generate presentation: {str(e)}")
554
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  @router.get("/templates")
556
  async def get_available_templates(token: Annotated[str, Depends(verify_token)]):
557
  """Get list of available presentation templates"""